active-deactive-accounts #187

Merged
farajollahi merged 2 commits from active-deactive-accounts into dev 2026-07-03 19:24:16 +02:00
21 changed files with 594 additions and 49 deletions
@@ -20,6 +20,7 @@ class AccountProfile(BaseModel):
organization_id: uuid.UUID
organization_name: str
deleted: bool
activated: bool
is_current: bool = False
is_real_account: bool = False
is_impersonating: bool = False
@@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel):
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
activated: Optional[bool] = None
@@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
activated=account.activated,
is_current=account.id == token.effective_account_id,
is_real_account=account.id == token.real_account_id,
is_impersonating=token.is_impersonating(),
@@ -108,17 +109,21 @@ def list_accounts(
search: Optional[str] = None,
organization_id: Optional[uuid.UUID] = None,
) -> AccountPage:
if not _is_admin(access_token.effective_role):
if access_token.effective_role not in {
UserRole.SUPER_ADMIN,
UserRole.ADMIN,
UserRole.MANAGER,
}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can list accounts.",
detail="Only managers and admins can list accounts.",
)
statement = select(Account)
count_statement = select(func.count()).select_from(Account)
filters = []
if access_token.effective_role == UserRole.ADMIN:
if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}:
filters.append(Account.organization_id == access_token.effective_organization_id)
elif organization_id is not None:
filters.append(Account.organization_id == organization_id)
@@ -207,7 +212,7 @@ def list_organizations(
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
select(Organization)
.where(Organization.deleted == False) # noqa: E712
.where(Organization.deleted.is_not(True))
.order_by(Organization.name)
).all()
elif access_token.effective_role == UserRole.ADMIN:
@@ -285,6 +290,15 @@ def update_account(
account.deleted = payload.deleted
account.epoch += 1
if payload.activated is not None and payload.activated != account.activated:
if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only super admins can activate or deactivate other accounts.",
)
account.activated = payload.activated
account.epoch += 1
session.add(account)
session.commit()
session.refresh(account)
@@ -0,0 +1,180 @@
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse.account_management import service
from inse.account_management.model import UpdateAccountRequest
from inse.auth.model import Account, Organization, UserRole
@pytest.fixture()
def session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as database_session:
yield database_session
def access_token(role, account_id, organization_id):
return SimpleNamespace(
effective_role=role,
effective_account_id=account_id,
real_account_id=account_id,
effective_organization_id=organization_id,
is_impersonating=lambda: False,
)
def create_accounts(session):
organization = Organization(name="Test organization")
session.add(organization)
session.flush()
superadmin = Account(
email="superadmin@example.org",
name="Superadmin",
password_hash="hash",
organization_id=organization.id,
role=UserRole.SUPER_ADMIN,
)
user = Account(
email="user@example.org",
name="User",
password_hash="hash",
organization_id=organization.id,
)
session.add(superadmin)
session.add(user)
session.commit()
return organization, superadmin, user
def test_accounts_are_activated_by_default(session):
_, _, user = create_accounts(session)
assert user.activated is True
def test_superadmin_can_deactivate_and_reactivate_account(session):
organization, superadmin, user = create_accounts(session)
token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id)
profile = service.update_account(
session, token, user.id, UpdateAccountRequest(activated=False)
)
assert profile.activated is False
assert user.epoch == 1
profile = service.update_account(
session, token, user.id, UpdateAccountRequest(activated=True)
)
assert profile.activated is True
assert user.epoch == 2
def test_non_superadmin_cannot_change_activation(session):
organization, superadmin, user = create_accounts(session)
admin = Account(
email="admin@example.org",
name="Admin",
password_hash="hash",
organization_id=organization.id,
role=UserRole.ADMIN,
)
session.add(admin)
session.commit()
with pytest.raises(HTTPException) as error:
service.update_account(
session,
access_token(UserRole.ADMIN, admin.id, organization.id),
user.id,
UpdateAccountRequest(activated=False),
)
assert error.value.status_code == 403
assert user.activated is True
def test_superadmin_cannot_deactivate_own_account(session):
organization, superadmin, _ = create_accounts(session)
with pytest.raises(HTTPException) as error:
service.update_account(
session,
access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id),
superadmin.id,
UpdateAccountRequest(activated=False),
)
assert error.value.status_code == 403
assert superadmin.activated is True
def test_manager_only_lists_accounts_from_own_organization(session):
organization, superadmin, user = create_accounts(session)
manager = Account(
email="manager@example.org",
name="Manager",
password_hash="hash",
organization_id=organization.id,
role=UserRole.MANAGER,
)
other_organization = Organization(name="Other organization")
session.add(other_organization)
session.flush()
other_user = Account(
email="other@example.org",
name="Other User",
password_hash="hash",
organization_id=other_organization.id,
)
session.add(manager)
session.add(other_user)
session.commit()
result = service.list_accounts(
session,
access_token(UserRole.MANAGER, manager.id, organization.id),
page=0,
page_size=25,
organization_id=other_organization.id,
)
assert {profile.id for profile in result.items} == {
account.id for account in [superadmin, user, manager]
}
assert other_user.id not in {profile.id for profile in result.items}
def test_user_cannot_list_accounts(session):
organization, _, user = create_accounts(session)
with pytest.raises(HTTPException) as error:
service.list_accounts(
session,
access_token(UserRole.USER, user.id, organization.id),
page=0,
page_size=25,
)
assert error.value.status_code == 403
def test_superadmin_lists_all_active_organizations_for_selectbox(session):
first = Organization(name="Alpha")
second = Organization(name="Beta")
deleted = Organization(name="Deleted", deleted=True)
session.add(first)
session.add(second)
session.add(deleted)
session.commit()
organizations = service.list_organizations(
session,
access_token(UserRole.SUPER_ADMIN, first.id, first.id),
)
assert [organization.name for organization in organizations] == ["Alpha", "Beta"]
+6
View File
@@ -77,6 +77,12 @@ class Account(Durable, table=True):
nullable=False,
description="The epoch value for the account. Used for versioning of tokens.",
)
activated: bool = Field(
default=True,
nullable=False,
index=True,
description="Indicates whether the account is allowed to authenticate.",
)
password_hash: str = Field(
index=False,
nullable=False,
+37 -7
View File
@@ -180,7 +180,11 @@ def request_otk(session: Session, email: str, password: str):
logger.debug("OTK request for email %s: account found: %s", email, account)
if account is None or account.deleted or account.id is None:
if (
account is None
or account.deleted
or account.id is None
):
logger.warning("OTK request failed for email %s: account not found", email)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -196,6 +200,13 @@ def request_otk(session: Session, email: str, password: str):
detail="Invalid email or password",
)
if not account.activated:
logger.warning("OTK request rejected for deactivated account %s", account.id)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is deactivated and cannot log in.",
)
otk_code = f"{secrets.randbelow(1_000_000):06d}"
print(otk_code)
@@ -300,7 +311,7 @@ def login(
)
account = _get_active_account(session, account_id)
if not account or account.deleted or account.id is None:
if not account or account.deleted or not account.activated or account.id is None:
logger.warning("Login failed: account is not active %s", account_id)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -469,7 +480,12 @@ def _get_account_epoch(
"""
account = session.get(Account, account_id)
if account is None or account.deleted or account.id is None:
if (
account is None
or account.deleted
or not account.activated
or account.id is None
):
raise AccountNotFoundException
return account.epoch
@@ -487,7 +503,7 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
"""
account = session.get(Account, account_id)
if not account or account.deleted or account.id is None:
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.role
@@ -505,7 +521,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
"""
account = session.get(Account, account_id)
if not account or account.deleted or account.id is None:
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.organization_id
@@ -525,12 +541,18 @@ def _is_valid_impersonation(
bool: True if impersonation is allowed, False otherwise.
"""
real_account = session.get(Account, real_account_id)
if not real_account or real_account.deleted or real_account.id is None:
if (
not real_account
or real_account.deleted
or not real_account.activated
or real_account.id is None
):
raise AccountNotFoundException
effective_account = session.get(Account, effective_account_id)
if (
not effective_account
or effective_account.deleted
or not effective_account.activated
or effective_account.id is None
):
raise AccountNotFoundException
@@ -980,6 +1002,9 @@ def _verify_fp_token(
account_id=epoch_account_id,
)
if uuid.UUID(real_account_id) != epoch_account_id:
_get_active_account(session, uuid.UUID(real_account_id))
token_epoch = payload.get(EPOCH_KEY)
if token_epoch is None or token_epoch != current_account_epoch:
raise HTTPException(
@@ -1016,7 +1041,12 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
"""
account = session.get(Account, account_id)
if account is None or account.deleted or account.id is None:
if (
account is None
or account.deleted
or not account.activated
or account.id is None
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is not active.",
@@ -210,6 +210,35 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
auth_service.request_otk(in_memory_session, email, "wrongpw")
def test_deactivated_account_cannot_request_otk(in_memory_session):
email = "inactive@example.com"
password = "rightpw"
_, account = create_org_and_account(in_memory_session, email, password)
account.activated = False
in_memory_session.add(account)
in_memory_session.commit()
with pytest.raises(HTTPException) as error:
auth_service.request_otk(in_memory_session, email, password)
assert error.value.status_code == 403
assert error.value.detail == "Account is deactivated and cannot log in."
def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session):
_, account = create_org_and_account(
in_memory_session, "inactive-lookup@example.com", "password"
)
account.activated = False
in_memory_session.add(account)
in_memory_session.commit()
with pytest.raises(HTTPException) as error:
auth_service._get_active_account(in_memory_session, account.id)
assert error.value.status_code == 403
def test_login_with_expired_secret(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "expired-key"
config_module.settings.token_issuer_id = "expired-issuer"
+10
View File
@@ -1,6 +1,7 @@
from typing import Annotated
from fastapi import Depends
from sqlalchemy import inspect, text
from sqlmodel import SQLModel, Session, create_engine
from inse import config
@@ -18,6 +19,15 @@ engine = create_engine(
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
columns = {column["name"] for column in inspect(engine).get_columns("account")}
if "activated" not in columns:
with engine.begin() as connection:
connection.execute(
text(
"ALTER TABLE account ADD COLUMN activated "
"BOOLEAN NOT NULL DEFAULT TRUE"
)
)
def get_session():
@@ -73,6 +73,7 @@ def _member_counts(
.where(
Account.organization_id.in_(organization_ids),
Account.deleted == False, # noqa: E712
Account.activated == True, # noqa: E712
)
.group_by(Account.organization_id)
).all()
@@ -91,6 +92,21 @@ def _to_profile(
)
def _deactivate_organization_accounts(
session: Session, organization_id: uuid.UUID
) -> None:
accounts = session.exec(
select(Account).where(
Account.organization_id == organization_id,
Account.activated == True, # noqa: E712
)
).all()
for account in accounts:
account.activated = False
account.epoch += 1
session.add(account)
def get_organizations(
session: Session,
access_token: AccessToken,
@@ -162,6 +178,8 @@ def update_organization(
if payload.other_inst_id is not None:
organization.openalex_institution_id = payload.other_inst_id.strip() or None
if payload.deleted is not None:
if payload.deleted and not organization.deleted:
_deactivate_organization_accounts(session, organization.id)
organization.deleted = payload.deleted
session.add(organization)
@@ -178,6 +196,8 @@ def delete_organization(
) -> None:
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
if not organization.deleted:
_deactivate_organization_accounts(session, organization.id)
organization.deleted = True
session.add(organization)
session.commit()
@@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session):
assert session.get(Organization, created.id).deleted is True
def test_deleting_organization_deactivates_all_its_accounts(session):
organization = Organization(name="Organization to delete")
session.add(organization)
session.flush()
active_account = Account(
email="active-delete@example.org",
name="Active",
password_hash="hash",
organization_id=organization.id,
epoch=3,
)
inactive_account = Account(
email="inactive-delete@example.org",
name="Inactive",
password_hash="hash",
organization_id=organization.id,
activated=False,
epoch=5,
)
session.add(active_account)
session.add(inactive_account)
session.commit()
service.delete_organization(
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
)
session.refresh(active_account)
session.refresh(inactive_account)
assert active_account.activated is False
assert active_account.epoch == 4
assert inactive_account.activated is False
assert inactive_account.epoch == 5
def test_marking_organization_deleted_deactivates_its_accounts(session):
organization = Organization(name="Organization to update")
session.add(organization)
session.flush()
account = Account(
email="active-update@example.org",
name="Active",
password_hash="hash",
organization_id=organization.id,
)
session.add(account)
session.commit()
service.update_organization(
session,
token(UserRole.SUPER_ADMIN, organization.id),
organization.id,
UpdateOrganizationRequest(deleted=True),
)
session.refresh(account)
assert account.activated is False
assert account.epoch == 1
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
def test_only_superadmin_can_create_organizations(session, role):
organization = Organization(name="Scope")
+1 -1
View File
@@ -18,6 +18,7 @@ export interface AccountProfile {
organization_id: string;
organization_name: string;
deleted: boolean;
activated: boolean;
is_current?: boolean;
is_real_account?: boolean;
is_impersonating?: boolean;
@@ -25,4 +26,3 @@ export interface AccountProfile {
export namespace AccountProfile {
}
@@ -18,8 +18,8 @@ export interface UpdateAccountRequest {
password?: string | null;
openalex_person_id?: string | null;
deleted?: boolean | null;
activated?: boolean | null;
}
export namespace UpdateAccountRequest {
}
+2 -2
View File
@@ -1,6 +1,5 @@
import { Routes } from '@angular/router';
import { userGuard } from './shared/guards/user.guard';
import { adminGuard } from './shared/guards/admin.guard';
import { superAdminGuard } from './shared/guards/super-admin.guard';
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
import { personListResolver } from './resolvers/person-list.resolver';
@@ -20,6 +19,7 @@ import { fundingProjectPageResolver } from './resolvers/funding-project-page.res
import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver';
import { publicationResolver } from './resolvers/publication-resolver';
import { accountResolver } from './resolvers/account.resolver';
import { accountViewerGuard } from './shared/guards/account-viewer.guard';
export const routes: Routes = [
{
@@ -109,7 +109,7 @@ export const routes: Routes = [
},
{
path: 'accounts',
canActivate: [adminGuard],
canActivate: [accountViewerGuard],
loadComponent: () =>
import('./modules/accounts/accounts.component').then(
(mod) => mod.AccountsComponent,
@@ -2,16 +2,25 @@
<header class="page-header">
<div>
<h1>Accounts</h1>
<p>Account-Zugänge verwalten, Rollen setzen und Impersonation starten.</p>
<p>
{{
isReadOnly
? 'Personen der eigenen Organisation ansehen.'
: 'Account-Zugänge verwalten, Rollen setzen und Impersonation starten.'
}}
</p>
</div>
<button
mat-flat-button
color="primary"
type="button"
(click)="startCreate()">
<mat-icon>person_add</mat-icon>
Neuer Account
</button>
@if (!isReadOnly) {
<button
mat-flat-button
color="primary"
type="button"
matTooltip="Neuen Account anlegen"
(click)="startCreate()">
<mat-icon>person_add</mat-icon>
Neuer Account
</button>
}
</header>
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()">
@@ -35,11 +44,19 @@
}
<div class="filter-actions">
<button mat-flat-button color="primary" type="submit">
<button
mat-flat-button
color="primary"
type="submit"
matTooltip="Accounts mit den gewählten Filtern suchen">
<mat-icon>search</mat-icon>
Suchen
</button>
<button mat-button type="button" (click)="resetFilters()">
<button
mat-button
type="button"
matTooltip="Alle Suchfilter zurücksetzen"
(click)="resetFilters()">
Zurücksetzen
</button>
</div>
@@ -62,19 +79,28 @@
<th>Organisation</th>
<th>Rolle</th>
<th>Status</th>
<th>Aktionen</th>
@if (!isReadOnly) {
<th>Aktionen</th>
}
</tr>
</thead>
<tbody>
@for (account of accounts; track account.id) {
<tr [class.deleted]="account.deleted">
<tr
[class.deleted]="account.deleted"
[class.deactivated]="!account.activated">
<td>
<button
class="link-button"
type="button"
(click)="startEdit(account)">
@if (isReadOnly) {
{{ account.name }}
</button>
} @else {
<button
class="link-button"
type="button"
[matTooltip]="'Account „' + account.name + '“ bearbeiten'"
(click)="startEdit(account)">
{{ account.name }}
</button>
}
</td>
<td>{{ account.email }}</td>
<td>{{ account.organization_name }}</td>
@@ -82,16 +108,29 @@
<span class="role">{{ account.role | role }}</span>
</td>
<td>
<span class="status" [class.status--deleted]="account.deleted">
{{ account.deleted ? 'deleted' : 'active' }}
<span
class="status"
[class.status--deleted]="account.deleted"
[class.status--deactivated]="
!account.deleted && !account.activated
">
{{
account.deleted
? 'deleted'
: account.activated
? 'active'
: 'inactive'
}}
</span>
</td>
<td>
<div class="row-actions">
@if (!isReadOnly) {
<td>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
matTooltip="Account bearbeiten"
(click)="startEdit(account)">
<mat-icon>edit</mat-icon>
</button>
@@ -99,24 +138,48 @@
mat-icon-button
type="button"
aria-label="Impersonate"
matTooltip="Als dieser Account anmelden"
[disabled]="!canImpersonate(account)"
(click)="impersonate(account)">
<mat-icon>switch_account</mat-icon>
</button>
@if (credentialService.isEffectiveSuperAdmin()) {
<button
mat-icon-button
type="button"
[attr.aria-label]="
account.activated ? 'Deaktivieren' : 'Aktivieren'
"
[matTooltip]="
account.activated
? 'Account deaktivieren'
: 'Account aktivieren'
"
[disabled]="account.is_current || account.deleted"
(click)="toggleAccountActivation(account)">
<mat-icon>{{
account.activated ? 'person_off' : 'person_check'
}}</mat-icon>
</button>
}
<button
mat-icon-button
type="button"
aria-label="Deaktivieren"
aria-label="Löschen"
matTooltip="Account löschen"
[disabled]="account.is_current || account.deleted"
(click)="deleteAccount(account)">
<mat-icon>delete</mat-icon>
</button>
</div>
</td>
</div>
</td>
}
</tr>
} @empty {
<tr>
<td colspan="6" class="empty">Keine Accounts gefunden.</td>
<td [attr.colspan]="isReadOnly ? 5 : 6" class="empty">
Keine Accounts gefunden.
</td>
</tr>
}
</tbody>
@@ -127,6 +190,7 @@
<button
mat-button
type="button"
matTooltip="Vorherige Seite anzeigen"
[disabled]="!canPageBack"
(click)="loadAccounts(page - 1)">
<mat-icon>chevron_left</mat-icon>
@@ -136,6 +200,7 @@
<button
mat-button
type="button"
matTooltip="Nächste Seite anzeigen"
[disabled]="!canPageForward"
(click)="loadAccounts(page + 1)">
Weiter
@@ -88,6 +88,11 @@ tr.deleted {
color: #94a3b8;
}
tr.deactivated:not(.deleted) {
color: #64748b;
background: #f8fafc;
}
.link-button {
border: 0;
background: transparent;
@@ -120,6 +125,11 @@ tr.deleted {
color: #991b1b;
}
.status--deactivated {
background: #fef3c7;
color: #92400e;
}
.row-actions {
gap: 4px;
}
@@ -7,6 +7,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { finalize } from 'rxjs';
@@ -34,6 +35,7 @@ import { RolePipe } from '../../shared/pipes/role.pipe';
MatInputModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
MatDialogModule,
RolePipe,
],
@@ -48,6 +50,10 @@ export class AccountsComponent implements OnInit {
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
protected get isReadOnly(): boolean {
return this.credentialService.isEffectiveManager();
}
protected get availableRoles(): AccountRole[] {
if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
@@ -68,7 +74,9 @@ export class AccountsComponent implements OnInit {
});
ngOnInit(): void {
this.loadOrganizations();
if (!this.isReadOnly) {
this.loadOrganizations();
}
this.loadAccounts();
}
@@ -102,6 +110,13 @@ export class AccountsComponent implements OnInit {
next: (organizations) => {
this.organizations = organizations;
},
error: () => {
this.snackBar.open(
'Organisationen konnten nicht geladen werden.',
'OK',
{ duration: 5000 },
);
},
});
}
@@ -199,6 +214,59 @@ export class AccountsComponent implements OnInit {
});
}
protected toggleAccountActivation(account: AccountProfile): void {
if (
!this.credentialService.isEffectiveSuperAdmin() ||
account.is_current ||
account.deleted
) {
return;
}
const activated = !account.activated;
const action = activated ? 'aktivieren' : 'deaktivieren';
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
({ ConfirmationDialogComponent }) => {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: {
title: activated ? 'Account aktivieren' : 'Account deaktivieren',
message: `Möchtest Du den Account „${account.name}“ wirklich ${action}?`,
confirmText: activated ? 'Aktivieren' : 'Deaktivieren',
cancelText: 'Abbrechen',
},
});
dialogRef.componentInstance.confirmDelete.subscribe(() => {
this.updateAccountActivation(account, activated);
});
},
);
}
private updateAccountActivation(
account: AccountProfile,
activated: boolean,
): void {
this.accountService.updateAccount(account.id, { activated }).subscribe({
next: () => {
this.snackBar.open(
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
'OK',
{ duration: 3000 },
);
this.loadAccounts();
},
error: () => {
this.snackBar.open(
'Account-Status konnte nicht geändert werden.',
'OK',
{ duration: 5000 },
);
},
});
}
protected impersonate(account: AccountProfile): void {
if (!this.canImpersonate(account)) {
return;
@@ -232,7 +300,7 @@ export class AccountsComponent implements OnInit {
}
protected canImpersonate(account: AccountProfile): boolean {
if (account.is_current || account.deleted) {
if (account.is_current || account.deleted || !account.activated) {
return false;
}
@@ -245,7 +245,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
}
if (error.status === 403) {
return 'Dieses Konto ist nicht für die Anmeldung freigeschaltet.';
return 'Dieser Account ist deaktiviert und kann sich nicht anmelden.';
}
return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.';
@@ -0,0 +1,36 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { catchError, filter, of, switchMap, take } from 'rxjs';
import { CredentialService } from '../services/credential.service';
export const accountViewerGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
return credentialService.validating.pipe(
filter((validating) => !validating),
take(1),
switchMap(() => {
if (!credentialService.isAuthenticated.value) {
void router.navigate(['/login']);
return of(false);
}
return credentialService.validateCurrentSession().pipe(
switchMap(() => {
const mayViewAccounts =
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin() ||
credentialService.isEffectiveManager();
if (!mayViewAccounts) {
void router.navigate(['/dashboard']);
}
return of(mayViewAccounts);
}),
catchError(() => of(false)),
);
}),
);
};
@@ -13,6 +13,7 @@ export interface AccountProfile {
organization_id: string;
organization_name: string;
deleted: boolean;
activated: boolean;
is_current: boolean;
is_real_account: boolean;
is_impersonating: boolean;
@@ -38,6 +39,7 @@ export interface AccountPayload {
organization_id?: string;
password?: string;
deleted?: boolean;
activated?: boolean;
}
export interface CreateAccountPayload {
@@ -45,6 +45,9 @@ export class CredentialService {
public readonly isEffectiveAdmin = computed(
() => this.accessToken()?.effective_role === 'ADMIN',
);
public readonly isEffectiveManager = computed(
() => this.accessToken()?.effective_role === 'MANAGER',
);
public readonly effectiveOrganizationId = computed(
() => this.accessToken()?.effective_organization_id,
);
@@ -48,7 +48,11 @@
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin()) &&
(!itemGroup.superAdminOnly ||
credentialService.isEffectiveSuperAdmin())
credentialService.isEffectiveSuperAdmin()) &&
(!itemGroup.managerOrAdminOnly ||
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin() ||
credentialService.isEffectiveManager())
) {
<mat-divider></mat-divider>
@if (!collapsed()) {
@@ -19,6 +19,7 @@ type NavItem = {
queryParams?: Record<string, string | number | boolean>;
adminOnly?: boolean;
superAdminOnly?: boolean;
managerOrAdminOnly?: boolean;
};
type NavItemGroup = {
@@ -26,6 +27,7 @@ type NavItemGroup = {
items: NavItem[];
adminOnly?: boolean;
superAdminOnly?: boolean;
managerOrAdminOnly?: boolean;
};
@Component({
@@ -125,7 +127,7 @@ export class AppMenuComponent {
icon: 'manage_accounts',
route: '/accounts',
disabled: false,
adminOnly: true,
managerOrAdminOnly: true,
},
{
label: 'Organisationen',
@@ -139,15 +141,19 @@ export class AppMenuComponent {
{
label: 'Navigation',
items: this.navItems.filter(
(item) => !item.adminOnly && !item.superAdminOnly,
(item) =>
!item.adminOnly &&
!item.superAdminOnly &&
!item.managerOrAdminOnly,
),
},
{
label: 'Administration',
items: this.navItems.filter(
(item) => item.adminOnly && !item.superAdminOnly,
(item) =>
(item.adminOnly || item.managerOrAdminOnly) && !item.superAdminOnly,
),
adminOnly: true,
managerOrAdminOnly: true,
},
{
label: 'Super Administration',