-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathuser.py
More file actions
370 lines (326 loc) · 11.8 KB
/
Copy pathuser.py
File metadata and controls
370 lines (326 loc) · 11.8 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
from fastapi import APIRouter, Depends, Form, UploadFile, File, Request, HTTPException
from fastapi.responses import RedirectResponse, Response
from sqlmodel import Session, select, col
from typing import Optional, List
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import selectinload
import os
from utils.core.models import (
User,
UserAvatar,
AccountEmail,
DataIntegrityError,
Organization,
)
from utils.core.organizations import load_org_for_members_partial
from utils.core.auth import MAX_EMAILS_PER_ACCOUNT
from utils.core.dependencies import (
get_authenticated_user,
get_user_with_relations,
get_session,
)
from utils.core.images import (
validate_and_process_image,
MAX_FILE_SIZE,
MIN_DIMENSION,
MAX_DIMENSION,
ALLOWED_CONTENT_TYPES,
)
from utils.core.enums import ValidPermissions
from utils.app.enums import AppPermissions
from exceptions.http_exceptions import (
InsufficientPermissionsError,
UserNotFoundError,
OrganizationNotFoundError,
)
from routers.core.organization import router as organization_router
from utils.core.htmx import is_htmx_request, append_toast, toast_response
from utils.core.communication_preferences import (
parse_communication_preferences,
apply_communication_preferences,
)
router = APIRouter(prefix="/user", tags=["user"])
templates = Jinja2Templates(directory="templates")
# --- Routes ---
@router.get("/profile")
async def read_profile(
request: Request,
user: User = Depends(get_user_with_relations),
session: Session = Depends(get_session),
show_form: Optional[str] = "true",
):
# Load account emails
account_emails = (
session.exec(
select(AccountEmail)
.where(AccountEmail.account_id == user.account_id)
.order_by(col(AccountEmail.is_primary).desc())
).all()
if user.account_id
else []
)
return templates.TemplateResponse(
request,
"users/profile.html",
{
"show_form": show_form == "true",
"user": user,
"account_emails": account_emails,
"max_emails": MAX_EMAILS_PER_ACCOUNT,
"host_name": os.getenv("HOST_NAME", "our platform"),
},
)
@router.get("/edit-form")
async def edit_profile_form(
request: Request,
user: User = Depends(get_authenticated_user),
):
if not is_htmx_request(request):
return RedirectResponse(
url=router.url_path_for("read_profile"), status_code=303
)
return templates.TemplateResponse(
request,
"users/partials/profile_form.html",
{
"user": user,
"max_file_size_mb": MAX_FILE_SIZE / (1024 * 1024),
"min_dimension": MIN_DIMENSION,
"max_dimension": MAX_DIMENSION,
"allowed_formats": list(ALLOWED_CONTENT_TYPES.keys()),
},
)
@router.get("/profile-display")
async def profile_display(
request: Request,
user: User = Depends(get_authenticated_user),
):
if not is_htmx_request(request):
return RedirectResponse(
url=router.url_path_for("read_profile"), status_code=303
)
return templates.TemplateResponse(
request,
"users/partials/profile_display.html",
{"user": user},
)
@router.post("/update", response_class=RedirectResponse)
async def update_profile(
request: Request,
name: Optional[str] = Form(
None, strip_whitespace=True, title="Name", description="Updated display name"
),
avatar_file: Optional[UploadFile] = File(None),
user: User = Depends(get_authenticated_user),
session: Session = Depends(get_session),
):
avatar_changed = bool(avatar_file and avatar_file.filename)
# Handle avatar update
if avatar_changed:
assert avatar_file is not None
avatar_data = await avatar_file.read()
avatar_content_type = avatar_file.content_type
processed_image, content_type = validate_and_process_image(
avatar_data, avatar_content_type
)
if user.avatar:
user.avatar.avatar_data = processed_image
user.avatar.avatar_content_type = content_type
else:
assert user.id is not None
user.avatar = UserAvatar(
user_id=user.id,
avatar_data=processed_image,
avatar_content_type=content_type,
)
# Update user details
user.name = name
session.commit()
session.refresh(user)
if is_htmx_request(request):
response = templates.TemplateResponse(
request,
"users/partials/profile_display.html",
{"user": user},
)
if avatar_changed:
# Avatar also appears in the navbar — append an OOB swap for it.
navbar_html = bytes(
templates.TemplateResponse(
request,
"base/partials/navbar_avatar_oob.html",
{"user": user},
).body
).decode()
original = bytes(response.body).decode()
response.body = (original + navbar_html).encode()
response.headers["content-length"] = str(len(response.body))
return append_toast(
response, request, templates, "Profile updated successfully."
)
return RedirectResponse(url=router.url_path_for("read_profile"), status_code=303)
@router.post("/communication-preferences", response_class=RedirectResponse)
async def update_communication_preferences(
request: Request,
comm_opt_in: Optional[str] = Form(None),
comm_updates: Optional[str] = Form(None),
comm_marketing: Optional[str] = Form(None),
user: User = Depends(get_authenticated_user),
session: Session = Depends(get_session),
) -> Response:
apply_communication_preferences(
user,
parse_communication_preferences(comm_opt_in, comm_updates, comm_marketing),
)
session.commit()
session.refresh(user)
if is_htmx_request(request):
return toast_response(
request,
templates,
"Communication preferences updated.",
)
return RedirectResponse(url=router.url_path_for("read_profile"), status_code=303)
@router.get("/avatar")
async def get_avatar(user: User = Depends(get_authenticated_user)):
"""Serve avatar image from database"""
if not user.avatar:
raise DataIntegrityError(resource="User avatar")
return Response(
content=user.avatar.avatar_data, media_type=user.avatar.avatar_content_type
)
@router.post("/role/update", response_class=RedirectResponse)
def update_user_role(
request: Request,
user_id: int = Form(
..., title="User ID", description="ID of the user whose roles are being updated"
),
organization_id: int = Form(
..., title="Organization ID", description="ID of the organization"
),
roles: Optional[List[int]] = Form(
None, title="Role IDs", description="List of role IDs to assign to the user"
),
user: User = Depends(get_authenticated_user),
session: Session = Depends(get_session),
) -> Response:
"""Update the roles of a user in an organization"""
# Check if the current user has permission to edit user roles
if not user.has_permission(ValidPermissions.EDIT_USER_ROLE, organization_id):
raise InsufficientPermissionsError()
# Find the organization
organization = session.exec(
select(Organization)
.where(Organization.id == organization_id)
.options(selectinload(Organization.roles))
).first()
if not organization:
raise OrganizationNotFoundError()
# Find the target user
target_user = session.exec(
select(User).where(User.id == user_id).options(selectinload(User.roles))
).first()
if not target_user:
raise UserNotFoundError()
# Get all roles for this organization
org_roles = {role.id: role for role in organization.roles}
# Remove all current organization roles from the user
for role in list(target_user.roles):
if role.organization_id == organization_id:
target_user.roles.remove(role)
# Add selected roles to the user
if roles:
for role_id in roles:
fetched_role = org_roles.get(role_id)
if fetched_role is not None:
target_user.roles.append(fetched_role)
session.commit()
if is_htmx_request(request):
organization, user_permissions, pending_invitations = (
load_org_for_members_partial(session, organization_id, user)
)
response = templates.TemplateResponse(
request,
"organization/partials/members_table.html",
{
"organization": organization,
"pending_invitations": pending_invitations,
"user": user,
"user_permissions": user_permissions,
"ValidPermissions": ValidPermissions,
"all_permissions": list(ValidPermissions) + list(AppPermissions),
},
)
response.headers["HX-Trigger"] = "modalDismiss"
return append_toast(
response, request, templates, "User role updated successfully."
)
return RedirectResponse(
url=organization_router.url_path_for(
"read_organization", org_id=organization_id
),
status_code=303,
)
@router.post("/organization/remove", response_class=RedirectResponse)
def remove_user_from_organization(
request: Request,
user_id: int = Form(..., title="User ID", description="ID of the user to remove"),
organization_id: int = Form(
...,
title="Organization ID",
description="ID of the organization to remove the user from",
),
user: User = Depends(get_authenticated_user),
session: Session = Depends(get_session),
) -> Response:
"""Remove a user from an organization by removing all their roles in that organization"""
# Check if the current user has permission to remove users
if not user.has_permission(ValidPermissions.REMOVE_USER, organization_id):
raise InsufficientPermissionsError()
# Find the organization
organization = session.exec(
select(Organization).where(Organization.id == organization_id)
).first()
if not organization:
raise OrganizationNotFoundError()
# Find the target user
target_user = session.exec(
select(User).where(User.id == user_id).options(selectinload(User.roles))
).first()
if not target_user:
raise UserNotFoundError()
# Prevent removing oneself
if target_user.id == user.id:
raise HTTPException(
status_code=400, detail="You cannot remove yourself from the organization"
)
# Remove all organization roles from the user
for role in list(target_user.roles):
if role.organization_id == organization_id:
target_user.roles.remove(role)
session.commit()
if is_htmx_request(request):
organization, user_permissions, pending_invitations = (
load_org_for_members_partial(session, organization_id, user)
)
response = templates.TemplateResponse(
request,
"organization/partials/members_table.html",
{
"organization": organization,
"pending_invitations": pending_invitations,
"user": user,
"user_permissions": user_permissions,
"ValidPermissions": ValidPermissions,
"all_permissions": list(ValidPermissions) + list(AppPermissions),
},
)
return append_toast(
response, request, templates, "User removed from organization."
)
return RedirectResponse(
url=organization_router.url_path_for(
"read_organization", org_id=organization_id
),
status_code=303,
)