Support multiple roles per account #213
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
from inse.auth.model import UserRole, normalize_roles
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
@@ -16,7 +16,7 @@ class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
roles: List[UserRole]
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
@@ -34,20 +34,45 @@ class AccountPage(BaseModel):
|
||||
|
||||
|
||||
class CreateAccountRequest(BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
role: UserRole = UserRole.USER
|
||||
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
self.roles = normalize_roles(self.roles)
|
||||
return self
|
||||
|
||||
|
||||
class UpdateAccountRequest(BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
role: Optional[UserRole] = None
|
||||
roles: Optional[List[UserRole]] = None
|
||||
organization_id: Optional[uuid.UUID] = None
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
activated: Optional[bool] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
if self.roles is not None:
|
||||
self.roles = normalize_roles(self.roles)
|
||||
return self
|
||||
|
||||
@@ -5,7 +5,13 @@ from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||
from inse.auth.model import (
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
Organization,
|
||||
UserRole,
|
||||
normalize_roles,
|
||||
)
|
||||
|
||||
from .model import (
|
||||
AccountPage,
|
||||
@@ -28,13 +34,17 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _roles_allowed_for_editor(editor_role: UserRole, roles: list[UserRole]) -> bool:
|
||||
return all(_role_allowed_for_editor(editor_role, role) for role in roles)
|
||||
|
||||
|
||||
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
|
||||
organization_name = account.organization.name if account.organization else ""
|
||||
return AccountProfile(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
roles=normalize_roles(account.roles),
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
@@ -175,7 +185,7 @@ def create_account(
|
||||
detail="Admins can only create accounts in their own organization.",
|
||||
)
|
||||
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
@@ -194,7 +204,7 @@ def create_account(
|
||||
account = Account(
|
||||
email=email,
|
||||
name=payload.name.strip(),
|
||||
role=payload.role,
|
||||
roles=payload.roles,
|
||||
organization_id=payload.organization_id,
|
||||
password_hash=auth_service._hash_password(payload.password),
|
||||
openalex_person_id=payload.openalex_person_id,
|
||||
@@ -261,15 +271,15 @@ def update_account(
|
||||
if payload.openalex_person_id is not None:
|
||||
account.openalex_person_id = payload.openalex_person_id
|
||||
|
||||
if payload.role is not None:
|
||||
if payload.roles is not None:
|
||||
if not can_admin_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
account.role = payload.role
|
||||
account.roles = payload.roles
|
||||
account.epoch += 1
|
||||
|
||||
if payload.organization_id is not None:
|
||||
|
||||
@@ -3,8 +3,8 @@ from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from pydantic import BaseModel, model_validator
|
||||
from sqlalchemy import JSON, Column, UniqueConstraint
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
@@ -15,6 +15,35 @@ class UserRole(StrEnum):
|
||||
USER = "USER"
|
||||
|
||||
|
||||
ROLE_PRIORITY = {
|
||||
UserRole.SUPER_ADMIN: 0,
|
||||
UserRole.ADMIN: 1,
|
||||
UserRole.MANAGER: 2,
|
||||
UserRole.USER: 3,
|
||||
}
|
||||
|
||||
|
||||
def normalize_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> List[UserRole]:
|
||||
if roles is None:
|
||||
return [UserRole.USER]
|
||||
if isinstance(roles, (str, UserRole)):
|
||||
roles = [roles]
|
||||
|
||||
normalized = []
|
||||
seen = set()
|
||||
for role in roles:
|
||||
user_role = role if isinstance(role, UserRole) else UserRole(role)
|
||||
if user_role not in seen:
|
||||
normalized.append(user_role)
|
||||
seen.add(user_role)
|
||||
|
||||
return sorted(normalized or [UserRole.USER], key=lambda role: ROLE_PRIORITY[role])
|
||||
|
||||
|
||||
def effective_role_for_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> UserRole:
|
||||
return normalize_roles(roles)[0]
|
||||
|
||||
|
||||
class TokenType(StrEnum):
|
||||
ID_TOKEN = "ID_TOKEN"
|
||||
REFRESH_TOKEN = "REFRESH_TOKEN"
|
||||
@@ -57,6 +86,13 @@ class Organization(Durable, table=True):
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
@@ -101,15 +137,22 @@ class Account(Durable, table=True):
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this account holds within its organization.",
|
||||
roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
|
||||
description="The roles this account holds within its organization.",
|
||||
)
|
||||
|
||||
organization: Organization = Relationship(back_populates="accounts")
|
||||
|
||||
@property
|
||||
def role(self) -> UserRole:
|
||||
return effective_role_for_roles(self.roles)
|
||||
|
||||
@role.setter
|
||||
def role(self, value: UserRole) -> None:
|
||||
self.roles = normalize_roles(value)
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
__table_args__ = (
|
||||
@@ -176,6 +219,17 @@ class IdTokenMetadata(BaseTokenData):
|
||||
|
||||
|
||||
class AccessTokenMetadata(BaseTokenData):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _effective_role_to_roles(cls, values):
|
||||
if (
|
||||
isinstance(values, dict)
|
||||
and "effective_roles" not in values
|
||||
and "effective_role" in values
|
||||
):
|
||||
values = {**values, "effective_roles": [values["effective_role"]]}
|
||||
return values
|
||||
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ACCESS_TOKEN,
|
||||
const=True,
|
||||
@@ -191,6 +245,10 @@ class AccessTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
@@ -211,6 +269,17 @@ class AccessToken(AccessTokenMetadata):
|
||||
|
||||
|
||||
class RefreshTokenMetadata(BaseTokenData):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _effective_role_to_roles(cls, values):
|
||||
if (
|
||||
isinstance(values, dict)
|
||||
and "effective_roles" not in values
|
||||
and "effective_role" in values
|
||||
):
|
||||
values = {**values, "effective_roles": [values["effective_role"]]}
|
||||
return values
|
||||
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.REFRESH_TOKEN,
|
||||
const=True,
|
||||
@@ -223,6 +292,10 @@ class RefreshTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
|
||||
@@ -28,6 +28,8 @@ from inse.auth.model import (
|
||||
SecretPurpose,
|
||||
TokenType,
|
||||
UserRole,
|
||||
effective_role_for_roles,
|
||||
normalize_roles,
|
||||
)
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
@@ -44,6 +46,7 @@ PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
EFFECTIVE_ROLE_KEY = "effective_role"
|
||||
EFFECTIVE_ROLES_KEY = "effective_roles"
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
|
||||
EPOCH_KEY = "epoch"
|
||||
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
|
||||
@@ -110,14 +113,14 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
session.add(organization)
|
||||
for account_data in data.get("accounts", []):
|
||||
organization_id = uuid.UUID(account_data["organization_id"])
|
||||
role = UserRole(account_data["role"])
|
||||
roles = normalize_roles(account_data.get("roles", account_data.get("role")))
|
||||
email = account_data["email"]
|
||||
password_hash = _hash_password(account_data["password"])
|
||||
account = Account(
|
||||
email=email,
|
||||
name=account_data["name"],
|
||||
organization_id=organization_id,
|
||||
role=role,
|
||||
roles=roles,
|
||||
password_hash=password_hash,
|
||||
epoch=0,
|
||||
)
|
||||
@@ -609,6 +612,11 @@ def _get_current_user_access_token_payload(
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_roles=normalize_roles(
|
||||
access_token_payload.get(
|
||||
EFFECTIVE_ROLES_KEY, access_token_payload[EFFECTIVE_ROLE_KEY]
|
||||
)
|
||||
),
|
||||
effective_organization_id=uuid.UUID(
|
||||
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
@@ -649,6 +657,11 @@ def _get_current_user_refresh_token_payload(
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_roles=normalize_roles(
|
||||
refresh_token_payload.get(
|
||||
EFFECTIVE_ROLES_KEY, refresh_token_payload[EFFECTIVE_ROLE_KEY]
|
||||
)
|
||||
),
|
||||
effective_organization_id=uuid.UUID(
|
||||
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
@@ -728,7 +741,7 @@ def _get_account_epoch(
|
||||
return account.epoch
|
||||
|
||||
|
||||
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
def _get_account_roles(session: Session, account_id: uuid.UUID) -> list[UserRole]:
|
||||
"""Retrieves the role for the given account ID.
|
||||
|
||||
Args:
|
||||
@@ -736,14 +749,14 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
|
||||
|
||||
Returns:
|
||||
UserRole: The role associated with the given account ID.
|
||||
list[UserRole]: The roles associated with the given account ID.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or not account.activated or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.role
|
||||
return normalize_roles(account.roles)
|
||||
|
||||
|
||||
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
|
||||
@@ -794,13 +807,16 @@ def _is_valid_impersonation(
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
|
||||
if real_account.role == UserRole.SUPER_ADMIN:
|
||||
real_account_role = effective_role_for_roles(real_account.roles)
|
||||
effective_account_role = effective_role_for_roles(effective_account.roles)
|
||||
|
||||
if real_account_role == UserRole.SUPER_ADMIN:
|
||||
return True # Super admins can impersonate any account
|
||||
|
||||
if real_account.organization_id != effective_account.organization_id:
|
||||
return False # Cannot impersonate accounts from different organizations
|
||||
|
||||
if real_account.role == UserRole.ADMIN and effective_account.role in [
|
||||
if real_account_role == UserRole.ADMIN and effective_account_role in [
|
||||
UserRole.MANAGER,
|
||||
UserRole.USER,
|
||||
]:
|
||||
@@ -847,7 +863,8 @@ def get_access_token(
|
||||
detail="Impersonation not allowed",
|
||||
)
|
||||
|
||||
role = _get_account_role(session=session, account_id=effective_account_id)
|
||||
roles = _get_account_roles(session=session, account_id=effective_account_id)
|
||||
role = effective_role_for_roles(roles)
|
||||
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
|
||||
organization_id = _get_account_organization(
|
||||
session=session, account_id=effective_account_id
|
||||
@@ -862,6 +879,7 @@ def get_access_token(
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
effective_roles=roles,
|
||||
)
|
||||
_set_refresh_token(
|
||||
response=response,
|
||||
@@ -870,6 +888,7 @@ def get_access_token(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
effective_roles=roles,
|
||||
)
|
||||
return AccessResponse(
|
||||
access_token=access_token,
|
||||
@@ -974,6 +993,7 @@ def refresh_access_token(
|
||||
effective_organization_id=refresh_token.effective_organization_id,
|
||||
epoch=refresh_token.epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
effective_roles=refresh_token.effective_roles,
|
||||
)
|
||||
|
||||
|
||||
@@ -1020,6 +1040,7 @@ def _set_refresh_token(
|
||||
effective_role: UserRole,
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
) -> RefreshTokenMetadata:
|
||||
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1038,10 +1059,12 @@ def _set_refresh_token(
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
}
|
||||
@@ -1058,6 +1081,7 @@ def _set_refresh_token(
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_roles=effective_roles,
|
||||
effective_organization_id=effective_organization_id,
|
||||
)
|
||||
|
||||
@@ -1069,6 +1093,7 @@ def _build_access_token(
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
) -> AccessToken:
|
||||
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1087,10 +1112,12 @@ def _build_access_token(
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
@@ -1108,6 +1135,7 @@ def _build_access_token(
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_roles=effective_roles,
|
||||
effective_organization_id=effective_organization_id,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
raw_token=raw_token,
|
||||
|
||||
@@ -91,6 +91,21 @@ def create_db_and_tables():
|
||||
"BOOLEAN NOT NULL DEFAULT TRUE"
|
||||
)
|
||||
)
|
||||
if "roles" not in columns:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"ALTER TABLE account ADD COLUMN roles "
|
||||
"JSON NOT NULL DEFAULT '[\"USER\"]'"
|
||||
)
|
||||
)
|
||||
if "role" in columns:
|
||||
connection.execute(
|
||||
text(
|
||||
"UPDATE account SET roles = '[\"' || role || '\"]' "
|
||||
"WHERE role IS NOT NULL"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface AccessToken {
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
effective_roles?: Array<UserRole>;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
roles: Array<UserRole>;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
|
||||
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
|
||||
export interface CreateAccountRequest {
|
||||
email: string;
|
||||
name: string;
|
||||
role?: UserRole;
|
||||
roles?: Array<UserRole>;
|
||||
organization_id: string;
|
||||
password: string;
|
||||
openalex_person_id?: string | null;
|
||||
|
||||
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
|
||||
export interface UpdateAccountRequest {
|
||||
email?: string | null;
|
||||
name?: string | null;
|
||||
role?: UserRole | null;
|
||||
roles?: Array<UserRole> | null;
|
||||
organization_id?: string | null;
|
||||
password?: string | null;
|
||||
openalex_person_id?: string | null;
|
||||
|
||||
@@ -186,7 +186,7 @@ export class AccountComponent {
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
this.roles = [this.accountProfile().role];
|
||||
this.roles = this.accountProfile().roles;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Rolle</mat-label>
|
||||
<mat-select formControlName="role">
|
||||
<mat-select formControlName="roles" multiple>
|
||||
@for (role of data.roles; track role) {
|
||||
<mat-option [value]="role">{{ role }}</mat-option>
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ export interface AccountDialogData {
|
||||
export interface AccountPayload {
|
||||
email?: string;
|
||||
name?: string;
|
||||
role?: UserRole;
|
||||
roles?: UserRole[];
|
||||
organization_id?: string;
|
||||
password?: string;
|
||||
deleted?: boolean;
|
||||
@@ -45,7 +45,7 @@ export interface AccountPayload {
|
||||
export interface CreateAccountPayload {
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
roles: UserRole[];
|
||||
organization_id: string;
|
||||
password: string;
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export class AccountDialogComponent {
|
||||
name: new FormControl<string>(this.data.account?.name ?? '', [
|
||||
Validators.required,
|
||||
]),
|
||||
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
|
||||
roles: new FormControl<UserRole[]>(this.data.account?.roles ?? ['USER'], [
|
||||
Validators.required,
|
||||
]),
|
||||
organizationId: new FormControl<string>(
|
||||
@@ -115,7 +115,7 @@ export class AccountDialogComponent {
|
||||
payload: {
|
||||
email: value.email ?? '',
|
||||
name: value.name ?? '',
|
||||
role: value.role ?? 'USER',
|
||||
roles: value.roles ?? ['USER'],
|
||||
organization_id: value.organizationId ?? '',
|
||||
password: value.password ?? '',
|
||||
},
|
||||
@@ -128,7 +128,7 @@ export class AccountDialogComponent {
|
||||
|
||||
const email = (value.email ?? '').trim();
|
||||
const name = (value.name ?? '').trim();
|
||||
const role = value.role ?? account.role;
|
||||
const roles = value.roles ?? account.roles;
|
||||
const organizationId = value.organizationId ?? account.organization_id;
|
||||
const password = value.password?.trim() ?? '';
|
||||
|
||||
@@ -140,8 +140,8 @@ export class AccountDialogComponent {
|
||||
payload.name = name;
|
||||
}
|
||||
|
||||
if (role !== account.role) {
|
||||
payload.role = role;
|
||||
if (!this.sameRoles(roles, account.roles)) {
|
||||
payload.roles = roles;
|
||||
}
|
||||
|
||||
if (password) {
|
||||
@@ -166,4 +166,10 @@ export class AccountDialogComponent {
|
||||
protected close(): void {
|
||||
this.dialogRef.close();
|
||||
}
|
||||
|
||||
private sameRoles(left: UserRole[], right: UserRole[]): boolean {
|
||||
return (
|
||||
left.length === right.length && left.every((role) => right.includes(role))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,9 @@
|
||||
</section>
|
||||
|
||||
<ng-template #accountRoleTmp let-row>
|
||||
<span class="role">{{ row.role | role }}</span>
|
||||
@for (role of row.roles; track role) {
|
||||
<span class="role">{{ role | role }}</span>
|
||||
}
|
||||
</ng-template>
|
||||
|
||||
<ng-template #accountStatusTmp let-row>
|
||||
|
||||
@@ -126,10 +126,10 @@ export class AccountsComponent implements OnInit {
|
||||
accessorKey: 'organization_name',
|
||||
},
|
||||
{
|
||||
id: 'role',
|
||||
id: 'roles',
|
||||
header: 'Rolle',
|
||||
type: 'accessor',
|
||||
accessorKey: 'role',
|
||||
accessorKey: 'roles',
|
||||
cellTemplate: this.accountRoleTmp(),
|
||||
},
|
||||
{
|
||||
@@ -325,7 +325,22 @@ export class AccountsComponent implements OnInit {
|
||||
|
||||
return (
|
||||
this.credentialService.isEffectiveAdmin() &&
|
||||
(account.role === 'MANAGER' || account.role === 'USER')
|
||||
(this.effectiveRole(account) === 'MANAGER' ||
|
||||
this.effectiveRole(account) === 'USER')
|
||||
);
|
||||
}
|
||||
|
||||
protected effectiveRole(account: AccountProfile): UserRole {
|
||||
const roles = account.roles;
|
||||
if (roles.includes('SUPER_ADMIN')) {
|
||||
return 'SUPER_ADMIN';
|
||||
}
|
||||
if (roles.includes('ADMIN')) {
|
||||
return 'ADMIN';
|
||||
}
|
||||
if (roles.includes('MANAGER')) {
|
||||
return 'MANAGER';
|
||||
}
|
||||
return 'USER';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user