From 40fcdba595f5bce21d043d29b72aef77f962ebab Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Wed, 24 Jun 2026 13:14:26 +0200 Subject: [PATCH 1/2] implement UI Frontend --- .../app-login/app-login.component.html | 216 ++++++++++++------ .../app-login/app-login.component.scss | 215 +++++++++++++---- .../modules/app-login/app-login.component.ts | 123 +++++++++- 3 files changed, 436 insertions(+), 118 deletions(-) diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index e7cb87a6..35a4fc3e 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -1,68 +1,154 @@ -
-
-

Anmeldung

-

- Um auf den Dienst zuzugreifen, musst Du Deine Anmeldedaten eingeben. -

- - - Login - - @if (loginForm.controls.login.hasError('required')) { - Fehler: Login erforderlich. - } @else if (loginForm.controls.login.hasError('minlength')) { - Fehler: Login ist unvollständig. - } - - - - Passwort - - @if (showPassword) { - visibility - } @else { - visibility_off - } - @if (loginForm.controls.password.hasError('required')) { - Fehler: Passwort erforderlich. - } @else if (loginForm.controls.password.hasError('minlength')) { - Fehler: Passwort ist unvollständig. - } - - - -
- +
+ diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index 034b92ac..e5cdaf91 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -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; + } +} diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 24fd129f..3352060d 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -15,6 +15,8 @@ import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; +type LoginStep = 'credentials' | 'otk'; + @Component({ selector: 'app-app-login', imports: [ @@ -32,20 +34,29 @@ import { Router, RouterLink } from '@angular/router'; standalone: true, }) export class AppLoginComponent implements OnInit, OnDestroy { - loginForm = new FormGroup({ - login: new FormControl('', [ - Validators.required, - Validators.minLength(4), - ]), + credentialsForm = new FormGroup({ + email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ Validators.required, - Validators.minLength(4), + Validators.minLength(8), ]), }); + otkForm = new FormGroup({ + code: new FormControl('', [ + 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; constructor( protected credentialService: CredentialService, @@ -57,9 +68,11 @@ export class AppLoginComponent implements OnInit, OnDestroy { 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(); } }, @@ -80,13 +93,99 @@ 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(); + + setTimeout(() => { + this.isSubmitting = false; + this.credentialsForm.enable(); + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open('OTK-Code wurde an die E-Mail-Adresse gesendet.', 'OK', { + duration: 4000, + }); + }, 450); + } + + 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; + } + + this.isSubmitting = true; + this.otkForm.disable(); + + setTimeout(() => { + this.isSubmitting = false; + this.otkForm.enable(); + this.snackBar.open( + 'Backend-Anbindung folgt: login(emailCode) wird hier ausgeführt.', + 'OK', + { duration: 5000 }, + ); + }, 450); + } + + editCredentials() { + this.currentStep = 'credentials'; + 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; } } } -- 2.56.1 From 901cca5eb97e97faf82b1cbf06e3287fb06943d3 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Fri, 26 Jun 2026 10:31:20 +0200 Subject: [PATCH 2/2] connect front to back --- .../main/inse/account_management/__init__.py | 1 + .../src/main/inse/account_management/model.py | 51 +++ .../main/inse/account_management/router.py | 125 +++++++ .../main/inse/account_management/service.py | 311 ++++++++++++++++++ service/src/main/inse/auth/service.py | 4 +- service/src/main/inse/main.py | 2 + webapp/package.json | 2 +- webapp/src/app/app.config.ts | 6 +- webapp/src/app/app.routes.ts | 8 + .../accounts/account-dialog.component.html | 71 ++++ .../accounts/account-dialog.component.scss | 22 ++ .../accounts/account-dialog.component.ts | 123 +++++++ .../modules/accounts/accounts.component.html | 140 ++++++++ .../modules/accounts/accounts.component.scss | 147 +++++++++ .../modules/accounts/accounts.component.ts | 243 ++++++++++++++ .../modules/app-login/app-login.component.ts | 107 ++++-- .../error-page/error-page.component.ts | 4 +- .../authentication.interceptor.ts | 5 +- .../services/account-management.service.ts | 117 +++++++ .../app/shared/services/credential.service.ts | 252 ++++++++++++-- .../ui/app-layout/app-layout.component.html | 9 + .../ui/app-layout/app-layout.component.scss | 20 ++ .../ui/app-layout/app-layout.component.ts | 7 + .../shared/ui/app-menu/app-menu.component.ts | 6 + webapp/src/proxy.conf.json | 17 +- 25 files changed, 1736 insertions(+), 64 deletions(-) create mode 100644 service/src/main/inse/account_management/__init__.py create mode 100644 service/src/main/inse/account_management/model.py create mode 100644 service/src/main/inse/account_management/router.py create mode 100644 service/src/main/inse/account_management/service.py create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.html create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.scss create mode 100644 webapp/src/app/modules/accounts/account-dialog.component.ts create mode 100644 webapp/src/app/modules/accounts/accounts.component.html create mode 100644 webapp/src/app/modules/accounts/accounts.component.scss create mode 100644 webapp/src/app/modules/accounts/accounts.component.ts create mode 100644 webapp/src/app/shared/services/account-management.service.ts diff --git a/service/src/main/inse/account_management/__init__.py b/service/src/main/inse/account_management/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/service/src/main/inse/account_management/__init__.py @@ -0,0 +1 @@ + diff --git a/service/src/main/inse/account_management/model.py b/service/src/main/inse/account_management/model.py new file mode 100644 index 00000000..2bb7613d --- /dev/null +++ b/service/src/main/inse/account_management/model.py @@ -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 diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py new file mode 100644 index 00000000..82781fb0 --- /dev/null +++ b/service/src/main/inse/account_management/router.py @@ -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) diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py new file mode 100644 index 00000000..5ef45372 --- /dev/null +++ b/service/src/main/inse/account_management/service.py @@ -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() diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 3c390c8c..c772012f 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -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() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index e1030d0e..71d27db6 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -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, diff --git a/webapp/package.json b/webapp/package.json index 7c6bbb36..0ac6a13e 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -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", diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 0325060b..1c579be1 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -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') }), ], diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a7d8b279..1204da01 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -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], diff --git a/webapp/src/app/modules/accounts/account-dialog.component.html b/webapp/src/app/modules/accounts/account-dialog.component.html new file mode 100644 index 00000000..0e08dbc8 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.html @@ -0,0 +1,71 @@ +

+ {{ data.mode === 'create' ? 'Account erstellen' : 'Account bearbeiten' }} +

+ + + + + + + + + diff --git a/webapp/src/app/modules/accounts/account-dialog.component.scss b/webapp/src/app/modules/accounts/account-dialog.component.scss new file mode 100644 index 00000000..ccc5f64e --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.scss @@ -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; + } +} diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts new file mode 100644 index 00000000..784a2474 --- /dev/null +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -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 + >(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly form = new FormGroup({ + email: new FormControl(this.data.account?.email ?? '', [ + Validators.required, + Validators.email, + ]), + name: new FormControl(this.data.account?.name ?? '', [ + Validators.required, + ]), + role: new FormControl(this.data.account?.role ?? 'USER', [ + Validators.required, + ]), + organizationId: new FormControl( + this.data.account?.organization_id ?? + (this.data.organizations.length === 1 ? this.data.organizations[0].id : ''), + [Validators.required], + ), + password: new FormControl('', [ + ...(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); + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html new file mode 100644 index 00000000..f9610b4e --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -0,0 +1,140 @@ +
+ + +
+ + Name oder E-Mail + + + + @if (credentialService.superadmin | async) { + + Organisation + + Alle Organisationen + @for (organization of organizations; track organization.id) { + + {{ organization.name }} + + } + + + } + +
+ + +
+
+ +
+
+ {{ total }} Accounts + @if (isLoading) { + Wird geladen... + } +
+ +
+ + + + + + + + + + + + + @for (account of accounts; track account.id) { + + + + + + + + + } @empty { + + + + } + +
NameE-MailOrganisationRolleStatusAktionen
+ + {{ account.email }}{{ account.organization_name }}{{ account.role }} + + {{ account.deleted ? 'deleted' : 'active' }} + + +
+ + + +
+
Keine Accounts gefunden.
+
+ + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss new file mode 100644 index 00000000..53149e49 --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -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; + } +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts new file mode 100644 index 00000000..dc99bd2e --- /dev/null +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -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(''), + organizationId: new FormControl(''), + }); + + 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') + ); + } +} diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 547068a7..eecd2512 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -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,10 @@ 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'; @@ -58,6 +58,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { subscription?: Subscription; private countdownInterval?: ReturnType; + private accountId?: string; constructor( protected credentialService: CredentialService, @@ -65,8 +66,6 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected snackBar: MatSnackBar, ) {} - private readonly authService = inject(AuthService); - ngOnInit(): void { this.subscription = this.credentialService.validating.subscribe( (validating) => { @@ -80,7 +79,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { } }, ); - if (!this.credentialService.validating) { + if (!this.credentialService.validating.value) { this.checkEnter(); } } @@ -108,16 +107,42 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.isSubmitting = true; this.credentialsForm.disable(); - setTimeout(() => { - this.isSubmitting = false; - this.credentialsForm.enable(); - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open('OTK-Code wurde an die E-Mail-Adresse gesendet.', 'OK', { - duration: 4000, + 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, + }); + }, }); - }, 450); } resendCode() { @@ -143,22 +168,46 @@ export class AppLoginComponent implements OnInit, OnDestroy { return; } - this.isSubmitting = true; - this.otkForm.disable(); - - setTimeout(() => { - this.isSubmitting = false; - this.otkForm.enable(); + if (!this.accountId) { this.snackBar.open( - 'Backend-Anbindung folgt: login(emailCode) wird hier ausgeführt.', + 'Bitte fordere zuerst einen neuen Code an.', 'OK', { duration: 5000 }, ); - }, 450); + 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(); } @@ -191,4 +240,16 @@ export class AppLoginComponent implements OnInit, OnDestroy { 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.'; + } } diff --git a/webapp/src/app/modules/error-page/error-page.component.ts b/webapp/src/app/modules/error-page/error-page.component.ts index 26acf5ee..1315396c 100644 --- a/webapp/src/app/modules/error-page/error-page.component.ts +++ b/webapp/src/app/modules/error-page/error-page.component.ts @@ -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(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(); } } diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index e4024263..6cbac0b4 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -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) => { diff --git a/webapp/src/app/shared/services/account-management.service.ts b/webapp/src/app/shared/services/account-management.service.ts new file mode 100644 index 00000000..bc64586f --- /dev/null +++ b/webapp/src/app/shared/services/account-management.service.ts @@ -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 { + return this.httpClient.get(`${this.apiBasePath}/api/accounts/me`); + } + + listAccounts(options: { + page: number; + pageSize: number; + search?: string; + organizationId?: string; + }): Observable { + 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(`${this.apiBasePath}/api/accounts`, { + params, + }); + } + + createAccount(payload: CreateAccountPayload): Observable { + return this.httpClient.post( + `${this.apiBasePath}/api/accounts`, + payload, + ); + } + + updateAccount( + accountId: string, + payload: AccountPayload, + ): Observable { + return this.httpClient.put( + `${this.apiBasePath}/api/accounts/${accountId}`, + payload, + ); + } + + deleteAccount(accountId: string): Observable { + return this.httpClient.delete( + `${this.apiBasePath}/api/accounts/${accountId}`, + ); + } + + listOrganizations(): Observable { + return this.httpClient.get( + `${this.apiBasePath}/api/accounts/organizations`, + ); + } + + private get apiBasePath(): string { + return this.apiConfiguration?.basePath ?? ''; + } +} diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index a6963764..ce13f616 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -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(false); public readonly superadmin = new BehaviorSubject(false); public readonly universityadmin = new BehaviorSubject(false); - public readonly organization = new BehaviorSubject( + public readonly organization = new BehaviorSubject( undefined, ); public readonly login = new BehaviorSubject(''); public readonly email = new BehaviorSubject(''); public readonly organizationName = new BehaviorSubject(''); + public readonly impersonating = new BehaviorSubject(false); + public readonly realAccountId = new BehaviorSubject(''); + public readonly effectiveAccountId = new BehaviorSubject(''); 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 { + 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 { + 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 { + 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 { + 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 { + 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 { return new Observable((observer) => { diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 7b479fe8..e299503c 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -23,6 +23,15 @@ } @if (credentialService.authenticated | async) { + @if (credentialService.impersonating | async) { +
+ switch_account + Impersonation aktiv + +
+ }
@if (mediaQuery.matches) { diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 1f16e6cf..7c3ff20a 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -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; diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index f0a1e6c1..8bb0ab1a 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -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(); } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 3386701a..ca664e06 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -90,6 +90,12 @@ export class AppMenuComponent { sorting_order: 'asc', }, }, + { + label: 'Accounts', + icon: 'manage_accounts', + route: '/accounts', + disabled: false, + }, ]; constructor( diff --git a/webapp/src/proxy.conf.json b/webapp/src/proxy.conf.json index 1e0c9ebd..e5656e77 100644 --- a/webapp/src/proxy.conf.json +++ b/webapp/src/proxy.conf.json @@ -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" + } } } -- 2.56.1