Skip to content

Commit 57eedd0

Browse files
param dict deletion (#181)
1 parent b17d6a5 commit 57eedd0

18 files changed

Lines changed: 140 additions & 424 deletions

File tree

auth_backend/auth_plugins/auth_method.py

Lines changed: 1 addition & 138 deletions
Original file line numberDiff line numberDiff line change
@@ -42,148 +42,11 @@ class Session(Base):
4242
AUTH_METHODS: dict[str, type[AuthMethodMeta]] = {}
4343

4444

45-
class MethodMeta(metaclass=ABCMeta):
46-
"""Параметры метода аввторизации пользователя
47-
Args:
48-
`__fields__: frozenset - required` - множество параметров данного метода авторизации
49-
50-
`__required_fields__: frozenset - required` - множество обязательных парамтеров данного метода авторизации
51-
52-
`__auth_method__: str - required` - __repr__ соотвествуещго метода авторизации
53-
54-
Пример:
55-
```
56-
class YourAuthParams(MethodMeta):
57-
__auth_method__ = "your_auth" ##YourAuth.__repr__ === "your_auth"
58-
59-
__fields__ = frozenset(frozenset(("very_important_field", "not_important_field",))("very_important_field", "not_important_field",))
60-
61-
__required_fields__ = frozenset(("very_important_field",))
62-
```
63-
"""
64-
65-
__auth_method__: str = None
66-
67-
__fields__ = frozenset()
68-
__required_fields__ = frozenset()
69-
__user: User
70-
71-
def __init__(self, user: User, methods: list[AuthMethod] = None):
72-
assert self.__fields__ and self.__required_fields__, "__fields__ or __required_fields__ not defined"
73-
if methods is None:
74-
methods = []
75-
self.__user = user
76-
for method in methods:
77-
assert method.param in self.__fields__
78-
setattr(self, method.param, method)
79-
80-
async def create(self, param: str, value: str) -> AuthMethod:
81-
"""
82-
Создает AuthMethod у данного юзера, auth_method берется из
83-
self.__auth_method__
84-
85-
Args:
86-
param: str - параметр AuthMethod
87-
88-
value: str - значение, которое будет задано по этому параметру
89-
90-
Returns:
91-
AuthMethod - созданный метод
92-
93-
Raises:
94-
AssertionError - если param не нахяодятся в __fields__
95-
96-
AlreadyExists - если метод по такому ключу уже существует
97-
98-
Пример:
99-
```
100-
user.auth_methods.email.create("email", value)
101-
```
102-
"""
103-
assert param in self.__fields__, "You cant create auth_method which not declared in __fields__"
104-
if (attr := getattr(self, param)) and getattr(attr, "is_deleted") is not True:
105-
raise AlreadyExists(AuthMethod, attr.id)
106-
_method = AuthMethod(
107-
user_id=self.__user.id, param=param, value=value, auth_method=self.__class__.get_auth_method_name()
108-
)
109-
assert param in self.__fields__, "You cant create auth_method which not daclared"
110-
db.session.add(_method)
111-
db.session.flush()
112-
db.session.refresh(self.__user)
113-
setattr(self, param, _method)
114-
return _method
115-
116-
async def bulk_create(self, map: dict[str, str]) -> list[AuthMethod]:
117-
"""Создает несколько AuthMethod'ов по мапе param-value,
118-
auth_method берется из self.__auth_method__
119-
120-
Args:
121-
map: dict[str, str] - словарь, по которому будуут создаваться AuthMthods
122-
123-
Returns:
124-
list[AuthMethod] - созданные методы
125-
126-
Raises:
127-
AssertionError - если ключи словаря не нахяодятся в ___fields__
128-
129-
AlreadyExists - если метод по такому ключу уже существует
130-
131-
Пример:
132-
```
133-
user.auth_method.email.bulk_create({"email": val1, "salt": val2})
134-
```
135-
"""
136-
for k in map.keys():
137-
assert k in self.__fields__, "You cant create auth_method which not declared in __fields__"
138-
if (attr := getattr(self, k)) and getattr(attr, "is_deleted") is not True:
139-
raise AlreadyExists(AuthMethod, attr.id)
140-
methods: list[AuthMethod] = []
141-
for k, v in map.items():
142-
methods.append(
143-
method := AuthMethod(
144-
user_id=self.__user.id, param=k, value=v, auth_method=self.__class__.get_auth_method_name()
145-
)
146-
)
147-
db.session.add(method)
148-
db.session.flush()
149-
db.session.refresh(self.__user)
150-
return methods
151-
152-
def __bool__(self) -> bool:
153-
"""Определен ли для польщователя этот метод аутентификации
154-
Args:
155-
None
156-
Returns:
157-
Если у юзера удалено/не определено хотя бы одно из полей из
158-
__required_fields__ -> False, иначе True
159-
160-
"""
161-
for field in self.__required_fields__:
162-
if not getattr(self, field):
163-
return False
164-
return True
165-
166-
@classmethod
167-
def get_auth_method_name(cls) -> str:
168-
"""Имя соответствующего метода аутентфикации
169-
170-
Args:
171-
None
172-
173-
Returns:
174-
Имя метода аутентификации, к которому
175-
приилагается данный класс
176-
"""
177-
return re.sub(r"(?<!^)(?=[A-Z])", "_", cls.__auth_method__).lower()
178-
179-
18045
class AuthMethodMeta(metaclass=ABCMeta):
18146
router: APIRouter
18247
prefix: str
18348
tags: list[str] = []
18449

185-
fields: type[AuthMethodMeta] = MethodMeta
186-
18750
@classmethod
18851
def get_name(cls) -> str:
18952
return re.sub(r"(?<!^)(?=[A-Z])", "_", cls.__name__).lower()
@@ -225,7 +88,7 @@ def generate_kafka_key(user_id: int) -> UserLoginKey:
22588

22689
@staticmethod
22790
async def _create_session(
228-
user: User, scopes_list_names: list[TypeScope] | None, session_name: str = None, *, db_session: DbSession
91+
user: User, scopes_list_names: list[TypeScope] | None, session_name: str | None = None, *, db_session: DbSession
22992
) -> Session:
23093
"""Создает сессию пользователя"""
23194
return await create_session(user, scopes_list_names, db_session=db_session, session_name=session_name)

0 commit comments

Comments
 (0)