-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path__init__.py
281 lines (224 loc) · 9.39 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""FastAPI Users database adapter for SQLAlchemy."""
import uuid
from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, Type
from fastapi_users.db.base import BaseUserDatabase
from fastapi_users.models import ID, OAP, UP
from sqlalchemy import Boolean, ForeignKey, Integer, String, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, Session, declared_attr, mapped_column
from sqlalchemy.sql import Select
from fastapi_users_db_sqlalchemy.generics import GUID
__version__ = "6.0.0"
UUID_ID = uuid.UUID
class SQLAlchemyBaseUserTable(Generic[ID]):
"""Base SQLAlchemy users table definition."""
__tablename__ = "user"
if TYPE_CHECKING: # pragma: no cover
id: ID
email: str
hashed_password: str
is_active: bool
is_superuser: bool
is_verified: bool
else:
email: Mapped[str] = mapped_column(
String(length=320), unique=True, index=True, nullable=False
)
hashed_password: Mapped[str] = mapped_column(
String(length=1024), nullable=False
)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
is_superuser: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False
)
is_verified: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False
)
class SQLAlchemyBaseUserTableUUID(SQLAlchemyBaseUserTable[UUID_ID]):
if TYPE_CHECKING: # pragma: no cover
id: UUID_ID
else:
id: Mapped[UUID_ID] = mapped_column(GUID, primary_key=True, default=uuid.uuid4)
class SQLAlchemyBaseOAuthAccountTable(Generic[ID]):
"""Base SQLAlchemy OAuth account table definition."""
__tablename__ = "oauth_account"
if TYPE_CHECKING: # pragma: no cover
id: ID
oauth_name: str
access_token: str
expires_at: Optional[int]
refresh_token: Optional[str]
account_id: str
account_email: str
else:
oauth_name: Mapped[str] = mapped_column(
String(length=100), index=True, nullable=False
)
access_token: Mapped[str] = mapped_column(String(length=1024), nullable=False)
expires_at: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
refresh_token: Mapped[Optional[str]] = mapped_column(
String(length=1024), nullable=True
)
account_id: Mapped[str] = mapped_column(
String(length=320), index=True, nullable=False
)
account_email: Mapped[str] = mapped_column(String(length=320), nullable=False)
class SQLAlchemyBaseOAuthAccountTableUUID(SQLAlchemyBaseOAuthAccountTable[UUID_ID]):
if TYPE_CHECKING: # pragma: no cover
id: UUID_ID
user_id: UUID_ID
else:
id: Mapped[UUID_ID] = mapped_column(GUID, primary_key=True, default=uuid.uuid4)
@declared_attr
def user_id(cls) -> Mapped[GUID]:
return mapped_column(
GUID, ForeignKey("user.id", ondelete="cascade"), nullable=False
)
class SQLAlchemyUserDatabase(Generic[UP, ID], BaseUserDatabase[UP, ID]):
"""
Database adapter for SQLAlchemy.
:param session: SQLAlchemy session instance.
:param user_table: SQLAlchemy user model.
:param oauth_account_table: Optional SQLAlchemy OAuth accounts model.
"""
session: AsyncSession
user_table: Type[UP]
oauth_account_table: Optional[Type[SQLAlchemyBaseOAuthAccountTable]]
def __init__(
self,
session: AsyncSession,
user_table: Type[UP],
oauth_account_table: Optional[Type[SQLAlchemyBaseOAuthAccountTable]] = None,
):
self.session = session
self.user_table = user_table
self.oauth_account_table = oauth_account_table
async def get(self, id: ID) -> Optional[UP]:
statement = select(self.user_table).where(self.user_table.id == id)
return await self._get_user(statement)
async def get_by_email(self, email: str) -> Optional[UP]:
statement = select(self.user_table).where(
func.lower(self.user_table.email) == func.lower(email)
)
return await self._get_user(statement)
async def get_by_oauth_account(self, oauth: str, account_id: str) -> Optional[UP]:
if self.oauth_account_table is None:
raise NotImplementedError()
statement = (
select(self.user_table)
.join(self.oauth_account_table)
.where(self.oauth_account_table.oauth_name == oauth) # type: ignore
.where(self.oauth_account_table.account_id == account_id) # type: ignore
)
return await self._get_user(statement)
async def create(self, create_dict: Dict[str, Any]) -> UP:
user = self.user_table(**create_dict)
self.session.add(user)
await self.session.commit()
return user
async def update(self, user: UP, update_dict: Dict[str, Any]) -> UP:
for key, value in update_dict.items():
setattr(user, key, value)
self.session.add(user)
await self.session.commit()
return user
async def delete(self, user: UP) -> None:
await self.session.delete(user)
await self.session.commit()
async def add_oauth_account(self, user: UP, create_dict: Dict[str, Any]) -> UP:
if self.oauth_account_table is None:
raise NotImplementedError()
await self.session.refresh(user)
oauth_account = self.oauth_account_table(**create_dict)
self.session.add(oauth_account)
user.oauth_accounts.append(oauth_account) # type: ignore
self.session.add(user)
await self.session.commit()
return user
async def update_oauth_account(
self, user: UP, oauth_account: OAP, update_dict: Dict[str, Any]
) -> UP:
if self.oauth_account_table is None:
raise NotImplementedError()
for key, value in update_dict.items():
setattr(oauth_account, key, value)
self.session.add(oauth_account)
await self.session.commit()
return user
async def _get_user(self, statement: Select) -> Optional[UP]:
results = await self.session.execute(statement)
return results.unique().scalar_one_or_none()
class SQLAlchemySynchronousUserDatabase(Generic[UP, ID], BaseUserDatabase[UP, ID]):
"""
Database adapter for SQLAlchemy with synchronous session support.
:param session: SQLAlchemy session instance.
:param user_table: SQLAlchemy user model.
:param oauth_account_table: Optional SQLAlchemy OAuth accounts model.
"""
session: Session
user_table: Type[UP]
oauth_account_table: Optional[Type[SQLAlchemyBaseOAuthAccountTable]]
def __init__(
self,
session: Session,
user_table: Type[UP],
oauth_account_table: Optional[Type[SQLAlchemyBaseOAuthAccountTable]] = None,
):
self.session = session
self.user_table = user_table
self.oauth_account_table = oauth_account_table
async def get(self, id: ID) -> Optional[UP]:
statement = select(self.user_table).where(self.user_table.id == id)
return await self._get_user(statement)
async def get_by_email(self, email: str) -> Optional[UP]:
statement = select(self.user_table).where(
func.lower(self.user_table.email) == func.lower(email)
)
return await self._get_user(statement)
async def get_by_oauth_account(self, oauth: str, account_id: str) -> Optional[UP]:
if self.oauth_account_table is None:
raise NotImplementedError()
statement = (
select(self.user_table)
.join(self.oauth_account_table)
.where(self.oauth_account_table.oauth_name == oauth) # type: ignore
.where(self.oauth_account_table.account_id == account_id) # type: ignore
)
return await self._get_user(statement)
async def create(self, create_dict: Dict[str, Any]) -> UP:
user = self.user_table(**create_dict)
self.session.add(user)
self.session.commit()
return user
async def update(self, user: UP, update_dict: Dict[str, Any]) -> UP:
for key, value in update_dict.items():
setattr(user, key, value)
self.session.add(user)
self.session.commit()
return user
async def delete(self, user: UP) -> None:
self.session.delete(user)
self.session.commit()
async def add_oauth_account(self, user: UP, create_dict: Dict[str, Any]) -> UP:
if self.oauth_account_table is None:
raise NotImplementedError()
self.session.refresh(user)
oauth_account = self.oauth_account_table(**create_dict)
self.session.add(oauth_account)
user.oauth_accounts.append(oauth_account) # type: ignore
self.session.add(user)
self.session.commit()
return user
async def update_oauth_account(
self, user: UP, oauth_account: OAP, update_dict: Dict[str, Any]
) -> UP:
if self.oauth_account_table is None:
raise NotImplementedError()
for key, value in update_dict.items():
setattr(oauth_account, key, value)
self.session.add(oauth_account)
self.session.commit()
return user
async def _get_user(self, statement: Select) -> Optional[UP]:
results = self.session.execute(statement)
return results.unique().scalar_one_or_none()