-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepository.py
More file actions
292 lines (244 loc) · 9.98 KB
/
Copy pathrepository.py
File metadata and controls
292 lines (244 loc) · 9.98 KB
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
282
283
284
285
286
287
288
289
290
291
292
from typing import Any, cast
from uuid import UUID
from sqlalchemy import delete, select, text, update
from sqlalchemy.exc import IntegrityError
from sqlmodel.ext.asyncio.session import AsyncSession
from api.core.exceptions import AlreadyExistsException, NotFoundException
from api.core.security import UserInfo
from api.src.workspaces.schemas import (
QuestDefinitionType,
User,
Workspace,
WorkspaceImagery,
WorkspaceLongQuest,
WorkspaceUserRole,
WorkspaceUserRoleType,
)
class WorkspaceRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def create(
self, current_user: UserInfo, workspace_data: dict[str, Any]
) -> Workspace:
workspace = Workspace(
**workspace_data,
createdBy=current_user.user_uuid, # type: ignore[reportArgumentType]
createdByName=current_user.user_name,
)
try:
if workspace.tdeiProjectGroupId not in current_user.getProjectGroupIds():
raise ValueError(
"User does not have permissions to create a workspace in that project group."
)
self.session.add(workspace)
await self.session.commit()
await self.session.refresh(workspace)
return workspace
except IntegrityError:
await self.session.rollback()
raise AlreadyExistsException(
f"Workspace with ID {workspace.id} already exists"
)
async def getById(self, current_user: UserInfo, workspace_id: int) -> Workspace:
query = select(Workspace).where(
(Workspace.id == workspace_id)
& (Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds())) # type: ignore[attr-defined]
)
result = await self.session.execute(query)
workspace = result.scalar_one_or_none()
if not workspace:
raise NotFoundException(f"Workspace with id {workspace_id} not found")
return workspace
async def getAll(self, current_user: UserInfo) -> list[Workspace]:
query = select(Workspace).where(
Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds()) # type: ignore[attr-defined]
)
result = await self.session.execute(query)
return list(result.scalars().all())
async def update(
self,
current_user: UserInfo,
workspace_id: int,
workspace_data: dict[str, Any],
) -> Workspace:
query = (
update(Workspace)
.where(
(Workspace.id == workspace_id)
& (Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds())) # type: ignore[attr-defined]
)
.values(**workspace_data)
)
result = await self.session.execute(query)
if result.rowcount != 1: # type: ignore[attr-defined]
raise NotFoundException(f"Update failed for workspace id {workspace_id}")
await self.session.commit()
return await self.getById(current_user, workspace_id)
async def createLongformQuest(
self,
current_user: UserInfo,
workspace_id: int,
longform_quest_data: dict[str, Any],
) -> Workspace | None:
query = select(Workspace).where(
(Workspace.id == workspace_id)
& (Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds())) # type: ignore[attr-defined]
)
result = await self.session.execute(query)
workspace = result.scalar_one_or_none()
if workspace:
workspace.longFormQuestDef = WorkspaceLongQuest(
**longform_quest_data,
modifiedBy=current_user.user_uuid, # type: ignore[reportArgumentType]
modifiedByName=current_user.user_name,
workspace_id=workspace_id,
)
await self.session.commit()
await self.session.refresh(workspace)
return workspace
async def updateLongformQuest(
self,
current_user: UserInfo,
workspace_id: int,
longform_quest_data: dict[str, Any],
) -> Workspace:
update_data = longform_quest_data
update_data["modifiedBy"] = current_user.user_uuid
update_data["modifiedByName"] = current_user.user_name
quest_type = longform_quest_data.get("type")
update_data["type"] = QuestDefinitionType[
quest_type.name if quest_type else "NONE"
].value
query = (
update(WorkspaceLongQuest)
.values(**update_data)
.where(WorkspaceLongQuest.workspace_id == workspace_id) # type: ignore[reportArgumentType]
)
result = await self.session.execute(query)
if result.rowcount == 0: # type: ignore[attr-defined]
raise NotFoundException(f"Workspace with id {workspace_id} not found")
await self.session.commit()
return await self.getById(current_user, workspace_id)
async def createImageryDef(
self,
current_user: UserInfo,
workspace_id: int,
imagery_def_data: dict[str, Any],
) -> Workspace | None:
query = select(Workspace).where(
(Workspace.id == workspace_id)
& (Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds())) # type: ignore[attr-defined]
)
result = await self.session.execute(query)
workspace = result.scalar_one_or_none()
if workspace:
workspace.imageryListDef = WorkspaceImagery(
**imagery_def_data,
modifiedBy=current_user.user_uuid, # type: ignore[reportArgumentType]
modifiedByName=current_user.user_name,
workspace_id=workspace_id,
)
await self.session.commit()
await self.session.refresh(workspace)
return workspace
async def updateImageryDef(
self,
current_user: UserInfo,
workspace_id: int,
imagery_def_data: dict[str, Any],
) -> Workspace:
update_data = imagery_def_data
update_data["modifiedBy"] = current_user.user_uuid
update_data["modifiedByName"] = current_user.user_name
query = (
update(WorkspaceImagery)
.values(**update_data)
.where(WorkspaceImagery.workspace_id == workspace_id) # type: ignore[reportArgumentType]
)
result = await self.session.execute(query)
if result.rowcount != 1: # type: ignore[attr-defined]
raise NotFoundException(f"Update failed for workspace id {workspace_id}")
await self.session.commit()
return await self.getById(current_user, workspace_id)
async def delete(self, current_user: UserInfo, workspace_id: int) -> None:
query = delete(Workspace).where(
(Workspace.id == workspace_id)
& (Workspace.tdeiProjectGroupId.in_(current_user.getProjectGroupIds())) # type: ignore[attr-defined]
)
result = await self.session.execute(query)
if result.rowcount != 1: # type: ignore[attr-defined]
raise NotFoundException(f"Workspace delete failed for id {workspace_id}")
await self.session.commit()
class OSMRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def getWorkspaceBBox(
self,
current_user: UserInfo,
workspace_id: int,
):
# Postgres does not support parameter binding for `SET search_path`, so
# workspace_id is interpolated directly. The explicit int() cast guards
# against SQL injection if this method is ever called from outside of a
# FastAPI path handler (where the type annotation acts as a safeguard).
#
await self.session.execute(
text(f"SET search_path TO 'workspace-{int(workspace_id)}', public")
)
sql_query = text(
"select MAX(latitude) AS max_lat, MAX(longitude) AS max_lon, \
MIN(latitude) AS min_lat, MIN(longitude) AS min_lon from nodes"
)
result = await self.session.execute(sql_query)
retVal = result.mappings().first()
if retVal is None:
raise NotFoundException(f"Workspace with id {workspace_id} not found")
return retVal
async def getAllUsers(
self,
):
query = select(User)
result = await self.session.execute(query)
return list(result.scalars().all())
async def get_current_user(self, current_user: UserInfo) -> User:
result = await self.session.exec(
select(User).where(User.auth_uid == str(current_user.user_uuid))
)
# Current user should exist--throw if it doesn't:
return result.scalar_one()
async def addUserToWorkspaceWithRole(
self,
current_user: UserInfo,
workspace_id: int,
user_id: UUID,
role: WorkspaceUserRoleType,
) -> None:
userRole = WorkspaceUserRole(
auth_user_uid=cast(UUID, user_id),
workspace_id=workspace_id,
role=role,
)
try:
self.session.add(userRole)
await self.session.commit()
except IntegrityError:
await self.session.rollback()
raise AlreadyExistsException(
"User association with that workspace already exists"
)
async def removeUserFromWorkspace(
self,
current_user: UserInfo,
workspace_id: int,
user_id: UUID,
) -> None:
query = delete(WorkspaceUserRole).where(
(WorkspaceUserRole.workspace_id == workspace_id) # type: ignore[reportArgumentType]
& (WorkspaceUserRole.auth_user_uid == user_id)
)
result = await self.session.execute(query)
if result.rowcount != 1: # type: ignore[attr-defined]
raise NotFoundException(
f"User association removal failed for workspace {workspace_id} and user {user_id}"
)
await self.session.commit()