-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathorganization.py
More file actions
503 lines (423 loc) · 17.5 KB
/
organization.py
File metadata and controls
503 lines (423 loc) · 17.5 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import json
from fastapi import APIRouter, Request, Body, HTTPException
from fast_api.models import (
AddUserToOrganizationBody,
ArchiveAdminMessageBody,
ChangeOrganizationBody,
ChangeUserRoleBody,
CreateAdminMessageBody,
CreateOrganizationBody,
CreateUpdateCrossSellingBody,
CreateUpdateReleaseNotificationBody,
DeleteOrganizationBody,
DeleteUserBody,
MappedSortedPaginatedUsers,
MissingUsersBody,
RemoveUserToOrganizationBody,
UpdateOneDriveFieldRequest,
UpdateSettingsRequest,
)
from controller.auth import manager as auth_manager
from controller.auth import kratos
from controller.auth.kratos import (
resolve_user_mail_by_id,
resolve_user_name_by_id,
)
from controller.organization import manager
from controller.admin_message import manager as admin_message_manager
from controller.organization import manager as organization_manager
from controller.user import manager as user_manager
from controller.cross_selling import manager as cross_selling_manager
from fast_api.routes.client_response import get_silent_success, pack_json_result
from submodules.model.business_objects import organization, release_notification, user
from submodules.model.exceptions import EntityNotFoundException
from submodules.model.util import sql_alchemy_to_dict
from util import notification
router = APIRouter()
ACTIVE_ADMIN_MESSAGES_WHITELIST = {
"archive_date",
"created_at",
"id",
"level",
"text",
"scheduled_date",
}
USER_INFO_WHITELIST = {
"id",
"organization_id",
"role",
"language_display",
"email",
"use_new_cognition_ui",
"auto_logout_minutes",
"one_drive_path",
"sound_settings",
"notification_settings",
"is_light_user",
"use_chat_auto_scroll",
}
USER_INFO_RENAME_MAP = {"email": "mail"}
ALL_ORGANIZATIONS_WHITELIST = {
"id",
"name",
"created_at",
"started_at",
"is_paying",
"cross_selling_id",
"max_rows",
"max_cols",
"max_char_count",
"log_admin_requests",
"conversation_lifespan_days",
"file_lifespan_days",
"token_limit",
"light_user_config",
}
CROSS_SELLING_WHITELIST = {"id", "name", "created_at"}
RELEASE_NOTIFICATIONS_WHITELIST = {"id", "link", "config"}
# in use refinery-ui (07.01.25)
@router.get("")
def get_organization(request: Request):
user = auth_manager.get_user_by_info(request.state.info)
return pack_json_result(manager.get_organization_by_id(user.organization_id))
# in use refinery-ui (07.01.25)
@router.get("/overview-stats")
def get_overview_stats(request: Request):
org_id = str(auth_manager.get_user_by_info(request.state.info).organization_id)
return pack_json_result(manager.get_overview_stats(org_id), wrap_for_frontend=False)
# in use refinery-ui (07.01.25)
@router.get("/user-info")
def get_user_info(request: Request):
user = auth_manager.get_user_by_info(request.state.info)
return pack_json_result(manager.get_user_info(user), wrap_for_frontend=False)
# in use cognition-ui & admin dashboard (07.01.25)
@router.get("/get-user-info-extended")
def get_user_info_extended(request: Request):
user = auth_manager.get_user_by_info(request.state.info)
kratos.__refresh_identity_cache()
name = resolve_user_name_by_id(user.id)
user_dict = {
**sql_alchemy_to_dict(
user,
column_whitelist=USER_INFO_WHITELIST,
column_rename_map=USER_INFO_RENAME_MAP,
),
"first_name": name.get("first") if name else None,
"last_name": name.get("last") if name else None,
"light_user_config": None,
"messages_created_today": None,
"messages_created_this_month": None,
}
if user.is_light_user:
org = organization.get(user.organization_id)
if org and org.light_user_config and org.light_user_config.get("is_active"):
user_dict["light_user_config"] = org.light_user_config
user_dict["messages_created_today"] = user.messages_created_today
user_dict["messages_created_this_month"] = user.messages_created_this_month
return pack_json_result(user_dict)
# in use admin dashboard (08.01.25)
@router.get("/org-id-name-map")
def get_org_id_name_map(request: Request):
auth_manager.check_admin_access(request.state)
return pack_json_result(
organization.get_org_id_to_name_map(), wrap_for_frontend=False
)
# in use cognition-ui & refinery-ui (08.01.25)
@router.get("/all-users")
def get_all_user(
request: Request,
include_engineers: bool = False,
include_admins: bool = False,
limited_teams: bool = False,
org_id: str = None,
):
relevant_users = []
user_is_admin = request.state.adm.is_admin
if org_id:
if not user_is_admin:
raise HTTPException(status_code=403, detail="Not authorized")
relevant_users = manager.get_all_users(org_id)
else:
user_info = auth_manager.get_user_by_info(request.state.info)
if not user_info.organization_id:
return pack_json_result([], wrap_for_frontend=False)
relevant_users = manager.get_all_users(
user_info.organization_id, limited_teams=limited_teams, user_id=user_info.id
)
if include_admins:
admin_support_users = user_manager.get_admin_users(expand_mail_name=True)
relevant_users.extend(admin_support_users)
if include_engineers:
engineer_users = user_manager.get_engineer_users(
org_id=user_info.organization_id, expand_mail_name=True
)
relevant_users.extend(engineer_users)
# Remove duplicates by user id
unique_users = {str(user["id"]): user for user in relevant_users}.values()
return pack_json_result(list(unique_users), wrap_for_frontend=False)
# in use cognition-ui & refinery-ui & admin-dashboard (08.01.25)
@router.get("/all-active-admin-messages")
def all_active_admin_messages(request: Request, limit: int = 100) -> str:
data = admin_message_manager.get_messages(limit, active_only=True)
data_dict = sql_alchemy_to_dict(
data, column_whitelist=ACTIVE_ADMIN_MESSAGES_WHITELIST
)
return pack_json_result(data_dict)
# in use admin-dashboard (08.01.25)
@router.get("/all-admin-messages")
def all_admin_messages(request: Request, limit: int = 100) -> str:
auth_manager.check_admin_access(request.state)
data = admin_message_manager.get_messages(limit, active_only=False)
data_dict = sql_alchemy_to_dict(data)
return pack_json_result(data_dict)
# in use admin-dashboard (08.01.25)
@router.post("/create-organization")
def create_organization(request: Request, body: CreateOrganizationBody = Body(...)):
auth_manager.check_admin_access(request.state)
organization_manager.create_organization(body.name)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/add-user-to-organization")
def add_user_to_organization(
request: Request, body: AddUserToOrganizationBody = Body(...)
):
auth_manager.check_admin_access(request.state)
user_manager.update_organization_of_user(body.organization_name, body.user_mail)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/remove-user-from-organization")
def remove_user_from_organization(
request: Request, body: RemoveUserToOrganizationBody = Body(...)
):
auth_manager.check_admin_access(request.state)
user_manager.remove_organization_from_user(body.user_mail)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/change-organization")
def change_organization(request: Request, body: ChangeOrganizationBody = Body(...)):
auth_manager.check_admin_access(request.state)
organization_manager.change_organization(body.org_id, json.loads(body.changes))
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.get("/user-roles")
def get_user_roles(request: Request):
auth_manager.check_admin_access(request.state)
data = user_manager.get_user_roles()
return pack_json_result(data, wrap_for_frontend=False)
# in use admin-dashboard (08.01.25)
@router.post("/change-user-role")
def change_user_role(request: Request, body: ChangeUserRoleBody = Body(...)):
auth_manager.check_admin_access(request.state)
user_manager.update_user_role(body.user_id, body.role)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.get("/all-organizations")
def get_all_organizations(request: Request):
auth_manager.check_admin_access(request.state)
organizations = manager.get_all_organizations()
org_dicts = [
{
**sql_alchemy_to_dict(org, column_whitelist=ALL_ORGANIZATIONS_WHITELIST),
"userCount": manager.get_user_count(org.id),
}
for org in organizations
]
return pack_json_result(org_dicts)
# in use admin-dashboard (08.01.25)
@router.delete("/delete-organization")
def delete_organization(request: Request, body: DeleteOrganizationBody = Body(...)):
auth_manager.check_admin_access(request.state)
organization_manager.delete_organization(body.name)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/create-admin-message")
def create_admin_message(request: Request, body: CreateAdminMessageBody = Body(...)):
auth_manager.check_admin_access(request.state)
user_id = auth_manager.get_user_id_by_info(request.state.info)
admin_message_manager.create_admin_message(
body.text, body.level, body.archive_date, body.scheduled_date, user_id
)
notification.send_global_update_for_all_organizations("admin_message")
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.delete("/archive-admin-message")
def archive_admin_message(
request: Request,
body: ArchiveAdminMessageBody = Body(...),
):
auth_manager.check_admin_access(request.state)
user_id = auth_manager.get_user_id_by_info(request.state.info)
admin_message_manager.archive_admin_message(
body.message_id, user_id, body.archived_reason
)
notification.send_global_update_for_all_organizations("admin_message")
return get_silent_success()
# in use cognition-ui (23.06.25)
@router.put("/update-user-field/{field}/{value}")
def set_language_display(request: Request, field: str, value: str):
user_id = auth_manager.get_user_id_by_info(request.state.info)
user_manager.update_user_field(user_id, field, value)
return get_silent_success()
# in use cognition-ui (15.12.25)
@router.post("/update-one-drive-field")
def set_one_drive_field(request: Request, body: UpdateOneDriveFieldRequest = Body(...)):
user_id = auth_manager.get_user_id_by_info(request.state.info)
user_manager.update_user_field(user_id, "one_drive_path", body.oneDrivePath)
return get_silent_success()
# in use cognition-ui (19.01.26)
@router.put("/update-settings/{setting_type}")
def update_settings(
request: Request, setting_type: str, body: UpdateSettingsRequest = Body(...)
):
user_id = auth_manager.get_user_id_by_info(request.state.info)
user_manager.update_user_field(user_id, f"{setting_type}", body.settings)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/mapped-sorted-paginated-users")
def get_mapped_sorted_paginated_users(
request: Request, body: MappedSortedPaginatedUsers = Body(...)
):
auth_manager.check_admin_access(request.state)
count_users = user_manager.get_active_users_filtered(body.filter_minutes)
active_users = user_manager.get_active_users_filtered(
body.filter_minutes, body.sort_key, body.sort_direction, body.offset, body.limit
)
active_users = [
{
"id": str(user.id),
"last_interaction": (
user.last_interaction.isoformat() if user.last_interaction else None
),
"role": user.role,
"organization": user.organization_name,
"email": user.email,
"verified": user.verified,
"created_at": user.created_at.isoformat() if user.created_at else None,
"metadata_public": user.metadata_public,
"sso_provider": user.sso_provider,
"messages_created_this_month": user.messages_created_this_month,
"messages_created_today": user.messages_created_today,
"is_light_user": user.is_light_user,
}
for user in active_users
]
return pack_json_result(
{
"mappedSortedPaginatedUsers": active_users,
"fullCountUsers": len(count_users),
},
wrap_for_frontend=False, # needed because it's used like this on the frontend (kratos values)
)
# in use admin-dashboard (08.01.25)
@router.delete("/delete-user")
def delete_user(request: Request, body: DeleteUserBody = Body(...)):
auth_manager.check_admin_access(request.state)
user_manager.delete_user(body.user_id)
return get_silent_success()
# in use admin-dashboard (08.01.25)
@router.post("/missing-kratos-data")
def get_missing_kratos_data(request: Request, body: MissingUsersBody = Body(...)):
auth_manager.check_admin_access(request.state)
data = user.get_missing_kratos_data(body.user_ids)
return pack_json_result(data, wrap_for_frontend=False)
# in use admin-dashboard (08.01.25)
@router.get("/user-to-organization")
def get_user_to_organization(request: Request):
auth_manager.check_admin_access(request.state)
data = user.get_user_to_organization()
return pack_json_result(data, wrap_for_frontend=False)
# in use admin-dashboard (01.10.25)
@router.get("/all-release-notifications-admin")
def get_all_release_notifications(request: Request):
auth_manager.check_admin_access(request.state)
data = sql_alchemy_to_dict(release_notification.get_all())
for item in data:
item["createdByEmail"] = resolve_user_mail_by_id(item["created_by"])
return pack_json_result(data)
# in use admin-dashboard (08.10.25)
@router.get("/release-notifications")
def get_release_notifications(request: Request):
data = sql_alchemy_to_dict(
release_notification.get_all(),
column_whitelist=RELEASE_NOTIFICATIONS_WHITELIST,
)
return pack_json_result(data)
# in use admin-dashboard (01.10.25)
@router.post("/create-release-notification")
def create_release_notification(
request: Request, body: CreateUpdateReleaseNotificationBody = Body(...)
):
auth_manager.check_admin_access(request.state)
user_id = auth_manager.get_user_id_by_info(request.state.info)
validate_result = manager.validate_json_release_notification(body.config)
if validate_result["is_valid"]:
release_notification.create(body.link, body.config, user_id, with_commit=True)
return pack_json_result(validate_result, wrap_for_frontend=False)
# in use admin-dashboard (02.10.25)
@router.put("/update-release-notification/{notification_id}")
def update_release_notification(
request: Request,
notification_id: str,
body: CreateUpdateReleaseNotificationBody = Body(...),
):
auth_manager.check_admin_access(request.state)
release_notification.update(
notification_id, body.link, body.config, with_commit=True
)
return get_silent_success()
# in use admin-dashboard (02.10.25)
@router.delete("/delete-release-notification/{notification_id}")
def delete_release_notification(request: Request, notification_id: str):
auth_manager.check_admin_access(request.state)
release_notification.delete(notification_id, with_commit=True)
return get_silent_success()
# in use admin-dashboard (27.01.26)
@router.put("/toggle-light-user-status/{user_id}")
def toggle_light_user_status(request: Request, user_id: str):
auth_manager.check_admin_access(request.state)
u = user_manager.get_or_create_user(user_id)
if not u:
raise HTTPException(status_code=404, detail="User not found")
user_manager.update_user_field(user_id, "is_light_user", not u.is_light_user)
return get_silent_success()
# in use admin-dashboard (10.02.26)
@router.get("/cross-selling")
def get_all_cross_sellings(request: Request):
auth_manager.check_admin_access(request.state)
data = cross_selling_manager.get_all_cross_sellings()
data_dict = sql_alchemy_to_dict(data, column_whitelist=CROSS_SELLING_WHITELIST)
return pack_json_result(data_dict)
# in use admin-dashboard (10.02.26)
@router.post("/cross-selling")
def create_cross_selling(
request: Request, body: CreateUpdateCrossSellingBody = Body(...)
):
auth_manager.check_admin_access(request.state)
entity = cross_selling_manager.create_cross_selling(name=body.name)
data = sql_alchemy_to_dict(entity, column_whitelist=CROSS_SELLING_WHITELIST)
return pack_json_result(data)
# in use admin-dashboard (10.02.26)
@router.put("/cross-selling/{cross_selling_id}")
def update_cross_selling(
request: Request,
cross_selling_id: str,
body: CreateUpdateCrossSellingBody = Body(...),
):
auth_manager.check_admin_access(request.state)
try:
entity = cross_selling_manager.update_cross_selling(
cross_selling_id, name=body.name
)
data = sql_alchemy_to_dict(entity, column_whitelist=CROSS_SELLING_WHITELIST)
return pack_json_result(data)
except EntityNotFoundException as e:
return pack_json_result({"error": str(e)}, status_code=404)
# in use admin-dashboard (10.02.26)
@router.delete("/cross-selling/{cross_selling_id}")
def delete_cross_selling(request: Request, cross_selling_id: str):
auth_manager.check_admin_access(request.state)
try:
cross_selling_manager.delete_cross_selling(cross_selling_id)
return get_silent_success()
except EntityNotFoundException as e:
return pack_json_result({"error": str(e)}, status_code=404)