Skip to content

Commit 1fb47b0

Browse files
authored
feat: Allow using 'allow_origin_regex' configuration
2 parents e8244d6 + 3d927c1 commit 1fb47b0

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

fastapi_sio/utils.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
from typing import Any
22
from fastapi import FastAPI
33
from fastapi.middleware.cors import CORSMiddleware
4+
import re
5+
6+
7+
def match_origin(origin: str | None, pattern: str) -> bool:
8+
"""
9+
Matches origin against a pattern.
10+
"""
11+
return origin is not None and re.match(pattern, origin) is not None
12+
413

514

615
def find_cors_configuration(app: FastAPI, default: Any) -> Any:
@@ -14,11 +23,14 @@ def find_cors_configuration(app: FastAPI, default: Any) -> Any:
1423
continue
1524

1625
origins = middleware.options.get("allow_origins")
17-
18-
# Incompatibility fix between CORSMiddleware and python-socketio
19-
if origins == ["*"]:
20-
origins = "*"
26+
if origins:
27+
# Incompatibility fix between CORSMiddleware and python-socketio
28+
if origins == ["*"]:
29+
origins = "*"
30+
return origins
2131

22-
return origins
32+
origins_regex = middleware.options.get("allow_origin_regex")
33+
if origins_regex:
34+
return lambda origin: match_origin(origin, origins_regex)
2335

2436
return default

0 commit comments

Comments
 (0)