fix(frontend/accounts): unfucked everything

This commit is contained in:
Mats Paul Tončik
2026-07-04 23:49:39 +02:00
29 changed files with 676 additions and 294 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
@@ -181,7 +181,11 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
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,
@@ -197,6 +201,13 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
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)
@@ -301,7 +312,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,
@@ -470,7 +481,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
@@ -488,7 +504,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
@@ -506,7 +522,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
@@ -526,12 +542,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
@@ -981,6 +1003,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(
@@ -1017,7 +1042,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
View File
@@ -5,6 +5,7 @@ import {
Router,
withComponentInputBinding,
withNavigationErrorHandler,
withRouterConfig,
} from '@angular/router';
import { routes } from './app.routes';
@@ -37,6 +38,7 @@ export const appConfig: ApplicationConfig = {
provideRouter(
routes,
withComponentInputBinding(),
withRouterConfig({ onSameUrlNavigation: 'reload' }),
withNavigationErrorHandler((navigationError: NavigationError) => {
const router = inject(Router);
const errorService = inject(ErrorService);
+5 -9
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';
@@ -9,7 +8,6 @@ import { personResolver } from './resolvers/person.resolver';
import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
@@ -20,7 +18,9 @@ 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';
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
import { organizationsResolver } from './resolvers/organizations.resolver';
export const routes: Routes = [
{
@@ -110,20 +110,16 @@ export const routes: Routes = [
},
{
path: 'accounts',
canActivate: [adminGuard],
canActivate: [accountViewerGuard],
loadComponent: () =>
import('./modules/accounts/accounts.component').then(
(mod) => mod.AccountsComponent,
),
resolve: {
accountPage: accountsPageResolver,
organizations: organizationsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'search', 'organization_id'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
runGuardsAndResolvers: 'always',
},
{
path: 'organizations',
@@ -16,22 +16,38 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import type {
AccountPayload,
import {
AccountProfile,
AccountRole,
CreateAccountPayload,
OrganizationProfile,
} from '../../shared/services/account-management.service';
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
export type AccountDialogMode = 'create' | 'edit';
export interface AccountDialogData {
mode: AccountDialogMode;
account?: AccountProfile;
organizations: OrganizationProfile[];
organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean;
roles: AccountRole[];
roles: UserRole[];
}
export interface AccountPayload {
email?: string;
name?: string;
role?: UserRole;
organization_id?: string;
password?: string;
deleted?: boolean;
activated?: boolean;
}
export interface CreateAccountPayload {
email: string;
name: string;
role: UserRole;
organization_id: string;
password: string;
}
export type AccountDialogResult =
@@ -69,7 +85,7 @@ export class AccountDialogComponent {
name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required,
]),
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
Validators.required,
]),
organizationId: new FormControl<string>(
@@ -148,6 +164,6 @@ export class AccountDialogComponent {
}
protected close(): void {
this.dialogRef.close(undefined);
this.dialogRef.close();
}
}
@@ -2,34 +2,39 @@
<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>
<div
style="
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
">
<section style="display: flex; gap: 1rem; align-items: center">
<app-query-param-input
queryParamKey="search"
label="Nach Name oder E-Mail suchen"
style="width: 30%" />
style="width: 35%" />
<app-query-param-selector
queryParamKey="organization_id"
[options]="selectorOptions"
label="Organisation" />
</div>
[options]="selectorOptions()"
label="Organisation"
[allowEmptyValue]="true"
style="width: 25%" />
</section>
<mat-card appearance="outlined">
<mat-card-content>
<app-data-table [columns]="accountColumns" [data]="accountPage().items" />
@@ -43,8 +48,13 @@
</ng-template>
<ng-template #accountStatusTmp let-row>
<span class="status" [class.status--deleted]="row.deleted">
{{ row.deleted ? 'deleted' : 'active' }}
<span
class="status"
[class.status--deleted]="row.deleted"
[class.status--deactivated]="!row.deleted && !row.activated">
{{
(row.deleted ? 'deleted' : row.activated ? 'active' : 'inactive') | status
}}
</span>
</ng-template>
@@ -65,6 +75,14 @@
(click)="impersonate(row)">
<mat-icon>switch_account</mat-icon>
</button>
<button
mat-icon-button
type="button"
[attr.aria-label]="row.activated ? 'Deaktivieren' : 'Aktivieren'"
[disabled]="row.is_current || row.deleted"
(click)="toggleAccountActivation(row)">
<mat-icon>{{ row.activated ? 'person_off' : 'person_check' }}</mat-icon>
</button>
<button
mat-icon-button
type="button"
@@ -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;
}
@@ -3,26 +3,22 @@ import {
Component,
OnInit,
TemplateRef,
effect,
computed,
inject,
input,
viewChild,
} from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
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';
import {
AccountManagementService,
AccountRole,
OrganizationProfile,
} from '../../shared/services/account-management.service';
import { CredentialService } from '../../shared/services/credential.service';
import type {
AccountDialogComponent,
@@ -40,7 +36,14 @@ import {
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
import { MatCardModule } from '@angular/material/card';
import { AccountPage, AccountProfile } from '../../api';
import {
AccountPage,
AccountProfile,
AuthService,
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
import { StatusPipe } from '../../shared/pipes/status.pipe';
@Component({
selector: 'app-accounts',
@@ -53,6 +56,7 @@ import { AccountPage, AccountProfile } from '../../api';
MatInputModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
MatDialogModule,
RolePipe,
DataTableComponent,
@@ -60,55 +64,48 @@ import { AccountPage, AccountProfile } from '../../api';
QueryParamInputComponent,
QueryParamSelectorComponent,
MatCardModule,
StatusPipe
],
templateUrl: './accounts.component.html',
styleUrl: './accounts.component.scss',
standalone: true,
})
export class AccountsComponent implements OnInit {
private readonly accountService = inject(AccountManagementService);
protected readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
private readonly authService = inject(AuthService);
protected get availableRoles(): AccountRole[] {
if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
}
return ['MANAGER', 'USER'];
protected get isReadOnly(): boolean {
return this.credentialService.isEffectiveManager();
}
protected accounts: AccountProfile[] = [];
protected organizations: OrganizationProfile[] = [];
protected total = 0;
protected page = 0;
protected readonly pageSize = 10;
protected isLoading = false;
protected filterForm = new FormGroup({
search: new FormControl<string>(''),
organizationId: new FormControl<string>(''),
});
accountColumns: GenericColumn<AccountProfile>[] = [];
accountRoleTmp = viewChild.required<TemplateRef<any>>('accountRoleTmp');
accountStatusTmp = viewChild.required<TemplateRef<any>>('accountStatusTmp');
accountActionsTmp = viewChild.required<TemplateRef<any>>('accountActionsTmp');
selectorOptions: SelectorOption[] = [];
availableRoles = computed<UserRole[]>(() => {
if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
}
return ['MANAGER', 'USER'];
});
selectorOptions = computed<SelectorOption[]>(() => {
return this.organizations().map((org) => ({
value: org.id,
display_name: org.name,
}));
});
accountPage = input.required<AccountPage>();
constructor() {
effect(() => {
console.log('accountPage changed:', this.accountPage());
});
}
organizations =
input.required<InseAccountManagementModelOrganizationProfile[]>();
ngOnInit(): void {
this.loadOrganizations();
this.loadAccounts();
this.accountColumns = [
{
id: 'name',
@@ -150,52 +147,6 @@ export class AccountsComponent implements OnInit {
];
}
protected loadAccounts(page = this.page): void {
this.page = page;
this.isLoading = true;
this.accountService
.listAccounts({
page: this.page,
pageSize: this.pageSize,
search: this.filterForm.controls.search.value?.trim() || undefined,
organizationId:
this.filterForm.controls.organizationId.value || undefined,
})
.pipe(finalize(() => (this.isLoading = false)))
.subscribe({
next: (result) => {
this.accounts = result.items;
this.total = result.total;
},
error: () => {
this.snackBar.open('Accounts konnten nicht geladen werden.', 'OK', {
duration: 5000,
});
},
});
}
protected loadOrganizations(): void {
this.accountService.listOrganizations().subscribe({
next: (organizations) => {
this.organizations = organizations;
this.selectorOptions = organizations.map((org) => ({
value: org.id,
display_name: org.name,
}));
},
});
}
protected applyFilters(): void {
this.loadAccounts(0);
}
protected resetFilters(): void {
this.filterForm.reset({ search: '', organizationId: '' });
this.loadAccounts(0);
}
protected startCreate(): void {
this.openAccountDialog({ mode: 'create' });
}
@@ -207,15 +158,18 @@ export class AccountsComponent implements OnInit {
private saveDialogResult(result: AccountDialogResult): void {
const request =
result.mode === 'create'
? this.accountService.createAccount(result.payload)
: this.accountService.updateAccount(result.accountId, result.payload);
? this.authService.createAccount(result.payload)
: this.authService.updateAccount(result.accountId, result.payload);
request.subscribe({
next: () => {
this.snackBar.open('Account wurde gespeichert.', 'OK', {
duration: 3000,
});
this.loadAccounts(0);
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: (error) => {
const message =
@@ -237,9 +191,9 @@ export class AccountsComponent implements OnInit {
{
mode: 'create' | 'edit';
account?: AccountProfile;
organizations: OrganizationProfile[];
organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean;
roles: AccountRole[];
roles: UserRole[];
},
AccountDialogResult | undefined
>(AccountDialogComponent, {
@@ -247,9 +201,9 @@ export class AccountsComponent implements OnInit {
maxWidth: 'calc(100vw - 32px)',
data: {
...data,
organizations: this.organizations,
organizations: this.organizations(),
canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(),
roles: this.availableRoles,
roles: this.availableRoles(),
},
});
@@ -266,12 +220,15 @@ export class AccountsComponent implements OnInit {
return;
}
this.accountService.deleteAccount(account.id).subscribe({
this.authService.deleteAccount(account.id).subscribe({
next: () => {
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
duration: 3000,
});
this.loadAccounts();
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
@@ -281,6 +238,62 @@ 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.authService.updateAccount(account.id, { activated }).subscribe({
next: () => {
this.snackBar.open(
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
'OK',
{ duration: 3000 },
);
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
this.snackBar.open(
'Account-Status konnte nicht geändert werden.',
'OK',
{ duration: 5000 },
);
},
});
}
protected async impersonate(account: AccountProfile): Promise<void> {
if (!this.canImpersonate(account)) {
return;
@@ -301,16 +314,8 @@ export class AccountsComponent implements OnInit {
}
}
protected get canPageBack(): boolean {
return this.page > 0;
}
protected get canPageForward(): boolean {
return (this.page + 1) * this.pageSize < this.total;
}
protected canImpersonate(account: AccountProfile): boolean {
if (account.is_current || account.deleted) {
if (account.is_current || account.deleted || !account.activated) {
return false;
}
@@ -232,7 +232,7 @@ export class AppLoginComponent implements 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.';
@@ -4,7 +4,6 @@ import {
OnDestroy,
signal,
DestroyRef,
OnInit,
effect,
} from '@angular/core';
import { CommonModule } from '@angular/common';
+2 -3
View File
@@ -1,8 +1,7 @@
import { ResolveFn } from '@angular/router';
import { AccountProfile } from '../api';
import { AccountProfile, AuthService } from '../api';
import { inject } from '@angular/core';
import { AccountManagementService } from '../shared/services/account-management.service';
export const accountResolver: ResolveFn<AccountProfile> = (route, state) => {
return inject(AccountManagementService).getCurrentAccount();
return inject(AuthService).getCurrentAccount();
};
@@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import {
AuthService,
InseAccountManagementModelOrganizationProfile,
} from '../api';
export const organizationsResolver: ResolveFn<
InseAccountManagementModelOrganizationProfile[]
> = (route, state) => {
return inject(AuthService).listAccountOrganizations();
};
@@ -0,0 +1,41 @@
import { effect, inject, Injector } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { CredentialService } from '../services/credential.service';
export const accountViewerGuard: CanActivateFn = () => {
const credentialService = inject(CredentialService);
const router = inject(Router);
const injector = inject(Injector);
return new Promise<boolean>((resolve) => {
const ref = effect(
() => {
if (credentialService.isValidating()) {
return;
}
ref.destroy();
if (!credentialService.isAuthenticated()) {
void router.navigate(['/login']);
resolve(false);
return;
}
const mayViewAccounts =
credentialService.isEffectiveSuperAdmin() ||
credentialService.isEffectiveAdmin() ||
credentialService.isEffectiveManager();
if (!mayViewAccounts) {
void router.navigate(['/dashboard']);
resolve(false);
return;
}
resolve(true);
},
{ injector },
);
});
};
@@ -0,0 +1,18 @@
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'status',
})
export class StatusPipe implements PipeTransform {
transform(value: string, ...args: unknown[]): string {
value = value?.toUpperCase() ?? '';
switch (value) {
case 'ACTIVE':
return 'Aktiv';
case 'INACTIVE':
return 'Inaktiv';
default:
return value;
}
}
}
@@ -1,122 +0,0 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../../api';
export type AccountRole = 'SUPER_ADMIN' | 'ADMIN' | 'MANAGER' | 'USER';
export interface AccountProfile {
id: string;
email: string;
name: string;
role: AccountRole;
organization_id: string;
organization_name: string;
deleted: boolean;
is_current: boolean;
is_real_account: boolean;
is_impersonating: boolean;
}
export interface AccountPage {
items: AccountProfile[];
total: number;
page: number;
page_size: number;
}
export interface OrganizationProfile {
id: string;
name: string;
openalex_institution_id?: string | null;
}
export interface AccountPayload {
email?: string;
name?: string;
role?: AccountRole;
organization_id?: string;
password?: string;
deleted?: boolean;
}
export interface CreateAccountPayload {
email: string;
name: string;
role: AccountRole;
organization_id: string;
password: string;
}
@Injectable({
providedIn: 'root',
})
export class AccountManagementService {
private readonly httpClient = inject(HttpClient);
private readonly apiConfiguration = inject(Configuration, { optional: true });
getCurrentAccount(): Observable<AccountProfile> {
return this.httpClient.get<AccountProfile>(
`${this.apiBasePath}/api/accounts/me`,
);
}
listAccounts(options: {
page: number;
pageSize: number;
search?: string;
organizationId?: string;
}): Observable<AccountPage> {
let params = new HttpParams()
.set('page', options.page)
.set('page_size', options.pageSize);
if (options.search) {
params = params.set('search', options.search);
}
if (options.organizationId) {
params = params.set('organization_id', options.organizationId);
}
return this.httpClient.get<AccountPage>(
`${this.apiBasePath}/api/accounts`,
{
params,
},
);
}
createAccount(payload: CreateAccountPayload): Observable<AccountProfile> {
return this.httpClient.post<AccountProfile>(
`${this.apiBasePath}/api/accounts`,
payload,
);
}
updateAccount(
accountId: string,
payload: AccountPayload,
): Observable<AccountProfile> {
return this.httpClient.put<AccountProfile>(
`${this.apiBasePath}/api/accounts/${accountId}`,
payload,
);
}
deleteAccount(accountId: string): Observable<void> {
return this.httpClient.delete<void>(
`${this.apiBasePath}/api/accounts/${accountId}`,
);
}
listOrganizations(): Observable<OrganizationProfile[]> {
return this.httpClient.get<OrganizationProfile[]>(
`${this.apiBasePath}/api/accounts/organizations`,
);
}
private get apiBasePath(): string {
return this.apiConfiguration?.basePath ?? '';
}
}
@@ -35,6 +35,9 @@ export class CredentialService {
this.accessToken()?.effective_role === 'ADMIN' ||
this.isEffectiveSuperAdmin(),
);
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',
@@ -1,5 +1,12 @@
<select (change)="_handleSelectionChange($event)" [ngModel]="_urlValue()">
@for (option of options(); track $index) {
<option [value]="option.value">{{ option.display_name }}</option>
<mat-form-field style="width: 100%">
@if (label()) {
<mat-label>{{ label() }}</mat-label>
}
</select>
<mat-select
(selectionChange)="_handleSelectionChange($event)"
[value]="_urlValue()">
@for (option of _options(); track $index) {
<mat-option [value]="option.value">{{ option.display_name }}</mat-option>
}
</mat-select>
</mat-form-field>
@@ -1,6 +1,7 @@
import { Component, computed, inject, input, output } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatSelectChange, MatSelectModule } from '@angular/material/select';
import { ActivatedRoute, Router } from '@angular/router';
export type SelectorOption = {
@@ -10,14 +11,30 @@ export type SelectorOption = {
@Component({
selector: 'app-query-param-selector',
imports: [FormsModule],
imports: [FormsModule, MatSelectModule],
templateUrl: './query-param-selector.component.html',
styleUrl: './query-param-selector.component.scss',
})
export class QueryParamSelectorComponent {
options = input.required<SelectorOption[]>();
queryParamKey = input.required<string>();
handleSelectionChange = output<Event>();
handleSelectionChange = output<MatSelectChange>();
allowEmptyValue = input<boolean>(false);
label = input<string>('');
_options = computed<SelectorOption[]>(() => {
const options = this.options();
if (!options) {
return [];
}
if (this.allowEmptyValue()) {
return [{ value: '', display_name: '' }, ...options];
}
return options;
});
private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router);
@@ -33,8 +50,8 @@ export class QueryParamSelectorComponent {
return params && key ? params[key] || '' : '';
});
_handleSelectionChange(event: Event): void {
const newValue = (event.target as HTMLSelectElement).value;
_handleSelectionChange(event: MatSelectChange): void {
const newValue = event.value;
this.router.navigate([], {
queryParams: { [this.queryParamKey()]: newValue },