Ui-login #168

Merged
farajollahi merged 3 commits from Ui-login into auth 2026-06-26 10:36:01 +02:00
27 changed files with 2155 additions and 165 deletions
@@ -0,0 +1 @@
@@ -0,0 +1,51 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
from inse.auth.model import UserRole
class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
openalex_institution_id: Optional[str] = None
class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
role: UserRole
organization_id: uuid.UUID
organization_name: str
deleted: bool
is_current: bool = False
is_real_account: bool = False
is_impersonating: bool = False
class AccountPage(BaseModel):
items: List[AccountProfile]
total: int
page: int
page_size: int
class CreateAccountRequest(BaseModel):
email: str = Field(min_length=3)
name: str = Field(min_length=1)
role: UserRole = UserRole.USER
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
class UpdateAccountRequest(BaseModel):
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
role: Optional[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
@@ -0,0 +1,125 @@
import uuid
from typing import Optional
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessToken
from inse.database import get_session
from inse.tags import Tags
from . import service
from .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
@router.get(
"/me",
operation_id="getCurrentAccount",
response_model=AccountProfile,
)
async def get_current_account(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token)
@router.get(
"",
operation_id="listAccounts",
response_model=AccountPage,
)
async def list_accounts(
page: int = Query(default=0, ge=0),
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
search: Optional[str] = Query(default=None),
organization_id: Optional[uuid.UUID] = Query(default=None),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage:
return service.list_accounts(
session=session,
access_token=access_token,
page=page,
page_size=page_size,
offset=offset,
search=search,
organization_id=organization_id,
)
@router.post(
"",
operation_id="createAccount",
response_model=AccountProfile,
status_code=status.HTTP_201_CREATED,
)
async def create_account(
payload: CreateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.create_account(
session=session,
access_token=access_token,
payload=payload,
)
@router.get(
"/organizations",
operation_id="listAccountOrganizations",
response_model=list[OrganizationProfile],
)
async def list_organizations(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token)
@router.put(
"/{account_id}",
operation_id="updateAccount",
response_model=AccountProfile,
)
async def update_account(
account_id: uuid.UUID,
payload: UpdateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.update_account(
session=session,
access_token=access_token,
account_id=account_id,
payload=payload,
)
@router.delete(
"/{account_id}",
operation_id="deleteAccount",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_account(
account_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_account(
session=session,
access_token=access_token,
account_id=account_id,
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -0,0 +1,311 @@
import uuid
from typing import Optional
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 AccessToken, Account, Organization, UserRole
from .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
def _is_admin(role: UserRole) -> bool:
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
if editor_role == UserRole.SUPER_ADMIN:
return True
if editor_role == UserRole.ADMIN:
return role in {UserRole.MANAGER, UserRole.USER}
return False
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
is_current=account.id == token.effective_account_id,
is_real_account=account.id == token.real_account_id,
is_impersonating=token.is_impersonating(),
)
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
account = session.get(Account, account_id)
if account is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Account not found.",
)
return account
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
if token.effective_role == UserRole.SUPER_ADMIN:
return
if (
token.effective_role == UserRole.ADMIN
and account.organization_id == token.effective_organization_id
):
return
if account.id == token.effective_account_id:
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is outside your scope.",
)
def _ensure_email_available(
session: Session,
email: str,
excluded_account_id: Optional[uuid.UUID] = None,
) -> None:
normalized_email = email.lower().strip()
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Invalid email address.",
)
statement = select(Account).where(Account.email == normalized_email)
if excluded_account_id is not None:
statement = statement.where(Account.id != excluded_account_id)
existing = session.exec(statement).first()
if existing is not None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Email address is already used by another account.",
)
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile:
account = _get_account_or_404(session, access_token.effective_account_id)
return _account_to_profile(account, access_token)
def list_accounts(
session: Session,
access_token: AccessToken,
page: int,
page_size: int,
offset: Optional[int] = None,
search: Optional[str] = None,
organization_id: Optional[uuid.UUID] = None,
) -> AccountPage:
if not _is_admin(access_token.effective_role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can list accounts.",
)
statement = select(Account)
count_statement = select(func.count()).select_from(Account)
filters = []
if access_token.effective_role == UserRole.ADMIN:
filters.append(Account.organization_id == access_token.effective_organization_id)
elif organization_id is not None:
filters.append(Account.organization_id == organization_id)
if search:
pattern = f"%{search.lower().strip()}%"
filters.append(
or_(
func.lower(Account.name).like(pattern),
func.lower(Account.email).like(pattern),
)
)
for filter_expression in filters:
statement = statement.where(filter_expression)
count_statement = count_statement.where(filter_expression)
total = session.exec(count_statement).one()
effective_offset = offset if offset is not None else page * page_size
accounts = session.exec(
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
).all()
return AccountPage(
items=[_account_to_profile(account, access_token) for account in accounts],
total=total,
page=page,
page_size=page_size,
)
def create_account(
session: Session,
access_token: AccessToken,
payload: CreateAccountRequest,
) -> AccountProfile:
if not _is_admin(access_token.effective_role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can create accounts.",
)
if (
access_token.effective_role == UserRole.ADMIN
and payload.organization_id != access_token.effective_organization_id
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
email = payload.email.lower().strip()
_ensure_email_available(session, email)
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
)
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def list_organizations(
session: Session,
access_token: AccessToken,
) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
select(Organization)
.where(Organization.deleted == False) # noqa: E712
.order_by(Organization.name)
).all()
elif access_token.effective_role == UserRole.ADMIN:
organization = session.get(Organization, access_token.effective_organization_id)
organizations = [organization] if organization and not organization.deleted else []
else:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
return [
OrganizationProfile(
id=organization.id,
name=organization.name,
openalex_institution_id=organization.openalex_institution_id,
)
for organization in organizations
]
def update_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
payload: UpdateAccountRequest,
) -> AccountProfile:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
is_self_update = account.id == access_token.effective_account_id
can_admin_update = _is_admin(access_token.effective_role)
if not can_admin_update and not is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if payload.email is not None:
email = payload.email.lower().strip()
_ensure_email_available(session, email, excluded_account_id=account.id)
account.email = email
if payload.name is not None:
account.name = payload.name.strip()
if payload.password is not None:
account.password_hash = auth_service._hash_password(payload.password)
account.epoch += 1
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role 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):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.epoch += 1
if payload.organization_id is not None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
account.organization_id = payload.organization_id
account.epoch += 1
if payload.deleted is not None:
if not can_admin_update or is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = payload.deleted
account.epoch += 1
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def delete_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
) -> None:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
if (
not _is_admin(access_token.effective_role)
or account.id == access_token.effective_account_id
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = True
account.epoch += 1
session.add(account)
session.commit()
+3 -1
View File
@@ -4,6 +4,8 @@ import json
import secrets
import uuid
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Annotated, Any, Dict, Literal, Optional
import jwt
@@ -140,7 +142,6 @@ def _verify_password(password: str, password_hash: str) -> bool:
except (VerifyMismatchError, VerificationError, InvalidHashError):
return False
def request_otk(session: Session, email: str, password: str):
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
@@ -183,6 +184,7 @@ def request_otk(session: Session, email: str, password: str):
)
otk_code = f"{secrets.randbelow(1_000_000):06d}"
print(otk_code)
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
+2
View File
@@ -29,6 +29,7 @@ from inse.news.service import router as news_service_router
from inse.patents.service import router as patents_service_router
from inse.auth.router import router as auth_router
from inse.account_management.router import router as account_management_router
from inse.institutions.router import router as institutions_router
@@ -80,6 +81,7 @@ app.include_router(projects_router)
app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.add_middleware(
ETagCacheMiddleware,
+1 -1
View File
@@ -3,7 +3,7 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"start": "ng serve --proxy-config src/proxy.conf.json",
"build": "ng build",
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
"watch": "ng build --watch --configuration development",
+5 -1
View File
@@ -22,6 +22,7 @@ import { MatPaginatorIntl } from '@angular/material/paginator';
import { PaginatorIntl } from './shared/utils/paginatorIntl';
import { provideEchartsCore } from 'ngx-echarts';
import { ErrorService } from './shared/services/error.service';
import { provideApi } from './api/provide-api';
registerLocaleData(locale);
@@ -72,7 +73,10 @@ export const appConfig: ApplicationConfig = {
}),
),
provideHttpClient(withInterceptors([authenticationInterceptor])),
// provideApi('/inse-service'),
provideApi({
basePath: '/inse-webapp',
withCredentials: true,
}),
provideAnimationsAsync(),
provideEchartsCore({ echarts: () => import('echarts') }),
],
+8
View File
@@ -90,6 +90,14 @@ export const routes: Routes = [
loadComponent: () =>
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
},
{
path: 'accounts',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/accounts/accounts.component').then(
(mod) => mod.AccountsComponent,
),
},
{
path: 'news/:id',
canActivate: [userGuard],
@@ -0,0 +1,71 @@
<h2 mat-dialog-title>
{{ data.mode === 'create' ? 'Account erstellen' : 'Account bearbeiten' }}
</h2>
<mat-dialog-content>
<form class="account-form" [formGroup]="form" (ngSubmit)="submit()">
<mat-form-field appearance="outline">
<mat-label>E-Mail</mat-label>
<input matInput type="email" formControlName="email" />
@if (form.controls.email.hasError('required')) {
<mat-error>E-Mail ist erforderlich.</mat-error>
} @else if (form.controls.email.hasError('email')) {
<mat-error>Bitte gültige E-Mail eingeben.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Name</mat-label>
<input matInput formControlName="name" />
@if (form.controls.name.hasError('required')) {
<mat-error>Name ist erforderlich.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Rolle</mat-label>
<mat-select formControlName="role">
@for (role of data.roles; track role) {
<mat-option [value]="role">{{ role }}</mat-option>
}
</mat-select>
</mat-form-field>
@if (data.canSelectOrganization) {
<mat-form-field appearance="outline">
<mat-label>Organisation</mat-label>
<mat-select formControlName="organizationId">
@for (organization of data.organizations; track organization.id) {
<mat-option [value]="organization.id">
{{ organization.name }}
</mat-option>
}
</mat-select>
</mat-form-field>
}
<mat-form-field appearance="outline">
<mat-label>
{{
data.mode === 'create'
? 'Initiales Passwort'
: 'Neues Passwort'
}}
</mat-label>
<input matInput type="password" formControlName="password" />
@if (form.controls.password.hasError('required')) {
<mat-error>Passwort ist erforderlich.</mat-error>
} @else if (form.controls.password.hasError('minlength')) {
<mat-error>Mindestens 8 Zeichen.</mat-error>
}
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-flat-button color="primary" type="button" (click)="submit()">
<mat-icon>save</mat-icon>
Speichern
</button>
</mat-dialog-actions>
@@ -0,0 +1,22 @@
.account-form {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 14px;
min-width: min(680px, calc(100vw - 64px));
padding-top: 4px;
}
.account-form mat-form-field {
width: 100%;
}
mat-dialog-actions {
padding: 12px 24px 20px;
}
@media (max-width: 720px) {
.account-form {
grid-template-columns: 1fr;
min-width: 0;
}
}
@@ -0,0 +1,123 @@
import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
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,
AccountProfile,
AccountRole,
CreateAccountPayload,
OrganizationProfile,
} from '../../shared/services/account-management.service';
export type AccountDialogMode = 'create' | 'edit';
export interface AccountDialogData {
mode: AccountDialogMode;
account?: AccountProfile;
organizations: OrganizationProfile[];
canSelectOrganization: boolean;
roles: AccountRole[];
}
export type AccountDialogResult =
| { mode: 'create'; payload: CreateAccountPayload }
| { mode: 'edit'; accountId: string; payload: AccountPayload };
@Component({
selector: 'app-account-dialog',
imports: [
CommonModule,
ReactiveFormsModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatSelectModule,
],
templateUrl: './account-dialog.component.html',
styleUrl: './account-dialog.component.scss',
standalone: true,
})
export class AccountDialogComponent {
private readonly dialogRef = inject<
MatDialogRef<AccountDialogComponent, AccountDialogResult | undefined>
>(MatDialogRef);
protected readonly data = inject<AccountDialogData>(MAT_DIALOG_DATA);
protected readonly form = new FormGroup({
email: new FormControl<string>(this.data.account?.email ?? '', [
Validators.required,
Validators.email,
]),
name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required,
]),
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
Validators.required,
]),
organizationId: new FormControl<string>(
this.data.account?.organization_id ??
(this.data.organizations.length === 1 ? this.data.organizations[0].id : ''),
[Validators.required],
),
password: new FormControl<string>('', [
...(this.data.mode === 'create' ? [Validators.required] : []),
Validators.minLength(8),
]),
});
protected submit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
const value = this.form.getRawValue();
if (this.data.mode === 'create') {
this.dialogRef.close({
mode: 'create',
payload: {
email: value.email ?? '',
name: value.name ?? '',
role: value.role ?? 'USER',
organization_id: value.organizationId ?? '',
password: value.password ?? '',
},
});
return;
}
this.dialogRef.close({
mode: 'edit',
accountId: this.data.account!.id,
payload: {
email: value.email ?? '',
name: value.name ?? '',
role: value.role ?? 'USER',
organization_id: value.organizationId ?? '',
password: value.password || undefined,
},
});
}
protected close(): void {
this.dialogRef.close(undefined);
}
}
@@ -0,0 +1,140 @@
<section class="accounts-page">
<header class="page-header">
<div>
<h1>Accounts</h1>
<p>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>
</header>
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()">
<mat-form-field appearance="outline">
<mat-label>Name oder E-Mail</mat-label>
<input matInput formControlName="search" />
</mat-form-field>
@if (credentialService.superadmin | async) {
<mat-form-field appearance="outline">
<mat-label>Organisation</mat-label>
<mat-select formControlName="organizationId">
<mat-option value="">Alle Organisationen</mat-option>
@for (organization of organizations; track organization.id) {
<mat-option [value]="organization.id">
{{ organization.name }}
</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="filter-actions">
<button mat-flat-button color="primary" type="submit">
<mat-icon>search</mat-icon>
Suchen
</button>
<button mat-button type="button" (click)="resetFilters()">
Zurücksetzen
</button>
</div>
</form>
<section class="table-panel">
<div class="table-header">
<strong>{{ total }} Accounts</strong>
@if (isLoading) {
<span>Wird geladen...</span>
}
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Organisation</th>
<th>Rolle</th>
<th>Status</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
@for (account of accounts; track account.id) {
<tr [class.deleted]="account.deleted">
<td>
<button
class="link-button"
type="button"
(click)="startEdit(account)">
{{ account.name }}
</button>
</td>
<td>{{ account.email }}</td>
<td>{{ account.organization_name }}</td>
<td><span class="role">{{ account.role }}</span></td>
<td>
<span class="status" [class.status--deleted]="account.deleted">
{{ account.deleted ? 'deleted' : 'active' }}
</span>
</td>
<td>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Bearbeiten"
(click)="startEdit(account)">
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Impersonate"
[disabled]="!canImpersonate(account)"
(click)="impersonate(account)">
<mat-icon>switch_account</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Deaktivieren"
[disabled]="account.is_current || account.deleted"
(click)="deleteAccount(account)">
<mat-icon>delete</mat-icon>
</button>
</div>
</td>
</tr>
} @empty {
<tr>
<td colspan="6" class="empty">Keine Accounts gefunden.</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pagination">
<button
mat-button
type="button"
[disabled]="!canPageBack"
(click)="loadAccounts(page - 1)">
<mat-icon>chevron_left</mat-icon>
Zurück
</button>
<span>Seite {{ page + 1 }}</span>
<button
mat-button
type="button"
[disabled]="!canPageForward"
(click)="loadAccounts(page + 1)">
Weiter
<mat-icon>chevron_right</mat-icon>
</button>
</div>
</section>
</section>
@@ -0,0 +1,147 @@
.accounts-page {
display: flex;
flex-direction: column;
gap: 20px;
padding: 24px;
}
.page-header,
.filters,
.table-header,
.pagination,
.row-actions {
display: flex;
align-items: center;
}
.page-header {
justify-content: space-between;
gap: 16px;
}
h1,
h2,
p {
margin: 0;
}
.page-header p {
color: #64748b;
margin-top: 6px;
}
.filters {
gap: 12px;
flex-wrap: wrap;
}
.filters mat-form-field {
width: min(320px, 100%);
}
.filter-actions {
display: flex;
gap: 8px;
margin-bottom: 22px;
}
.table-panel {
border: 1px solid #d7dde6;
border-radius: 8px;
background: #fff;
}
.table-header {
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid #e5e7eb;
}
.table-header span {
color: #64748b;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid #edf1f7;
white-space: nowrap;
}
th {
color: #475569;
font-weight: 700;
background: #f8fafc;
}
tr.deleted {
color: #94a3b8;
}
.link-button {
border: 0;
background: transparent;
color: #1d4ed8;
padding: 0;
font: inherit;
cursor: pointer;
}
.role,
.status {
display: inline-flex;
align-items: center;
min-height: 24px;
border-radius: 999px;
padding: 2px 10px;
background: #eef2ff;
color: #3730a3;
font-size: 12px;
font-weight: 700;
}
.status {
background: #dcfce7;
color: #166534;
}
.status--deleted {
background: #fee2e2;
color: #991b1b;
}
.row-actions {
gap: 4px;
}
.empty {
color: #64748b;
text-align: center;
}
.pagination {
justify-content: flex-end;
gap: 8px;
padding: 12px 16px;
}
@media (max-width: 640px) {
.accounts-page {
padding: 16px;
}
.page-header {
align-items: flex-start;
flex-direction: column;
}
}
@@ -0,0 +1,243 @@
import { CommonModule } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormControl, FormGroup, 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 { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { finalize } from 'rxjs';
import {
AccountManagementService,
} from '../../shared/services/account-management.service';
import type {
AccountProfile,
AccountRole,
OrganizationProfile,
} from '../../shared/services/account-management.service';
import { CredentialService } from '../../shared/services/credential.service';
import type {
AccountDialogComponent,
AccountDialogResult,
} from './account-dialog.component';
@Component({
selector: 'app-accounts',
imports: [
CommonModule,
ReactiveFormsModule,
MatButtonModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatSnackBarModule,
MatDialogModule,
],
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);
protected readonly roles: AccountRole[] = [
'SUPER_ADMIN',
'ADMIN',
'MANAGER',
'USER',
];
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>(''),
});
ngOnInit(): void {
this.loadOrganizations();
this.loadAccounts();
}
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;
},
});
}
protected applyFilters(): void {
this.loadAccounts(0);
}
protected resetFilters(): void {
this.filterForm.reset({ search: '', organizationId: '' });
this.loadAccounts(0);
}
protected startCreate(): void {
this.openAccountDialog({ mode: 'create' });
}
protected startEdit(account: AccountProfile): void {
this.openAccountDialog({ mode: 'edit', account });
}
private saveDialogResult(result: AccountDialogResult): void {
const request =
result.mode === 'create'
? this.accountService.createAccount(result.payload)
: this.accountService.updateAccount(result.accountId, result.payload);
request.subscribe({
next: () => {
this.snackBar.open('Account wurde gespeichert.', 'OK', {
duration: 3000,
});
this.loadAccounts(0);
},
error: (error) => {
const message =
error.status === 409
? 'Diese E-Mail-Adresse wird bereits verwendet.'
: 'Account konnte nicht gespeichert werden.';
this.snackBar.open(message, 'OK', { duration: 5000 });
},
});
}
private openAccountDialog(data: {
mode: 'create' | 'edit';
account?: AccountProfile;
}): void {
import('./account-dialog.component').then(({ AccountDialogComponent }) => {
const dialogRef = this.dialog.open<
AccountDialogComponent,
{
mode: 'create' | 'edit';
account?: AccountProfile;
organizations: OrganizationProfile[];
canSelectOrganization: boolean;
roles: AccountRole[];
},
AccountDialogResult | undefined
>(AccountDialogComponent, {
width: '760px',
maxWidth: 'calc(100vw - 32px)',
data: {
...data,
organizations: this.organizations,
canSelectOrganization: this.credentialService.superadmin.value,
roles: this.roles,
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.saveDialogResult(result);
}
});
});
}
protected deleteAccount(account: AccountProfile): void {
if (account.is_current) {
return;
}
this.accountService.deleteAccount(account.id).subscribe({
next: () => {
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
duration: 3000,
});
this.loadAccounts();
},
error: () => {
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
duration: 5000,
});
},
});
}
protected impersonate(account: AccountProfile): void {
if (!this.canImpersonate(account)) {
return;
}
this.credentialService.impersonateAccount(account.id).subscribe({
next: () => {
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
duration: 4000,
});
this.router.navigate(['/dashboard']);
},
error: () => {
this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
duration: 5000,
});
},
});
}
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) {
return false;
}
if (this.credentialService.superadmin.value) {
return true;
}
return (
this.credentialService.universityadmin.value &&
(account.role === 'MANAGER' || account.role === 'USER')
);
}
}
@@ -1,68 +1,154 @@
<div class="container">
<form class="form" [formGroup]="loginForm">
<h3>Anmeldung</h3>
<p class="field">
Um auf den Dienst zuzugreifen, musst Du Deine Anmeldedaten eingeben.
</p>
<mat-form-field class="field">
<mat-label>Login</mat-label>
<input id="dp-login" matInput formControlName="login" />
@if (loginForm.controls.login.hasError('required')) {
<mat-error>Fehler: <b>Login</b> erforderlich.</mat-error>
} @else if (loginForm.controls.login.hasError('minlength')) {
<mat-error>Fehler: <b>Login</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Passwort</mat-label>
<input
id="dp-password"
matInput
[type]="showPassword ? 'text' : 'password'"
formControlName="password" />
@if (showPassword) {
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
} @else {
<mat-icon matSuffix (click)="showPassword = true"
>visibility_off</mat-icon
>
}
@if (loginForm.controls.password.hasError('required')) {
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
} @else if (loginForm.controls.password.hasError('minlength')) {
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<button
mat-raised-button
class="button"
(click)="login()"
[disabled]="!loginForm.valid || (credentialService.validating | async)">
Anmelden
</button>
<div class="field" style="text-align: center; margin-top: -10px">
<button mat-button type="button" routerLink="/register">
Noch kein Konto? <b>Registrieren</b>
</button>
<section class="login-page">
<div class="login-panel">
<div class="brand-block">
<span class="eyebrow">SmartGuide Account Portal</span>
<h1>Login</h1>
<p>
Melde Dich mit Deiner Organisation an. Nach den Zugangsdaten erhältst Du
einen einmaligen Code per E-Mail.
</p>
</div>
</form>
<p class="progress">
@if (credentialService.validating | async) {
<span><i>Anmeldung läuft,</i> bitte warte einen Moment.</span>
<div class="stepper" aria-label="Login-Fortschritt">
<div class="step" [class.step--active]="currentStep === 'credentials'">
<span>1</span>
<strong>Zugangsdaten</strong>
</div>
<div class="step-line"></div>
<div class="step" [class.step--active]="currentStep === 'otk'">
<span>2</span>
<strong>OTK-Code</strong>
</div>
</div>
@if (currentStep === 'credentials') {
<form
class="login-form"
[formGroup]="credentialsForm"
(ngSubmit)="requestOtk()">
<mat-form-field class="field" appearance="outline">
<mat-label>E-Mail-Adresse</mat-label>
<input
id="login-email"
matInput
type="email"
autocomplete="email"
formControlName="email" />
@if (credentialsForm.controls.email.hasError('required')) {
<mat-error>E-Mail-Adresse ist erforderlich.</mat-error>
} @else if (credentialsForm.controls.email.hasError('email')) {
<mat-error>Bitte gib eine gültige E-Mail-Adresse ein.</mat-error>
}
</mat-form-field>
<mat-form-field class="field" appearance="outline">
<mat-label>Passwort</mat-label>
<input
id="login-password"
matInput
[type]="showPassword ? 'text' : 'password'"
autocomplete="current-password"
formControlName="password" />
<button
mat-icon-button
matSuffix
type="button"
[attr.aria-label]="showPassword ? 'Passwort verbergen' : 'Passwort anzeigen'"
(click)="showPassword = !showPassword">
<mat-icon>{{ showPassword ? 'visibility' : 'visibility_off' }}</mat-icon>
</button>
@if (credentialsForm.controls.password.hasError('required')) {
<mat-error>Passwort ist erforderlich.</mat-error>
} @else if (credentialsForm.controls.password.hasError('minlength')) {
<mat-error>Passwort muss mindestens 8 Zeichen haben.</mat-error>
}
</mat-form-field>
<button
mat-flat-button
color="primary"
class="submit-button"
type="submit"
[disabled]="credentialsForm.invalid || isSubmitting">
@if (isSubmitting) {
Code wird gesendet...
} @else {
Code per E-Mail senden
}
</button>
<div class="form-actions">
<a routerLink="/login">Passwort vergessen?</a>
<a routerLink="/register">Konto erstellen</a>
</div>
</form>
} @else {
@if (
(credentialService.authenticated | async) &&
!(credentialService.superadmin | async) &&
!(credentialService.universityadmin | async)
) {
<span class="error"
>Fehler: <b>{{ credentialService.login.value }}</b> ist nicht
berechtigt.</span
>
}
<form class="login-form" [formGroup]="otkForm" (ngSubmit)="login()">
<div class="code-intro">
<mat-icon>mark_email_unread</mat-icon>
<div>
<strong>Code eingeben</strong>
<span>
Wir haben den Code an
{{ credentialsForm.controls.email.value || 'Deine E-Mail-Adresse' }}
gesendet.
</span>
</div>
</div>
<mat-form-field class="field" appearance="outline">
<mat-label>OTK-Code</mat-label>
<input
id="login-otk"
matInput
inputmode="text"
autocomplete="one-time-code"
formControlName="code" />
@if (otkForm.controls.code.hasError('required')) {
<mat-error>OTK-Code ist erforderlich.</mat-error>
} @else if (otkForm.controls.code.hasError('pattern')) {
<mat-error>Bitte gib den Code aus der E-Mail ein.</mat-error>
}
</mat-form-field>
<div
class="expiry"
[class.expiry--expired]="codeExpiresIn === 0"
aria-live="polite">
<mat-icon>timer</mat-icon>
@if (codeExpiresIn > 0) {
<span>Code läuft in {{ formatCountdown() }} ab.</span>
} @else {
<span>Code ist abgelaufen. Bitte neuen Code anfordern.</span>
}
</div>
<button
mat-flat-button
color="primary"
class="submit-button"
type="submit"
[disabled]="otkForm.invalid || isSubmitting || codeExpiresIn === 0">
@if (isSubmitting) {
Anmeldung wird geprüft...
} @else {
Anmelden
}
</button>
<div class="form-actions">
<button
mat-button
type="button"
(click)="resendCode()"
[disabled]="isSubmitting">
Code erneut senden
</button>
<button mat-button type="button" (click)="editCredentials()">
E-Mail ändern
</button>
</div>
</form>
}
</p>
</div>
</div>
</section>
@@ -1,54 +1,187 @@
.container {
display: flex;
flex-direction: column;
.login-page {
display: grid;
min-height: calc(100svh - 41px);
place-items: center;
padding: 48px 20px;
background:
radial-gradient(circle at top left, rgba(61, 124, 255, 0.12), transparent 34%),
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
}
.login-panel {
width: min(100%, 480px);
padding: 34px;
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
box-shadow: var(--sg-shadow-md);
}
.brand-block {
display: grid;
gap: 10px;
margin-bottom: 28px;
}
.eyebrow {
color: var(--sg-blue-highlight);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 32px;
line-height: 1.15;
}
p {
margin: 0;
color: var(--sg-text-muted);
}
.stepper {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
justify-content: center;
gap: 12px;
margin-bottom: 28px;
}
.step {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--sg-text-muted);
font-size: 13px;
}
.step span {
display: grid;
width: 28px;
height: 28px;
place-items: center;
border: 1px solid var(--sg-border-strong);
border-radius: 50%;
background: var(--sg-surface);
font-weight: 700;
}
.step--active {
color: var(--sg-text);
}
.step--active span {
background: var(--sg-primary);
border-color: var(--sg-primary);
color: #ffffff;
}
.step-line {
height: 1px;
background: var(--sg-border);
}
.login-form {
display: grid;
gap: 18px;
}
.field,
.submit-button {
width: 100%;
height: 100%;
background: linear-gradient(160deg, #f4f6fb 0%, #e8ecf7 100%);
}
.form {
display: flex;
flex-direction: column;
align-items: center;
background: white;
border: none;
border-radius: 12px;
box-shadow:
0 2px 12px rgba(26, 58, 110, 0.1),
0 1px 4px rgba(0, 0, 0, 0.06);
gap: 20px;
padding: 36px 32px 28px;
}
.form h3 {
margin: 0 0 4px;
font-weight: 600;
color: #1a3a6e;
}
.button {
.submit-button {
min-height: 48px;
min-width: 140px;
border-radius: 8px;
font-weight: 500;
letter-spacing: 0.02em;
border-radius: var(--sg-radius-sm);
font-weight: 700;
}
.field {
width: 400px;
.form-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 40px;
}
.progress {
padding-top: 5px;
width: 300px;
height: 2em;
text-align: center;
font-size: small;
color: #585f71;
.form-actions a,
.form-actions button {
color: var(--sg-text-muted);
font-size: 13px;
}
.error {
.code-intro {
display: grid;
grid-template-columns: auto 1fr;
gap: 14px;
padding: 14px;
background: var(--sg-surface-soft);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
}
.code-intro mat-icon {
color: var(--sg-blue-highlight);
}
.code-intro div {
display: grid;
gap: 3px;
}
.code-intro span {
color: var(--sg-text-muted);
font-size: 13px;
overflow-wrap: anywhere;
}
.expiry {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--sg-success);
font-size: 13px;
}
.expiry mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.expiry--expired {
color: #ba1a1a;
}
@media (max-width: 560px) {
.login-page {
padding: 28px 14px;
place-items: start center;
}
.login-panel {
padding: 24px 18px;
}
h1 {
font-size: 28px;
}
.stepper {
grid-template-columns: 1fr;
align-items: start;
}
.step-line {
display: none;
}
.form-actions {
align-items: stretch;
flex-direction: column;
}
}
@@ -1,4 +1,4 @@
import { Component, inject, OnDestroy, OnInit } from '@angular/core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import {
FormControl,
FormGroup,
@@ -11,10 +11,12 @@ import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../../shared/services/credential.service';
import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';
import { finalize, Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router';
import { AuthService } from '../../api';
import { HttpErrorResponse } from '@angular/common/http';
type LoginStep = 'credentials' | 'otk';
@Component({
selector: 'app-app-login',
@@ -33,20 +35,30 @@ import { AuthService } from '../../api';
standalone: true,
})
export class AppLoginComponent implements OnInit, OnDestroy {
loginForm = new FormGroup({
login: new FormControl<string>('', [
Validators.required,
Validators.minLength(4),
]),
credentialsForm = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]),
password: new FormControl<string>('', [
Validators.required,
Validators.minLength(4),
Validators.minLength(8),
]),
});
otkForm = new FormGroup({
code: new FormControl<string>('', [
Validators.required,
Validators.pattern(/^[0-9A-Za-z]{6,10}$/),
]),
});
currentStep: LoginStep = 'credentials';
showPassword = false;
isSubmitting = false;
codeExpiresIn = 0;
readonly codeLifetimeSeconds = 300;
subscription?: Subscription;
private countdownInterval?: ReturnType<typeof setInterval>;
private accountId?: string;
constructor(
protected credentialService: CredentialService,
@@ -54,20 +66,20 @@ export class AppLoginComponent implements OnInit, OnDestroy {
protected snackBar: MatSnackBar,
) {}
private readonly authService = inject(AuthService);
ngOnInit(): void {
this.subscription = this.credentialService.validating.subscribe(
(validating) => {
if (validating) {
this.loginForm.disable();
this.credentialsForm.disable();
this.otkForm.disable();
} else {
this.loginForm.enable();
this.credentialsForm.enable();
this.otkForm.enable();
this.checkEnter();
}
},
);
if (!this.credentialService.validating) {
if (!this.credentialService.validating.value) {
this.checkEnter();
}
}
@@ -83,13 +95,161 @@ export class AppLoginComponent implements OnInit, OnDestroy {
this.subscription.unsubscribe();
this.subscription = undefined;
}
this.stopCountdown();
}
requestOtk() {
if (this.credentialsForm.invalid || this.isSubmitting) {
this.credentialsForm.markAllAsTouched();
return;
}
this.isSubmitting = true;
this.credentialsForm.disable();
const email = this.credentialsForm.controls.email.value ?? '';
const password = this.credentialsForm.controls.password.value ?? '';
this.credentialService
.requestOtk(email, password)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.credentialsForm.enable();
}),
)
.subscribe({
next: (accountId) => {
if (!accountId) {
return;
}
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
'OK',
{
duration: 4000,
},
);
},
error: (error: HttpErrorResponse) => {
this.credentialService.logoutAcount();
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
duration: 5000,
});
},
});
}
resendCode() {
if (this.isSubmitting) {
return;
}
this.requestOtk();
}
login() {
let user = this.loginForm.controls.login.value;
let pass = this.loginForm.controls.password.value;
if (user && pass) {
this.credentialService.loginAccount(user, pass);
if (this.otkForm.invalid || this.isSubmitting) {
this.otkForm.markAllAsTouched();
return;
}
if (this.codeExpiresIn <= 0) {
this.snackBar.open(
'Der Code ist abgelaufen. Bitte fordere einen neuen Code an.',
'OK',
{ duration: 5000 },
);
return;
}
if (!this.accountId) {
this.snackBar.open(
'Bitte fordere zuerst einen neuen Code an.',
'OK',
{ duration: 5000 },
);
return;
}
this.isSubmitting = true;
this.otkForm.disable();
const email = this.credentialsForm.controls.email.value ?? '';
const code = this.otkForm.controls.code.value ?? '';
this.credentialService
.loginWithOtk(this.accountId, email, code)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.otkForm.enable();
}),
)
.subscribe({
next: () => {
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
error: (error: HttpErrorResponse) => {
this.credentialService.logoutAcount();
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
duration: 5000,
});
},
});
}
editCredentials() {
this.currentStep = 'credentials';
this.accountId = undefined;
this.stopCountdown();
this.otkForm.reset();
}
formatCountdown(): string {
const minutes = Math.floor(this.codeExpiresIn / 60);
const seconds = this.codeExpiresIn % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
private startCountdown(): void {
this.stopCountdown();
this.codeExpiresIn = this.codeLifetimeSeconds;
this.countdownInterval = setInterval(() => {
this.codeExpiresIn = Math.max(this.codeExpiresIn - 1, 0);
if (this.codeExpiresIn === 0) {
this.stopCountdown(false);
}
}, 1000);
}
private stopCountdown(reset = true): void {
if (this.countdownInterval) {
clearInterval(this.countdownInterval);
this.countdownInterval = undefined;
}
if (reset) {
this.codeExpiresIn = 0;
}
}
private getLoginErrorMessage(error: HttpErrorResponse): string {
if (error.status === 401) {
return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
}
if (error.status === 403) {
return 'Dieses Konto ist nicht für die Anmeldung freigeschaltet.';
}
return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.';
}
}
@@ -1,4 +1,3 @@
import { Location } from '@angular/common';
import { Component, input, OnInit, signal, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -28,7 +27,6 @@ export class ErrorPageComponent implements OnInit {
isDetailsOpen = signal<boolean>(false);
private readonly location = inject(Location);
private readonly errorService = inject(ErrorService);
ngOnInit() {
@@ -53,6 +51,6 @@ export class ErrorPageComponent implements OnInit {
}
goBack() {
this.location.back();
window.history.back();
}
}
@@ -8,6 +8,10 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
(req.method == 'POST' &&
(req.url.endsWith('/auth/id') ||
req.url.endsWith('/auth/access') ||
req.url.endsWith('/api/auth/v2/request-otk') ||
req.url.endsWith('/api/auth/v2/login') ||
req.url.endsWith('/api/auth/v2/access') ||
req.url.endsWith('/api/auth/v2/refresh') ||
req.url.endsWith('/inse-account/create') ||
req.url.endsWith('/auth/v2/request-otk'))) ||
req.url.endsWith('/institutions/autocomplete')
@@ -16,7 +20,6 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
} else {
const credentialService = inject(CredentialService);
const tokenProvider = credentialService.getBearerToken();
console.log("Intercepting request to:", req.url, "with method:", req.method);
return tokenProvider.pipe(
switchMap((response) => {
@@ -0,0 +1,117 @@
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 ?? '';
}
}
@@ -1,17 +1,20 @@
import { Injectable, inject } from '@angular/core';
import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman
import { Observable, of } from 'rxjs'; // review
import { Observable, of, switchMap, tap, throwError } from 'rxjs'; // review
import { BehaviorSubject } from 'rxjs'; //review
import {
AuthService,
Configuration,
INSEAccountServiceService,
IdentityGrant as ApiIdentityGrant,
AccessGrant as ApiAccessGrant,
} from '../../api';
import { HttpClient, HttpHeaders } from '@angular/common/http';
export interface AuthAccount {
i: number;
i: string;
l: string;
o: number;
o: string;
e: string;
on: string;
}
@@ -41,11 +44,14 @@ export interface AccessGrant {
interface TimedIdentityGrant {
grant: IdentityGrant;
expiration: number;
accountId: string;
}
interface TimedAccessGrant {
grant: AccessGrant;
expiration: number;
realAccountId: string;
effectiveAccountId: string;
}
@Injectable({
@@ -53,6 +59,9 @@ interface TimedAccessGrant {
})
export class CredentialService {
private accountService = inject(INSEAccountServiceService);
private authService = inject(AuthService);
private httpClient = inject(HttpClient);
private apiConfiguration = inject(Configuration, { optional: true });
private static readonly KEY_GRANT = 'grant';
@@ -60,12 +69,15 @@ export class CredentialService {
public readonly authenticated = new BehaviorSubject<boolean>(false);
public readonly superadmin = new BehaviorSubject<boolean>(false);
public readonly universityadmin = new BehaviorSubject<boolean>(false);
public readonly organization = new BehaviorSubject<number | undefined>(
public readonly organization = new BehaviorSubject<string | undefined>(
undefined,
);
public readonly login = new BehaviorSubject<string>('');
public readonly email = new BehaviorSubject<string>('');
public readonly organizationName = new BehaviorSubject<string>('');
public readonly impersonating = new BehaviorSubject<boolean>(false);
public readonly realAccountId = new BehaviorSubject<string>('');
public readonly effectiveAccountId = new BehaviorSubject<string>('');
private readonly identityToken = new BehaviorSubject<
TimedIdentityGrant | undefined
@@ -81,16 +93,22 @@ export class CredentialService {
if (token) {
const r = token.grant.scope.r as string[];
this.superadmin.next(r.includes('SUPER_ADMIN'));
this.universityadmin.next(r.includes('UNI_ADMIN'));
this.universityadmin.next(r.includes('UNI_ADMIN') || r.includes('ADMIN'));
this.login.next(token.grant.scope.a?.l ?? '');
this.email.next(token.grant.scope.a?.e ?? '');
this.organizationName.next(token.grant.scope.a?.on ?? '');
this.impersonating.next(token.realAccountId !== token.effectiveAccountId);
this.realAccountId.next(token.realAccountId);
this.effectiveAccountId.next(token.effectiveAccountId);
} else {
this.superadmin.next(false);
this.universityadmin.next(false);
this.login.next('');
this.email.next('');
this.organizationName.next('');
this.impersonating.next(false);
this.realAccountId.next('');
this.effectiveAccountId.next('');
}
});
const data = localStorage.getItem(CredentialService.KEY_GRANT);
@@ -102,6 +120,67 @@ export class CredentialService {
}
}
public requestOtk(email: string, password: string): Observable<string> {
const request = ++this.request;
this.validating.next(true);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.universityadmin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
return this.authService
.requestOtk({ email: email.trim().toLowerCase(), password })
.pipe(
map((response: { account_id?: string }) => {
if (this.request != request) return '';
this.validating.next(false);
return response.account_id ?? '';
}),
);
}
public loginWithOtk(
accountId: string,
email: string,
emailCode: string,
): Observable<void> {
const request = ++this.request;
this.validating.next(true);
this.authenticated.next(false);
this.organization.next(undefined);
this.superadmin.next(false);
this.universityadmin.next(false);
this.identityToken.next(undefined);
this.accessToken.next(undefined);
return this.authService
.login({ account_id: accountId, email_code: emailCode.trim() })
.pipe(
switchMap((response: { id_token: string }) => {
if (this.request != request) return of(undefined);
const payload = this.decodeJwtPayload(response.id_token);
const token: TimedIdentityGrant = {
accountId,
grant: {
token_type: 'ID',
access_token: response.id_token,
expires_in: Math.max(payload.exp - Math.floor(Date.now() / 1000), 0),
scope: this.buildIdentityScope(accountId, email),
},
expiration: payload.exp * 1000,
};
this.identityToken.next(token);
localStorage.setItem(
CredentialService.KEY_GRANT,
JSON.stringify(token),
);
return this.getAccessGrantForIdentity(token, request);
}),
);
}
public loginAccount(login: string, password: string) {
const request = ++this.request;
const now = Date.now();
@@ -123,6 +202,7 @@ export class CredentialService {
const token: TimedIdentityGrant = {
grant: result as any as IdentityGrant,
expiration: result.expires_in * 1000 + now,
accountId: String((result as any).scope?.a?.i ?? ''),
};
this.identityToken.next(token);
localStorage.setItem(
@@ -140,36 +220,49 @@ export class CredentialService {
public refreshAccessToken(identityToken: TimedIdentityGrant) {
const request = ++this.request;
const now = Date.now();
this.validating.next(true);
this.accessToken.next(undefined);
const uid = identityToken.grant.scope.a!.i;
const org = identityToken.grant.scope.a!.o;
this.getAccessGrantForIdentity(identityToken, request).subscribe({
error: () => {
if (this.request != request) return;
this.identityToken.next(undefined);
this.organization.next(undefined);
this.authenticated.next(false);
this.superadmin.next(false);
this.universityadmin.next(false);
this.validating.next(false);
},
});
}
this.accountService
.getAccessGrant(identityToken.grant.access_token, uid, org)
.subscribe({
next: (result) => {
if (this.request != request) return;
const token: TimedAccessGrant = {
grant: result as any as AccessGrant,
expiration: result.expires_in * 1000 + now,
};
this.accessToken.next(token);
this.organization.next(result.scope.a!.o);
this.authenticated.next(true);
this.validating.next(false);
},
error: () => {
if (this.request != request) return;
this.identityToken.next(undefined);
this.organization.next(undefined);
this.authenticated.next(false);
this.superadmin.next(false);
this.universityadmin.next(false);
this.validating.next(false);
},
});
public impersonateAccount(accountId: string): Observable<void> {
if (!this.identityToken.value) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.next(undefined);
return this.getAccessGrantForIdentity(
this.identityToken.value,
request,
accountId,
).pipe(tap({ error: () => this.validating.next(false) }));
}
public stopImpersonating(): Observable<void> {
if (!this.identityToken.value) {
return throwError(() => new Error('No identity token available.'));
}
const request = ++this.request;
this.validating.next(true);
this.accessToken.next(undefined);
return this.getAccessGrantForIdentity(
this.identityToken.value,
request,
this.identityToken.value.accountId,
).pipe(tap({ error: () => this.validating.next(false) }));
}
public logoutAcount() {
@@ -217,6 +310,101 @@ export class CredentialService {
),
);
}
private getAccessGrantForIdentity(
identityToken: TimedIdentityGrant,
request: number,
effectiveAccountId?: string,
): Observable<void> {
const accountId =
identityToken.accountId || String(identityToken.grant.scope.a?.i ?? '');
const headers = new HttpHeaders({
Authorization: `Bearer ${identityToken.grant.access_token}`,
});
return this.httpClient
.post<{ access_token: string; refresh_token: string }>(
`${this.apiBasePath}/api/auth/v2/access`,
{
real_account_id: accountId,
effective_account_id: effectiveAccountId ?? accountId,
},
{ headers, withCredentials: true },
)
.pipe(
tap((result) => {
if (this.request != request) return;
const payload = this.decodeJwtPayload(result.access_token);
const scope = this.buildAccessScope(
payload,
identityToken.grant.scope.a?.e ?? '',
);
const token: TimedAccessGrant = {
grant: {
token_type: 'ACCESS',
access_token: result.access_token,
refresh_token: result.refresh_token,
expires_in: Math.max(
payload.exp - Math.floor(Date.now() / 1000),
0,
),
scope,
},
expiration: payload.exp * 1000,
realAccountId: payload.real_account_id ?? accountId,
effectiveAccountId: payload.effective_account_id ?? accountId,
};
this.accessToken.next(token);
this.organization.next(scope.a.o);
this.authenticated.next(true);
this.validating.next(false);
}),
map(() => undefined),
);
}
private get apiBasePath(): string {
return this.apiConfiguration?.basePath ?? '';
}
private decodeJwtPayload(token: string): any {
const payload = token.split('.')[1];
return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
}
private buildIdentityScope(accountId: string, email: string): AuthScope {
return {
t: 'ID',
d: null,
r: [],
a: {
i: accountId,
l: email,
o: '',
e: email,
on: '',
},
};
}
private buildAccessScope(payload: any, email: string): AuthScope {
const accountId = payload.effective_account_id ?? payload.real_account_id ?? '';
const organizationId = payload.organization_id ?? '';
const role = String(payload.effective_role ?? '');
return {
t: 'ACCESS',
d: null,
r: role ? [role] : [],
a: {
i: accountId,
l: email || accountId,
o: organizationId,
e: email,
on: organizationId,
},
};
}
/* Old version with added complete statements to resolve loading spinner issue
public getBearerToken(): Observable<string | undefined> {
return new Observable<string | undefined>((observer) => {
@@ -23,6 +23,15 @@
}
<mat-drawer-content class="content-shell">
@if (credentialService.authenticated | async) {
@if (credentialService.impersonating | async) {
<div class="impersonation-banner">
<mat-icon>switch_account</mat-icon>
<span>Impersonation aktiv</span>
<button mat-button type="button" (click)="stopImpersonating()">
Beenden
</button>
</div>
}
<mat-toolbar class="main">
<div class="topbar-left">
@if (mediaQuery.matches) {
@@ -58,6 +58,26 @@ mat-toolbar.main {
color: var(--sg-text);
}
.impersonation-banner {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
min-height: 44px;
padding: 6px 20px;
background: #fff7ed;
border-bottom: 1px solid #fed7aa;
color: #9a3412;
font-size: 13px;
font-weight: 700;
}
.impersonation-banner mat-icon {
width: 20px;
height: 20px;
font-size: 20px;
}
.back-link {
display: inline-flex;
align-items: center;
@@ -107,6 +107,13 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.credentialService.logoutAcount();
this.router.navigate(['/']);
}
stopImpersonating(): void {
this.credentialService.stopImpersonating().subscribe({
next: () => this.router.navigate(['/accounts']),
});
}
navigateBack() {
this.location.back();
}
@@ -90,6 +90,12 @@ export class AppMenuComponent {
sorting_order: 'asc',
},
},
{
label: 'Accounts',
icon: 'manage_accounts',
route: '/accounts',
disabled: false,
},
];
constructor(
+15 -2
View File
@@ -1,12 +1,25 @@
{
"/inse-service/": {
"/inse-service": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true
},
"/inse-account/": {
"/inse-account": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true
},
"/api": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true
},
"/inse-webapp/api": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/inse-webapp/api": "/api"
}
}
}