fastapi-rtk 1.0.7__py3-none-any.whl → 1.0.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastapi_rtk/__init__.py CHANGED
@@ -156,7 +156,6 @@ __all__ = [
156
156
  "docs",
157
157
  # .dependencies
158
158
  "set_global_user",
159
- "permissions",
160
159
  "current_permissions",
161
160
  "has_access_dependency",
162
161
  # .exceptions
fastapi_rtk/_version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "1.0.7"
1
+ __version__ = "1.0.9"
@@ -2328,6 +2328,7 @@ class ModelRestApi(BaseApi):
2328
2328
  )
2329
2329
 
2330
2330
  if self.datamodel.is_files(key) or self.datamodel.is_images(key):
2331
+ value = [x for x in value if x] # Remove None values
2331
2332
  old_filenames = (
2332
2333
  [x for x in value if isinstance(x, str)] if value else []
2333
2334
  )
fastapi_rtk/auth/auth.py CHANGED
@@ -142,15 +142,6 @@ class Authenticator(BaseAuthenticator):
142
142
  except HTTPException as e:
143
143
  if not default_to_none:
144
144
  raise e
145
-
146
- # Retrieve list of apis, that user has access to
147
- if user:
148
- user.permissions = []
149
- for role in user.roles:
150
- for permission_api in role.permissions:
151
- user.permissions.append(permission_api.api.name)
152
- user.permissions = list(set(user.permissions))
153
-
154
145
  return user, token
155
146
 
156
147
 
@@ -454,3 +454,11 @@ class SQLAQueryBuilder(AbstractQueryBuilder[Select[tuple[T]]]):
454
454
  load_column["related_columns"][col]["type"] = "some"
455
455
 
456
456
  return load_column
457
+
458
+ def _convert_id_into_dict(self, id):
459
+ # Cast the id into the right type based on the pk column type
460
+ pk_dict = super()._convert_id_into_dict(id)
461
+ for pk in pk_dict:
462
+ col_type = self.datamodel.list_columns[pk].type.python_type
463
+ pk_dict[pk] = col_type(pk_dict[pk])
464
+ return pk_dict
@@ -617,6 +617,22 @@ class SQLAFilterConverter:
617
617
  FilterIn,
618
618
  ],
619
619
  ),
620
+ (
621
+ "is_files",
622
+ [
623
+ FilterTextContains,
624
+ # TODO: Make compatible filters
625
+ # FilterEqual,
626
+ # FilterNotEqual,
627
+ # FilterStartsWith,
628
+ # FilterNotStartsWith,
629
+ # FilterEndsWith,
630
+ # FilterNotEndsWith,
631
+ # FilterContains,
632
+ # FilterNotContains,
633
+ # FilterIn,
634
+ ],
635
+ ),
620
636
  (
621
637
  "is_integer",
622
638
  [
@@ -255,7 +255,12 @@ class SQLAInterface(AbstractInterface[ModelType, Session | AsyncSession, Column]
255
255
  unique_order_columns.update(
256
256
  [f"{col_name}.{sub_col}" for sub_col in sub_order_columns]
257
257
  )
258
- elif self.is_property(col_name) and not self.is_hybrid_property(col_name):
258
+ elif (
259
+ self.is_property(col_name)
260
+ and not self.is_hybrid_property(col_name)
261
+ or self.is_files(col_name)
262
+ or self.is_images(col_name)
263
+ ):
259
264
  continue
260
265
 
261
266
  # Allow the column to be used for ordering by default
@@ -353,14 +358,12 @@ class SQLAInterface(AbstractInterface[ModelType, Session | AsyncSession, Column]
353
358
  ]
354
359
  elif self.is_file(col) or self.is_image(col):
355
360
  value_type = fastapi.UploadFile
361
+ annotated_str_type = typing.Annotated[
362
+ str | None, BeforeValidator(lambda x: None if x == "null" else x)
363
+ ]
356
364
  if self.is_files(col) or self.is_images(col):
357
- value_type = list[value_type | str]
358
- return (
359
- value_type
360
- | typing.Annotated[
361
- str | None, BeforeValidator(lambda x: None if x == "null" else x)
362
- ]
363
- )
365
+ value_type = list[value_type | annotated_str_type]
366
+ return value_type | annotated_str_type
364
367
  elif self.is_date(col):
365
368
  return date
366
369
  elif self.is_datetime(col):
@@ -35,6 +35,18 @@ class AbstractFileManager(abc.ABC):
35
35
  namegen: typing.Callable[[str], str] | None = None,
36
36
  permission: int | None = None,
37
37
  ):
38
+ """
39
+ Initializes the AbstractFileManager.
40
+
41
+ Args:
42
+ base_path (str | None, optional): Base path for file storage. Defaults to None.
43
+ allowed_extensions (list[str] | None, optional): Allowed file extensions. Defaults to None.
44
+ namegen (typing.Callable[[str], str] | None, optional): Callable for generating file names. Defaults to None.
45
+ permission (int | None, optional): File permission settings. Defaults to None.
46
+
47
+ Raises:
48
+ ValueError: If `base_path` is not set.
49
+ """
38
50
  if base_path is not None:
39
51
  self.base_path = base_path
40
52
  if allowed_extensions is not None:
@@ -1,14 +1,16 @@
1
1
  import fastapi
2
+ import sqlalchemy
2
3
  from fastapi import Depends, HTTPException
3
4
 
4
5
  from .api.base_api import BaseApi
5
- from .const import PERMISSION_PREFIX, ErrorCode
6
+ from .const import PERMISSION_PREFIX, ErrorCode, logger
7
+ from .db import db
6
8
  from .globals import g
7
- from .security.sqla.models import PermissionApi, User
9
+ from .security.sqla.models import Api, Permission, PermissionApi, Role, User
10
+ from .utils import smart_run
8
11
 
9
12
  __all__ = [
10
13
  "set_global_user",
11
- "permissions",
12
14
  "current_permissions",
13
15
  "has_access_dependency",
14
16
  ]
@@ -62,82 +64,65 @@ def check_g_user():
62
64
  return check_g_user_dependency
63
65
 
64
66
 
65
- def permissions(as_object=False):
67
+ def current_permissions(api: BaseApi):
66
68
  """
67
- A dependency for FastAPI that will return all permissions of the current user.
69
+ A dependency for FastAPI that will return all permissions of the current user for the specified API.
68
70
 
69
- This will implicitly call the `current_user` dependency from `fastapi_users`. Therefore, it can return `403 Forbidden` if the user is not authenticated.
71
+ Because it will implicitly check whether the user is authenticated, it can return `401 Unauthorized` or `403 Forbidden`.
70
72
 
71
73
  Args:
72
- as_object (bool): Whether to return the `PermissionApi` objects or return the api names (E.g "AuthApi" or "AuthApi|UserApi").
74
+ api (BaseApi): The API to be checked.
73
75
 
74
76
  Usage:
75
77
  ```python
76
78
  async def get_info(
77
79
  *,
78
- permissions: List[str] = Depends(permissions()),
80
+ permissions: List[str] = Depends(current_permissions(self)),
79
81
  session: AsyncSession | Session = Depends(get_async_session),
80
82
  ):
81
83
  ...more code
82
84
  ```
83
85
  """
84
86
 
85
- async def permissions_depedency():
86
- if not g.user:
87
- raise HTTPException(
88
- fastapi.status.HTTP_401_UNAUTHORIZED,
89
- ErrorCode.GET_USER_MISSING_TOKEN_OR_INACTIVE_USER,
90
- )
91
-
92
- if not g.user.roles:
93
- raise HTTPException(
94
- fastapi.status.HTTP_403_FORBIDDEN, ErrorCode.GET_USER_NO_ROLES
95
- )
87
+ async def current_permissions_depedency(_=Depends(_ensure_roles)):
88
+ sm = g.current_app.security
89
+ api_name = api.__class__.__name__
90
+ permissions = set[str]()
91
+ db_role_ids = list[int]()
96
92
 
97
- permissions = []
93
+ # Retrieve permissions from built-in roles
98
94
  for role in g.user.roles:
99
- for permission_api in role.permissions:
100
- if as_object:
101
- permissions.append(permission_api)
102
- else:
103
- permissions.append(permission_api.api.name)
104
- permissions = list(set(permissions))
105
-
106
- return permissions
107
-
108
- return permissions_depedency
109
-
95
+ if role.name not in sm.builtin_roles:
96
+ db_role_ids.append(role.id)
97
+ continue
110
98
 
111
- def current_permissions(api: BaseApi):
112
- """
113
- A dependency for FastAPI that will return all permissions of the current user for the specified API.
114
-
115
- Because it will implicitly call the `permissions` dependency, it can return `403 Forbidden` if the user is not authenticated.
99
+ api_permission_tuples = sm.get_api_permission_tuples_from_builtin_roles(
100
+ role.name
101
+ )
102
+ for multi_apis_str, multi_perms_str in api_permission_tuples:
103
+ api_names = multi_apis_str.split("|")
104
+ perm_names = multi_perms_str.split("|")
105
+ if api_name in api_names:
106
+ permissions.update(perm_names)
107
+
108
+ if db_role_ids:
109
+ query = (
110
+ sqlalchemy.select(Permission)
111
+ .join(PermissionApi)
112
+ .join(PermissionApi.roles)
113
+ .join(Api)
114
+ .where(Api.name == api_name, Role.id.in_(db_role_ids))
115
+ )
116
+ if api.base_permissions:
117
+ query = query.where(Permission.name.in_(api.base_permissions))
116
118
 
117
- Args:
118
- api (BaseApi): The API to be checked.
119
+ permissions_in_db = await smart_run(db.current_session.scalars, query)
120
+ permissions.update(perm.name for perm in permissions_in_db.all())
119
121
 
120
- Usage:
121
- ```python
122
- async def get_info(
123
- *,
124
- permissions: List[str] = Depends(current_permissions(self)),
125
- session: AsyncSession | Session = Depends(get_async_session),
126
- ):
127
- ...more code
128
- ```
129
- """
130
-
131
- async def current_permissions_depedency(
132
- permissions_apis: list[PermissionApi] = Depends(permissions(as_object=True)),
133
- ):
134
- permissions = []
135
- for permission_api in permissions_apis:
136
- if api.__class__.__name__ in permission_api.api.name.split("|"):
137
- permissions = permissions + permission_api.permission.name.split("|")
138
122
  if api.base_permissions:
139
- permissions = [x for x in permissions if x in api.base_permissions]
140
- return list(set(permissions))
123
+ permissions = permissions.intersection(set(api.base_permissions))
124
+
125
+ return list(permissions)
141
126
 
142
127
  return current_permissions_depedency
143
128
 
@@ -149,7 +134,7 @@ def has_access_dependency(
149
134
  """
150
135
  A dependency for FastAPI to check whether current user has access to the specified API and permission.
151
136
 
152
- Because it will implicitly call the `current_permissions` dependency, it can return `403 Forbidden` if the user is not authenticated.
137
+ Because it will implicitly check whether the user is authenticated, it can return `401 Unauthorized` or `403 Forbidden`.
153
138
 
154
139
  Usage:
155
140
  ```python
@@ -165,15 +150,55 @@ def has_access_dependency(
165
150
  api (BaseApi): The API to be checked.
166
151
  permission (str): The permission to check.
167
152
  """
153
+ permission = f"{PERMISSION_PREFIX}{permission}"
168
154
 
169
- async def check_permission(
170
- permissions: list[str] = Depends(current_permissions(api)),
171
- ):
172
- if f"{PERMISSION_PREFIX}{permission}" not in permissions:
155
+ async def check_permission():
156
+ _ensure_roles(ErrorCode.PERMISSION_DENIED)
157
+
158
+ # First, check built-in roles (avoiding unnecessary DB queries)
159
+ # This also covers the case for API and permission name with pipes
160
+ sm = g.current_app.security
161
+ if any(
162
+ sm.has_access_in_builtin_roles(
163
+ role.name, api.__class__.__name__, permission
164
+ )
165
+ for role in g.user.roles
166
+ ):
167
+ logger.debug(
168
+ f"User {g.user} has access to {api.__class__.__name__} with permission {permission} via built-in roles."
169
+ )
170
+ return
171
+
172
+ db_role_ids = [
173
+ role.id for role in g.user.roles if role.name not in sm.builtin_roles
174
+ ]
175
+ if not db_role_ids:
173
176
  raise HTTPException(
174
177
  fastapi.status.HTTP_403_FORBIDDEN, ErrorCode.PERMISSION_DENIED
175
178
  )
176
- return
179
+
180
+ api_name = api.__class__.__name__
181
+ exist_query = (
182
+ sqlalchemy.select(Permission)
183
+ .join(PermissionApi)
184
+ .join(PermissionApi.roles)
185
+ .join(Api)
186
+ .where(
187
+ Api.name == api_name,
188
+ Permission.name == permission,
189
+ Role.id.in_(db_role_ids),
190
+ )
191
+ .exists()
192
+ )
193
+ result: bool = await smart_run(
194
+ db.current_session.scalar, sqlalchemy.select(exist_query)
195
+ )
196
+ if result:
197
+ return
198
+
199
+ raise HTTPException(
200
+ fastapi.status.HTTP_403_FORBIDDEN, ErrorCode.PERMISSION_DENIED
201
+ )
177
202
 
178
203
  return check_permission
179
204
 
@@ -208,3 +233,24 @@ async def set_global_request(request: fastapi.Request):
208
233
  ...more code
209
234
  """
210
235
  g.request = request
236
+
237
+
238
+ def _ensure_roles(err_forbidden_message=ErrorCode.GET_USER_NO_ROLES):
239
+ """
240
+ A dependency for FastAPI that will ensure the current user has roles assigned.
241
+
242
+ Args:
243
+ err_forbidden_message (str): The error message to be used when raising `403 Forbidden`. Defaults to `ErrorCode.GET_USER_NO_ROLES`.
244
+
245
+ Raises:
246
+ HTTPException: Raised when the user is not authenticated.
247
+ HTTPException: Raised when the user has no roles assigned.
248
+ """
249
+ if not g.user:
250
+ raise HTTPException(
251
+ fastapi.status.HTTP_401_UNAUTHORIZED,
252
+ ErrorCode.GET_USER_MISSING_TOKEN_OR_INACTIVE_USER,
253
+ )
254
+
255
+ if not g.user.roles:
256
+ raise HTTPException(fastapi.status.HTTP_403_FORBIDDEN, err_forbidden_message)
@@ -16,13 +16,11 @@ from fastapi.templating import Jinja2Templates
16
16
  from fastapi_babel import BabelMiddleware
17
17
  from jinja2 import Environment, TemplateNotFound, select_autoescape
18
18
  from prometheus_fastapi_instrumentator import Instrumentator
19
- from sqlalchemy import and_, select
20
- from sqlalchemy.ext.asyncio import AsyncSession
21
- from sqlalchemy.orm import Session
22
19
  from starlette.routing import _DefaultLifespan
23
20
 
24
21
  from .api.model_rest_api import ModelRestApi
25
22
  from .auth import Auth
23
+ from .backends.sqla.session import SQLASession
26
24
  from .cli.commands.db import upgrade
27
25
  from .cli.commands.translate import init_babel_cli
28
26
  from .const import (
@@ -418,175 +416,121 @@ class FastAPIReactToolkit:
418
416
 
419
417
  async with db.session() as session:
420
418
  logger.info("INITIALIZING DATABASE")
421
- await self._insert_permissions(session)
422
- await self._insert_apis(session)
423
- await self._insert_roles(session)
424
- await self._associate_permission_with_api(session)
425
- await self._associate_permission_api_with_role(session)
419
+ permissions = await self._insert_permissions(session)
420
+ apis = await self._insert_apis(session)
421
+ roles = await self._insert_roles(session)
422
+ assert permissions is not None, "Permissions should not be None"
423
+ assert apis is not None, "APIs should not be None"
424
+ permission_apis = await self._associate_permission_with_api(
425
+ session, permissions, apis
426
+ )
427
+ assert roles is not None, "Roles should not be None"
428
+ assert permission_apis is not None, "PermissionApis should not be None"
429
+ await self._associate_role_with_permission_api(
430
+ session, roles, permission_apis
431
+ )
426
432
  if self.cleanup:
427
433
  await self.security.cleanup()
428
434
  logger.info("DATABASE INITIALIZED")
429
435
 
430
- async def _insert_permissions(self, session: AsyncSession | Session):
431
- new_permissions = self.total_permissions()
432
- stmt = select(Permission).where(Permission.name.in_(new_permissions))
433
- result = await safe_call(session.scalars(stmt))
434
- existing_permissions = [permission.name for permission in result.all()]
435
- if len(new_permissions) == len(existing_permissions):
436
- return
437
-
438
- permission_objs = [
439
- Permission(name=permission)
440
- for permission in new_permissions
441
- if permission not in existing_permissions
436
+ async def _insert_permissions(self, session: SQLASession):
437
+ permissions = self.total_permissions() + [
438
+ x[1] for x in self.security.get_api_permission_tuples_from_builtin_roles()
442
439
  ]
443
- for permission in permission_objs:
444
- logger.info(f"ADDING PERMISSION {permission}")
445
- session.add(permission)
446
- await safe_call(session.commit())
447
-
448
- async def _insert_apis(self, session: AsyncSession | Session):
449
- new_apis = [api.__class__.__name__ for api in self.apis]
450
- stmt = select(Api).where(Api.name.in_(new_apis))
451
- result = await safe_call(session.scalars(stmt))
452
- existing_apis = [api.name for api in result.all()]
453
- if len(new_apis) == len(existing_apis):
454
- return
455
-
456
- api_objs = [Api(name=api) for api in new_apis if api not in existing_apis]
457
- for api in api_objs:
458
- logger.info(f"ADDING API {api}")
459
- session.add(api)
460
- await safe_call(session.commit())
461
-
462
- async def _insert_roles(self, session: AsyncSession | Session):
463
- new_roles = [x for x in [g.admin_role, g.public_role] if x is not None]
464
- stmt = select(Role).where(Role.name.in_(new_roles))
465
- result = await safe_call(session.scalars(stmt))
466
- existing_roles = [role.name for role in result.all()]
467
- if len(new_roles) == len(existing_roles):
468
- return
440
+ permissions = list(dict.fromkeys(permissions))
441
+ return await self.security.create_permissions(permissions, session=session)
469
442
 
470
- role_objs = [
471
- Role(name=role) for role in new_roles if role not in existing_roles
443
+ async def _insert_apis(self, session: SQLASession):
444
+ apis = [api.__class__.__name__ for api in self.apis] + [
445
+ x[0] for x in self.security.get_api_permission_tuples_from_builtin_roles()
472
446
  ]
473
- for role in role_objs:
474
- logger.info(f"ADDING ROLE {role}")
475
- session.add(role)
476
- await safe_call(session.commit())
447
+ apis = list(dict.fromkeys(apis))
448
+ return await self.security.create_apis(apis, session=session)
449
+
450
+ async def _insert_roles(self, session: SQLASession):
451
+ roles = self.security.get_roles_from_builtin_roles()
452
+ if g.admin_role and g.admin_role not in roles:
453
+ roles.append(g.admin_role)
454
+ if g.public_role and g.public_role not in roles:
455
+ roles.append(g.public_role)
456
+ return await self.security.create_roles(roles, session=session)
457
+
458
+ async def _associate_permission_with_api(
459
+ self,
460
+ session: SQLASession,
461
+ permissions: list[Permission],
462
+ apis: list[Api],
463
+ ):
464
+ permission_map = {permission.name: permission for permission in permissions}
465
+ api_map = {api.name: api for api in apis}
466
+ permission_api_tuples = list[tuple[Permission, Api]]()
467
+ added_permission_api = set[tuple[str, str]]()
477
468
 
478
- async def _associate_permission_with_api(self, session: AsyncSession | Session):
479
469
  for api in self.apis:
480
- new_permissions = getattr(api, "permissions", [])
481
- if not new_permissions:
470
+ api_permissions = api.permissions
471
+ if not api_permissions:
482
472
  continue
483
473
 
484
- # Get the api object
485
- api_stmt = select(Api).where(Api.name == api.__class__.__name__)
486
- api_obj = await safe_call(session.scalar(api_stmt))
487
-
488
- if not api_obj:
489
- raise ValueError(f"API {api.__class__.__name__} not found")
490
-
491
- permission_stmt = select(Permission).where(
492
- and_(
493
- Permission.name.in_(new_permissions),
494
- ~Permission.id.in_([p.permission_id for p in api_obj.permissions]),
495
- )
496
- )
497
- permission_result = await safe_call(session.scalars(permission_stmt))
498
- new_permissions = permission_result.all()
499
-
500
- if not new_permissions:
474
+ for permission_name in api_permissions:
475
+ if (permission_name, api.__class__.__name__) in added_permission_api:
476
+ continue
477
+ permission = permission_map[permission_name]
478
+ api_obj = api_map[api.__class__.__name__]
479
+ permission_api_tuples.append((permission, api_obj))
480
+ added_permission_api.add((permission.name, api_obj.name))
481
+
482
+ for (
483
+ api_name,
484
+ perm_name,
485
+ ) in self.security.get_api_permission_tuples_from_builtin_roles():
486
+ if (perm_name, api_name) in added_permission_api:
501
487
  continue
488
+ permission = permission_map[perm_name]
489
+ api_obj = api_map[api_name]
490
+ permission_api_tuples.append((permission, api_obj))
491
+ added_permission_api.add((permission.name, api_obj.name))
502
492
 
503
- for permission in new_permissions:
504
- session.add(
505
- PermissionApi(permission_id=permission.id, api_id=api_obj.id)
506
- )
507
- logger.info(f"ASSOCIATING PERMISSION {permission} WITH API {api_obj}")
508
- await safe_call(session.commit())
493
+ return await self.security.associate_list_of_permission_with_api(
494
+ permission_api_tuples, session=session
495
+ )
509
496
 
510
- async def _associate_permission_api_with_role(
511
- self, session: AsyncSession | Session
497
+ async def _associate_role_with_permission_api(
498
+ self,
499
+ session: SQLASession,
500
+ roles: list[Role],
501
+ permission_apis: list[PermissionApi],
512
502
  ):
513
- # Read config based roles
514
- roles_dict = Setting.ROLES
515
-
516
- for role_name, role_permissions in roles_dict.items():
517
- role_stmt = select(Role).where(Role.name == role_name)
518
- role_result = await safe_call(session.scalars(role_stmt))
519
- role = role_result.first()
520
- if not role:
521
- role = Role(name=role_name)
522
- logger.info(f"ADDING ROLE {role}")
523
- session.add(role)
524
-
525
- for api_name, permission_name in role_permissions:
526
- permission_api_stmt = (
527
- select(PermissionApi)
528
- .where(
529
- and_(Api.name == api_name, Permission.name == permission_name)
530
- )
531
- .join(Permission)
532
- .join(Api)
533
- )
534
- permission_api = await safe_call(session.scalar(permission_api_stmt))
535
- if not permission_api:
536
- permission_stmt = select(Permission).where(
537
- Permission.name == permission_name
538
- )
539
- permission = await safe_call(session.scalar(permission_stmt))
540
- if not permission:
541
- permission = Permission(name=permission_name)
542
- logger.info(f"ADDING PERMISSION {permission}")
543
- session.add(permission)
544
-
545
- stmt = select(Api).where(Api.name == api_name)
546
- api = await safe_call(session.scalar(stmt))
547
- if not api:
548
- api = Api(name=api_name)
549
- logger.info(f"ADDING API {api}")
550
- session.add(api)
551
-
552
- permission_api = PermissionApi(permission=permission, api=api)
553
- logger.info(f"ADDING PERMISSION-API {permission_api}")
554
- session.add(permission_api)
555
-
556
- # Associate role with permission-api
557
- if role not in permission_api.roles:
558
- permission_api.roles.append(role)
559
- logger.info(
560
- f"ASSOCIATING {role} WITH PERMISSION-API {permission_api}"
561
- )
562
-
563
- await safe_call(session.commit())
564
-
565
- # Get admin role
566
- if g.admin_role is None:
567
- logger.warning("Admin role is not set, skipping admin role association")
568
- return
569
-
570
- admin_role_stmt = select(Role).where(Role.name == g.admin_role)
571
- admin_role = await safe_call(session.scalar(admin_role_stmt))
572
-
573
- if admin_role:
574
- # Get list of permission-api.assoc_permission_api_id of the admin role
575
- stmt = (
576
- select(PermissionApi)
577
- .where(~PermissionApi.roles.contains(admin_role))
578
- .join(Api)
579
- )
580
- result = await safe_call(session.scalars(stmt))
581
- existing_assoc_permission_api_roles = result.all()
582
-
583
- # Add admin role to all permission-api objects
584
- for permission_api in existing_assoc_permission_api_roles:
585
- permission_api.roles.append(admin_role)
586
- logger.info(
587
- f"ASSOCIATING {admin_role} WITH PERMISSION-API {permission_api}"
588
- )
589
- await safe_call(session.commit())
503
+ role_map = {role.name: role for role in roles}
504
+ permission_api_map = {
505
+ (pa.permission.name, pa.api.name): pa for pa in permission_apis
506
+ }
507
+ permission_apis_to_exclude_from_admin = list[PermissionApi]()
508
+ role_permission_api_tuples = list[tuple[Role, PermissionApi]]()
509
+
510
+ for (
511
+ role_name,
512
+ role_api_permissions,
513
+ ) in self.security.get_role_and_api_permission_tuples_from_builtin_roles():
514
+ for api_name, permission_name in role_api_permissions:
515
+ role = role_map[role_name]
516
+ permission_api = permission_api_map[(permission_name, api_name)]
517
+ role_permission_api_tuples.append((role, permission_api))
518
+ if "|" in permission_name and role_name != g.public_role:
519
+ # Exclude multi-tenant permissions from admin role if not explicitly set
520
+ permission_apis_to_exclude_from_admin.append(permission_api)
521
+
522
+ if g.admin_role:
523
+ admin_role = role_map[g.admin_role]
524
+ for permission_api in [
525
+ pa
526
+ for pa in permission_apis
527
+ if pa not in permission_apis_to_exclude_from_admin
528
+ ]:
529
+ role_permission_api_tuples.append((admin_role, permission_api))
530
+
531
+ await self.security.associate_list_of_role_with_permission_api(
532
+ role_permission_api_tuples, session=session
533
+ )
590
534
 
591
535
  def _mount_static_folder(self):
592
536
  """