feat(auth): started auth restructure
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
This commit is contained in:
@@ -139,6 +139,7 @@ model/newsArticleDetail.ts
|
||||
model/newsPage.ts
|
||||
model/openAccess.ts
|
||||
model/organizationPage.ts
|
||||
model/otkResponse.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/personBio.ts
|
||||
|
||||
@@ -41,6 +41,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco
|
||||
// @ts-ignore
|
||||
import { LoginResponse } from '../model/loginResponse';
|
||||
// @ts-ignore
|
||||
import { OtkResponse } from '../model/otkResponse';
|
||||
// @ts-ignore
|
||||
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||
|
||||
// @ts-ignore
|
||||
@@ -738,9 +740,9 @@ export class AuthService extends BaseService {
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OtkResponse>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OtkResponse>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OtkResponse>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||
@@ -782,7 +784,7 @@ export class AuthService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/auth/v2/request-otk`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<OtkResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestOtk,
|
||||
|
||||
@@ -115,6 +115,7 @@ export * from './newsArticleDetail';
|
||||
export * from './newsPage';
|
||||
export * from './openAccess';
|
||||
export * from './organizationPage';
|
||||
export * from './otkResponse';
|
||||
export * from './patentEntry';
|
||||
export * from './patentsByAuthorResponse';
|
||||
export * from './personBio';
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface OtkResponse {
|
||||
/**
|
||||
* The status of the one-time code (OTC) request.
|
||||
*/
|
||||
status: string;
|
||||
/**
|
||||
* The unique identifier of the account for which the OTC was requested.
|
||||
*/
|
||||
account_id: string;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-
|
||||
import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver';
|
||||
import { publicationResolver } from './resolvers/publication-resolver';
|
||||
import { accountResolver } from './resolvers/account.resolver';
|
||||
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -107,6 +108,15 @@ export const routes: Routes = [
|
||||
import('./modules/accounts/accounts.component').then(
|
||||
(mod) => mod.AccountsComponent,
|
||||
),
|
||||
resolve: {
|
||||
accountPage: accountsPageResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'search', 'organization_id'];
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'organizations',
|
||||
|
||||
@@ -145,18 +145,19 @@ export class AccountComponent {
|
||||
if (!oldPassword || !newPassword) {
|
||||
return;
|
||||
}
|
||||
this._credentialService
|
||||
.changePassword(oldPassword, newPassword)
|
||||
.subscribe({
|
||||
error: (error) => {
|
||||
console.error('Error changing password:', error);
|
||||
this._snackBar.open(
|
||||
'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
try {
|
||||
await this._credentialService.changePassword(
|
||||
oldPassword,
|
||||
newPassword,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error changing password:', error);
|
||||
this._snackBar.open(
|
||||
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -14,133 +14,64 @@
|
||||
</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.isEffectiveSuperAdmin()) {
|
||||
<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 | 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>
|
||||
<div
|
||||
style="
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
">
|
||||
<app-query-param-input
|
||||
queryParamKey="search"
|
||||
label="Nach Name oder E-Mail suchen"
|
||||
style="width: 30%" />
|
||||
<app-query-param-selector
|
||||
queryParamKey="organization_id"
|
||||
[options]="selectorOptions"
|
||||
label="Organisation" />
|
||||
</div>
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<app-data-table [columns]="accountColumns" [data]="accountPage().items" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<app-query-param-paginator [total]="accountPage().total" />
|
||||
</section>
|
||||
|
||||
<ng-template #accountRoleTmp let-row>
|
||||
<span class="role">{{ row.role | role }}</span>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #accountStatusTmp let-row>
|
||||
<span class="status" [class.status--deleted]="row.deleted">
|
||||
{{ row.deleted ? 'deleted' : 'active' }}
|
||||
</span>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #accountActionsTmp let-row>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(row)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Impersonate"
|
||||
[disabled]="!canImpersonate(row)"
|
||||
(click)="impersonate(row)">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="row.is_current || row.deleted"
|
||||
(click)="deleteAccount(row)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
@@ -145,3 +145,8 @@ tr.deleted {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
mat-card,
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import {
|
||||
Component,
|
||||
OnInit,
|
||||
TemplateRef,
|
||||
effect,
|
||||
inject,
|
||||
input,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
@@ -10,9 +18,8 @@ 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,
|
||||
import {
|
||||
AccountManagementService,
|
||||
AccountRole,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/account-management.service';
|
||||
@@ -22,6 +29,18 @@ import type {
|
||||
AccountDialogResult,
|
||||
} from './account-dialog.component';
|
||||
import { RolePipe } from '../../shared/pipes/role.pipe';
|
||||
import {
|
||||
GenericColumn,
|
||||
DataTableComponent,
|
||||
} from '../../shared/ui/data-table/data-table.component';
|
||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
|
||||
import {
|
||||
QueryParamSelectorComponent,
|
||||
SelectorOption,
|
||||
} from '../../shared/ui/query-param-selector/query-param-selector.component';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { AccountPage, AccountProfile } from '../../api';
|
||||
|
||||
@Component({
|
||||
selector: 'app-accounts',
|
||||
@@ -36,6 +55,11 @@ import { RolePipe } from '../../shared/pipes/role.pipe';
|
||||
MatSnackBarModule,
|
||||
MatDialogModule,
|
||||
RolePipe,
|
||||
DataTableComponent,
|
||||
QueryParamPaginatorComponent,
|
||||
QueryParamInputComponent,
|
||||
QueryParamSelectorComponent,
|
||||
MatCardModule,
|
||||
],
|
||||
templateUrl: './accounts.component.html',
|
||||
styleUrl: './accounts.component.scss',
|
||||
@@ -67,9 +91,63 @@ export class AccountsComponent implements OnInit {
|
||||
organizationId: new FormControl<string>(''),
|
||||
});
|
||||
|
||||
accountColumns: GenericColumn<AccountProfile>[] = [];
|
||||
accountRoleTmp = viewChild.required<TemplateRef<any>>('accountRoleTmp');
|
||||
accountStatusTmp = viewChild.required<TemplateRef<any>>('accountStatusTmp');
|
||||
accountActionsTmp = viewChild.required<TemplateRef<any>>('accountActionsTmp');
|
||||
|
||||
selectorOptions: SelectorOption[] = [];
|
||||
|
||||
accountPage = input.required<AccountPage>();
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
console.log('accountPage changed:', this.accountPage());
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadOrganizations();
|
||||
this.loadAccounts();
|
||||
this.accountColumns = [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Name',
|
||||
type: 'accessor',
|
||||
accessorKey: 'name',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
header: 'E-Mail',
|
||||
type: 'accessor',
|
||||
accessorKey: 'email',
|
||||
},
|
||||
{
|
||||
id: 'organization_name',
|
||||
header: 'Organisation',
|
||||
type: 'accessor',
|
||||
accessorKey: 'organization_name',
|
||||
},
|
||||
{
|
||||
id: 'role',
|
||||
header: 'Rolle',
|
||||
type: 'accessor',
|
||||
accessorKey: 'role',
|
||||
cellTemplate: this.accountRoleTmp(),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
type: 'display',
|
||||
cellTemplate: this.accountStatusTmp(),
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aktionen',
|
||||
type: 'display',
|
||||
cellTemplate: this.accountActionsTmp(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
protected loadAccounts(page = this.page): void {
|
||||
@@ -101,6 +179,10 @@ export class AccountsComponent implements OnInit {
|
||||
this.accountService.listOrganizations().subscribe({
|
||||
next: (organizations) => {
|
||||
this.organizations = organizations;
|
||||
this.selectorOptions = organizations.map((org) => ({
|
||||
value: org.id,
|
||||
display_name: org.name,
|
||||
}));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -199,28 +281,24 @@ export class AccountsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
protected impersonate(account: AccountProfile): void {
|
||||
protected async impersonate(account: AccountProfile): Promise<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,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
try {
|
||||
await this.credentialService.impersonateAccount(account.id);
|
||||
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
|
||||
duration: 4000,
|
||||
});
|
||||
this.router.navigate(['/dashboard']);
|
||||
} catch (error) {
|
||||
console.error('Impersonation failed:', error);
|
||||
this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
protected get canPageBack(): boolean {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { Component, effect, OnDestroy } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
@@ -11,7 +11,7 @@ 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 { finalize, Subscription } from 'rxjs';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
@@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk';
|
||||
styleUrl: './app-login.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
export class AppLoginComponent implements OnDestroy {
|
||||
credentialsForm = new FormGroup({
|
||||
email: new FormControl<string>('', [Validators.required, Validators.email]),
|
||||
password: new FormControl<string>('', [
|
||||
@@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
protected credentialService: CredentialService,
|
||||
protected router: Router,
|
||||
protected snackBar: MatSnackBar,
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.subscription = this.credentialService.validating.subscribe(
|
||||
(validating) => {
|
||||
if (validating) {
|
||||
this.credentialsForm.disable();
|
||||
this.otkForm.disable();
|
||||
} else {
|
||||
this.credentialsForm.enable();
|
||||
this.otkForm.enable();
|
||||
this.checkEnter();
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!this.credentialService.validating.value) {
|
||||
this.checkEnter();
|
||||
}
|
||||
) {
|
||||
effect(() => {
|
||||
if (this.credentialService.isValidating()) {
|
||||
this.credentialsForm.disable();
|
||||
this.otkForm.disable();
|
||||
} else {
|
||||
this.credentialsForm.enable();
|
||||
this.otkForm.enable();
|
||||
this.checkEnter();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
checkEnter(): void {
|
||||
if (this.credentialService.isAuthenticated.value) {
|
||||
if (this.credentialService.isAuthenticated()) {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
}
|
||||
@@ -98,7 +91,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
this.stopCountdown();
|
||||
}
|
||||
|
||||
requestOtk() {
|
||||
async requestOtk() {
|
||||
if (this.credentialsForm.invalid || this.isSubmitting) {
|
||||
this.credentialsForm.markAllAsTouched();
|
||||
return;
|
||||
@@ -110,39 +103,36 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
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,
|
||||
},
|
||||
);
|
||||
try {
|
||||
const otkResponse = await this.credentialService.requestOtk(
|
||||
email,
|
||||
password,
|
||||
);
|
||||
const accountId = otkResponse.account_id;
|
||||
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.clearLocalAuthState();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
this.credentialService.clearLocalAuthState();
|
||||
this.snackBar.open(
|
||||
this.getLoginErrorMessage(error as HttpErrorResponse),
|
||||
'OK',
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
});
|
||||
);
|
||||
} finally {
|
||||
this.isSubmitting = false;
|
||||
this.credentialsForm.enable();
|
||||
}
|
||||
}
|
||||
|
||||
resendCode() {
|
||||
@@ -153,7 +143,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
this.requestOtk();
|
||||
}
|
||||
|
||||
login() {
|
||||
async login() {
|
||||
if (this.otkForm.invalid || this.isSubmitting) {
|
||||
this.otkForm.markAllAsTouched();
|
||||
return;
|
||||
@@ -178,29 +168,25 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
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']);
|
||||
try {
|
||||
await this.credentialService.loginWithOtk(this.accountId, code);
|
||||
this.stopCountdown();
|
||||
this.router.navigate(['/dashboard']);
|
||||
} catch (error: unknown) {
|
||||
this.credentialService.clearLocalAuthState();
|
||||
this.snackBar.open(
|
||||
this.getLoginErrorMessage(error as HttpErrorResponse),
|
||||
'OK',
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
this.credentialService.clearLocalAuthState();
|
||||
this.snackBar.open(this.getLoginErrorMessage(error), 'OK', {
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
});
|
||||
);
|
||||
} finally {
|
||||
this.isSubmitting = false;
|
||||
this.otkForm.enable();
|
||||
}
|
||||
}
|
||||
|
||||
editCredentials() {
|
||||
@@ -240,6 +226,7 @@ export class AppLoginComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private getLoginErrorMessage(error: HttpErrorResponse): string {
|
||||
console.error('Login error:', error);
|
||||
if (error.status === 401) {
|
||||
return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
signal,
|
||||
DestroyRef,
|
||||
OnInit,
|
||||
effect,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
@@ -54,7 +55,7 @@ import { InstitutionsService } from '../../api';
|
||||
templateUrl: './app-register.component.html',
|
||||
styleUrl: './app-register.component.scss',
|
||||
})
|
||||
export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
export class AppRegisterComponent implements OnDestroy {
|
||||
private readonly fb = inject(FormBuilder);
|
||||
protected readonly credentialService = inject(CredentialService);
|
||||
private readonly router = inject(Router);
|
||||
@@ -73,42 +74,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
showPassword = false;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (this.credentialService.isValidating()) {
|
||||
this.registerForm.disable();
|
||||
} else {
|
||||
this.registerForm.enable();
|
||||
this.checkEnter();
|
||||
}
|
||||
});
|
||||
|
||||
this.setupInstitutionAutocomplete();
|
||||
}
|
||||
ngOnInit(): void {
|
||||
this.subscription = this.credentialService.validating.subscribe(
|
||||
(validating) => {
|
||||
if (validating) {
|
||||
this.registerForm.disable();
|
||||
} else {
|
||||
this.registerForm.enable();
|
||||
this.checkEnter();
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!this.credentialService.validating) {
|
||||
this.checkEnter();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
}
|
||||
|
||||
checkEnter(): void {
|
||||
if (this.credentialService.isAuthenticated.value) {
|
||||
if (this.credentialService.isAuthenticated()) {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
}
|
||||
submit() {
|
||||
if (this.registerForm.valid) {
|
||||
this.credentialService.validating.next(true);
|
||||
this.credentialService.isValidating.set(true);
|
||||
this.registerForm.disable();
|
||||
|
||||
this.subscription = this.credentialService
|
||||
.registerAccount(this.registerForm.value)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.credentialService.validating.next(false);
|
||||
this.credentialService.isValidating.set(false);
|
||||
this.snackBar.open(
|
||||
'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.',
|
||||
'OK',
|
||||
@@ -117,7 +113,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
this.router.navigate(['/login']);
|
||||
},
|
||||
error: (err) => {
|
||||
this.credentialService.validating.next(false);
|
||||
this.credentialService.isValidating.set(false);
|
||||
this.registerForm.enable();
|
||||
const message =
|
||||
err.error?.message ||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ResolveFn } from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { AccountPage, AuthService } from '../api';
|
||||
|
||||
export const accountsPageResolver: ResolveFn<AccountPage> = (route, state) => {
|
||||
const page = Number(route.queryParamMap.get('page') ?? '0');
|
||||
const size = Number(route.queryParamMap.get('size') ?? '10');
|
||||
const search = route.queryParamMap.get('search') || undefined;
|
||||
const organizationId =
|
||||
route.queryParamMap.get('organization_id') || undefined;
|
||||
|
||||
return inject(AuthService).listAccounts(
|
||||
page,
|
||||
size,
|
||||
undefined,
|
||||
search,
|
||||
organizationId,
|
||||
);
|
||||
};
|
||||
@@ -1,35 +1,36 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { effect, inject, Injector } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
|
||||
export const adminGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
const injector = inject(Injector);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const ref = effect(
|
||||
() => {
|
||||
if (credentialService.isValidating()) {
|
||||
return;
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
switchMap(() => {
|
||||
if (
|
||||
!credentialService.isEffectiveSuperAdmin() &&
|
||||
!credentialService.isEffectiveAdmin()
|
||||
) {
|
||||
void router.navigate(['/dashboard']);
|
||||
return of(false);
|
||||
}
|
||||
ref.destroy();
|
||||
|
||||
return of(true);
|
||||
}),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (!credentialService.isAuthenticated()) {
|
||||
void router.navigate(['/login']);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!credentialService.isEffectiveAdmin()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(true);
|
||||
},
|
||||
{ injector },
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { effect, inject, Injector } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
|
||||
export const superAdminGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
const injector = inject(Injector);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const ref = effect(
|
||||
() => {
|
||||
if (credentialService.isValidating()) {
|
||||
return;
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
switchMap(() => {
|
||||
if (!credentialService.isEffectiveSuperAdmin()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
return of(false);
|
||||
}
|
||||
return of(true);
|
||||
}),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
ref.destroy();
|
||||
|
||||
if (!credentialService.isAuthenticated()) {
|
||||
void router.navigate(['/login']);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!credentialService.isEffectiveSuperAdmin()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(true);
|
||||
},
|
||||
{ injector },
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { effect, inject, Injector } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, map, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
|
||||
export const userGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
const injector = inject(Injector);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const ref = effect(
|
||||
() => {
|
||||
if (credentialService.isValidating()) {
|
||||
return;
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
map(() => true),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
ref.destroy();
|
||||
|
||||
if (!credentialService.isAuthenticated()) {
|
||||
void router.navigate(['/login']);
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(true);
|
||||
},
|
||||
{ injector },
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,86 +1,73 @@
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import {
|
||||
HttpErrorResponse,
|
||||
HttpInterceptorFn,
|
||||
HttpRequest,
|
||||
} from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { catchError, switchMap, tap, throwError } from 'rxjs';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
import { UiFocusService } from '../services/ui-focus.service';
|
||||
|
||||
const UNAUTHENTICATED_POST_ENDPOINTS = [
|
||||
'/api/auth/v2/request-otk',
|
||||
'/api/auth/v2/login',
|
||||
'/institutions/autocomplete',
|
||||
];
|
||||
|
||||
const isUnauthenticatedPostRequest = (req: any) => {
|
||||
const url = req.url.split('?')[0];
|
||||
return (
|
||||
req.method === 'POST' &&
|
||||
UNAUTHENTICATED_POST_ENDPOINTS.some((endpoint) => url.endsWith(endpoint))
|
||||
);
|
||||
};
|
||||
|
||||
export const authenticationInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const url = req.url.split('?')[0];
|
||||
const uiFocusService = inject(UiFocusService);
|
||||
|
||||
const isPublicAuthRequest =
|
||||
req.method === 'POST' &&
|
||||
(url.endsWith('/api/auth/v2/request-otk') ||
|
||||
url.endsWith('/api/auth/v2/login') ||
|
||||
url.endsWith('/api/auth/v2/access') ||
|
||||
url.endsWith('/api/auth/v2/refresh'));
|
||||
|
||||
if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) {
|
||||
if (isUnauthenticatedPostRequest(req)) {
|
||||
return next(req);
|
||||
}
|
||||
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
const snackBar = inject(MatSnackBar);
|
||||
const tokenProvider = credentialService.getBearerToken();
|
||||
const isLogoutRequest = url.endsWith('/api/auth/v2/logout');
|
||||
|
||||
return tokenProvider.pipe(
|
||||
switchMap((response) => {
|
||||
if (response == undefined) {
|
||||
credentialService.clearLocalAuthState();
|
||||
if (!credentialService.isActiveIdentityToken()) {
|
||||
void router.navigate(['/login']);
|
||||
return throwError(() => new Error('No valid identity token'));
|
||||
}
|
||||
const idToken = credentialService.identityToken();
|
||||
let bearerToken: string;
|
||||
if (url.endsWith('/api/auth/v2/access')) {
|
||||
bearerToken = idToken?.raw_token ?? '';
|
||||
} else {
|
||||
if (!credentialService.isActiveAccessToken()) {
|
||||
credentialService.refreshAccessToken(idToken!);
|
||||
}
|
||||
const accessToken = credentialService.accessToken();
|
||||
if (!accessToken) {
|
||||
void router.navigate(['/login']);
|
||||
return throwError(() => new Error('No valid access token'));
|
||||
}
|
||||
return next(attachToken(req, accessToken.raw_token));
|
||||
}
|
||||
const authorizedRequest = req.clone({
|
||||
headers: req.headers.set('Authorization', 'Bearer ' + bearerToken),
|
||||
});
|
||||
|
||||
snackBar.open(
|
||||
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/login']);
|
||||
|
||||
return throwError(
|
||||
() => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }),
|
||||
);
|
||||
}
|
||||
|
||||
const authorizedRequest = req.clone({
|
||||
headers: req.headers.set('Authorization', 'Bearer ' + response),
|
||||
});
|
||||
|
||||
return next(authorizedRequest).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401 && !isLogoutRequest) {
|
||||
return credentialService.handleUnauthorized().pipe(
|
||||
tap((result) => {
|
||||
uiFocusService.blurActiveElement();
|
||||
|
||||
if (result === 'stopped-impersonating') {
|
||||
snackBar.open(
|
||||
'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/accounts']);
|
||||
} else if (result === 'logged-out') {
|
||||
snackBar.open(
|
||||
'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
|
||||
void router.navigate(['/login']);
|
||||
}
|
||||
}),
|
||||
switchMap(() => throwError(() => error)),
|
||||
);
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
}),
|
||||
);
|
||||
return next(authorizedRequest).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
console.error('Authentication error:', error);
|
||||
return throwError(() => error);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const attachToken = (
|
||||
req: HttpRequest<any>,
|
||||
token: string,
|
||||
): HttpRequest<any> => {
|
||||
return req.clone({
|
||||
headers: req.headers.set('Authorization', 'Bearer ' + token),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,56 +1,50 @@
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { filter, take, map, catchError, finalize } from 'rxjs/operators';
|
||||
import {
|
||||
BehaviorSubject,
|
||||
Observable,
|
||||
of,
|
||||
switchMap,
|
||||
tap,
|
||||
throwError,
|
||||
} from 'rxjs';
|
||||
import { Injectable, computed, effect, inject, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { firstValueFrom, Observable, of, switchMap, throwError } from 'rxjs';
|
||||
import {
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
AuthService,
|
||||
Configuration,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
AccountProfile,
|
||||
RefreshToken,
|
||||
OtkResponse,
|
||||
} from '../../api';
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
type LogoutResult = 'logged-out' | 'stopped-impersonating';
|
||||
type UnauthorizedRecoveryResult =
|
||||
| 'logged-out'
|
||||
| 'stopped-impersonating'
|
||||
| 'already-handling';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CredentialService {
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
private handlingUnauthorized = false;
|
||||
|
||||
private static readonly KEY_GRANT = 'grant';
|
||||
private static readonly KEY_IDENTITY_TOKEN = 'identity_token';
|
||||
private static readonly KEY_REFRESH_TOKEN = 'refresh_token';
|
||||
private static readonly KEY_ACCESS_TOKEN = 'access_token';
|
||||
|
||||
public readonly validating = new BehaviorSubject<boolean>(false);
|
||||
public readonly isAuthenticated = new BehaviorSubject<boolean>(false);
|
||||
public readonly isValidating = signal<boolean>(false);
|
||||
public readonly isAuthenticated = computed(
|
||||
() => this.accessToken() !== undefined,
|
||||
);
|
||||
public readonly isEffectiveSuperAdmin = computed(
|
||||
() => this.accessToken()?.effective_role === 'SUPER_ADMIN',
|
||||
);
|
||||
public readonly isEffectiveAdmin = computed(
|
||||
() => this.accessToken()?.effective_role === 'ADMIN',
|
||||
() =>
|
||||
this.accessToken()?.effective_role === 'ADMIN' ||
|
||||
this.isEffectiveSuperAdmin(),
|
||||
);
|
||||
public readonly effectiveOrganizationId = computed(
|
||||
() => this.accessToken()?.effective_organization_id,
|
||||
);
|
||||
public readonly login = new BehaviorSubject<string>('');
|
||||
public readonly email = new BehaviorSubject<string>('');
|
||||
public readonly organizationName = new BehaviorSubject<string>('');
|
||||
public readonly login = computed(
|
||||
() => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '',
|
||||
);
|
||||
public readonly email = computed(() => this.accountProfile()?.email ?? '');
|
||||
public readonly organizationName = computed(
|
||||
() => this.accountProfile()?.organization_name ?? '',
|
||||
);
|
||||
|
||||
public readonly realAccountId = computed(
|
||||
() => this.accessToken()?.real_account_id ?? '',
|
||||
@@ -62,298 +56,247 @@ export class CredentialService {
|
||||
() => this.realAccountId() !== this.effectiveAccountId(),
|
||||
);
|
||||
|
||||
private readonly identityToken = signal<IdToken | undefined>(undefined);
|
||||
private readonly accessToken = signal<AccessToken | undefined>(undefined);
|
||||
public readonly identityToken = signal<IdToken | undefined>(undefined);
|
||||
public readonly refreshToken = signal<RefreshToken | undefined>(undefined);
|
||||
public readonly accessToken = signal<AccessToken | undefined>(undefined);
|
||||
|
||||
public readonly isActiveIdentityToken = computed(() => {
|
||||
const idToken = this.identityToken();
|
||||
return (
|
||||
idToken !== undefined &&
|
||||
new Date(idToken.expires_at).getTime() >= Date.now()
|
||||
);
|
||||
});
|
||||
|
||||
public readonly isActiveAccessToken = computed(() => {
|
||||
const accessToken = this.accessToken();
|
||||
return (
|
||||
accessToken !== undefined &&
|
||||
new Date(accessToken.expires_at).getTime() >= Date.now()
|
||||
);
|
||||
});
|
||||
|
||||
public readonly accountProfile = toSignal<AccountProfile | undefined>(
|
||||
toObservable(this.isAuthenticated).pipe(
|
||||
switchMap((isAuthenticated) =>
|
||||
isAuthenticated
|
||||
? this.authService.getCurrentAccount()
|
||||
: of<AccountProfile | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
{ initialValue: undefined },
|
||||
);
|
||||
|
||||
private request = 0;
|
||||
|
||||
loadTokensFromStorage(): void {
|
||||
const idTokenData = localStorage.getItem(
|
||||
CredentialService.KEY_IDENTITY_TOKEN,
|
||||
);
|
||||
const refreshTokenData = localStorage.getItem(
|
||||
CredentialService.KEY_REFRESH_TOKEN,
|
||||
);
|
||||
const accessTokenData = localStorage.getItem(
|
||||
CredentialService.KEY_ACCESS_TOKEN,
|
||||
);
|
||||
|
||||
if (idTokenData) {
|
||||
this.identityToken.set(JSON.parse(idTokenData) as IdToken);
|
||||
}
|
||||
if (refreshTokenData) {
|
||||
this.refreshToken.set(JSON.parse(refreshTokenData) as RefreshToken);
|
||||
}
|
||||
if (accessTokenData) {
|
||||
this.accessToken.set(JSON.parse(accessTokenData) as AccessToken);
|
||||
}
|
||||
}
|
||||
|
||||
storeIdentityToken(idToken: IdToken): void {
|
||||
this.identityToken.set(idToken);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_IDENTITY_TOKEN,
|
||||
JSON.stringify(idToken),
|
||||
);
|
||||
}
|
||||
|
||||
storeRefreshToken(refreshToken: RefreshToken): void {
|
||||
this.refreshToken.set(refreshToken);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_REFRESH_TOKEN,
|
||||
JSON.stringify(refreshToken),
|
||||
);
|
||||
}
|
||||
|
||||
storeAccessToken(accessToken: AccessToken): void {
|
||||
this.accessToken.set(accessToken);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_ACCESS_TOKEN,
|
||||
JSON.stringify(accessToken),
|
||||
);
|
||||
}
|
||||
|
||||
clearTokensFromStorage(): void {
|
||||
localStorage.removeItem(CredentialService.KEY_IDENTITY_TOKEN);
|
||||
localStorage.removeItem(CredentialService.KEY_REFRESH_TOKEN);
|
||||
localStorage.removeItem(CredentialService.KEY_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
constructor(private readonly router: Router) {
|
||||
const data = localStorage.getItem(CredentialService.KEY_GRANT);
|
||||
const id = data ? (JSON.parse(data) as AccessToken) : undefined;
|
||||
this.loadTokensFromStorage();
|
||||
effect(() => {
|
||||
console.log('IdToken', this.identityToken());
|
||||
console.log('RefreshToken', this.refreshToken());
|
||||
console.log('AccessToken', this.accessToken());
|
||||
});
|
||||
const id = this.identityToken();
|
||||
if (id && new Date(id.expires_at).getTime() >= Date.now()) {
|
||||
this.identityToken.set(id);
|
||||
this.validating.next(true);
|
||||
this.isValidating.set(true);
|
||||
setTimeout(() => this.refreshAccessToken(id), 0);
|
||||
}
|
||||
}
|
||||
|
||||
public validateCurrentSession(): Observable<void> {
|
||||
return this.loadCurrentProfile();
|
||||
}
|
||||
|
||||
public requestOtk(email: string, password: string): Observable<string> {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.isAuthenticated.next(false);
|
||||
public async requestOtk(
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<OtkResponse> {
|
||||
this.isValidating.set(true);
|
||||
this.identityToken.set(undefined);
|
||||
this.accessToken.set(undefined);
|
||||
|
||||
return this.authService
|
||||
.requestOtk({ email: email.trim().toLowerCase(), password })
|
||||
.pipe(
|
||||
map((response: { account_id?: string }) => {
|
||||
if (this.request !== request) {
|
||||
return '';
|
||||
}
|
||||
const otkResponse: OtkResponse = await firstValueFrom(
|
||||
this.authService.requestOtk({
|
||||
email: email.trim().toLowerCase(),
|
||||
password,
|
||||
}),
|
||||
);
|
||||
|
||||
return response.account_id ?? '';
|
||||
}),
|
||||
finalize(() => {
|
||||
if (this.request === request) {
|
||||
this.validating.next(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
this.isValidating.set(false);
|
||||
return otkResponse;
|
||||
}
|
||||
|
||||
public loginWithOtk(
|
||||
public async loginWithOtk(
|
||||
accountId: string,
|
||||
email: string,
|
||||
emailCode: string,
|
||||
): Observable<void> {
|
||||
): Promise<void> {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.isAuthenticated.next(false);
|
||||
this.isValidating.set(true);
|
||||
|
||||
return this.authService
|
||||
.login({ account_id: accountId, email_code: emailCode.trim() })
|
||||
.pipe(
|
||||
switchMap((response: LoginResponse) => {
|
||||
if (this.request != request) return of(undefined);
|
||||
const loginResponse = await firstValueFrom(
|
||||
this.authService.login({
|
||||
account_id: accountId,
|
||||
email_code: emailCode.trim(),
|
||||
}),
|
||||
);
|
||||
|
||||
const idToken = response.id_token;
|
||||
const idToken = loginResponse.id_token;
|
||||
this.identityToken.set(idToken);
|
||||
this.storeIdentityToken(idToken);
|
||||
|
||||
this.identityToken.set(idToken);
|
||||
localStorage.setItem(
|
||||
CredentialService.KEY_GRANT,
|
||||
JSON.stringify(idToken),
|
||||
);
|
||||
return this.getAccessGrantForIdentity(idToken, request);
|
||||
}),
|
||||
);
|
||||
this.isValidating.set(false);
|
||||
await this.getAccessToken(idToken, request);
|
||||
}
|
||||
|
||||
public refreshAccessToken(identityToken: IdToken) {
|
||||
public async refreshAccessToken(identityToken: IdToken) {
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.isValidating.set(true);
|
||||
this.accessToken.set(undefined);
|
||||
this.getAccessGrantForIdentity(identityToken, request).subscribe({
|
||||
error: () => {
|
||||
if (this.request != request) return;
|
||||
|
||||
await this.getAccessToken(identityToken, request).catch((err) => {
|
||||
if (this.request === request) {
|
||||
this.clearLocalAuthState();
|
||||
},
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
this.isValidating.set(false);
|
||||
}
|
||||
|
||||
public impersonateAccount(accountId: string): Observable<void> {
|
||||
public async impersonateAccount(accountId: string): Promise<void> {
|
||||
const idToken = this.identityToken();
|
||||
|
||||
if (!idToken) {
|
||||
return throwError(() => new Error('No identity token available.'));
|
||||
throw new Error('No identity token available.');
|
||||
}
|
||||
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.isValidating.set(true);
|
||||
this.accessToken.set(undefined);
|
||||
return this.getAccessGrantForIdentity(idToken, request, accountId).pipe(
|
||||
tap({ error: () => this.validating.next(false) }),
|
||||
);
|
||||
await this.getAccessToken(idToken, request, accountId).catch((err) => {
|
||||
if (this.request === request) {
|
||||
this.clearLocalAuthState();
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
this.isValidating.set(false);
|
||||
}
|
||||
|
||||
public stopImpersonating(): Observable<void> {
|
||||
public async stopImpersonating(): Promise<void> {
|
||||
const idToken = this.identityToken();
|
||||
|
||||
if (!idToken) {
|
||||
return throwError(() => new Error('No identity token available.'));
|
||||
throw new Error('No identity token available.');
|
||||
}
|
||||
|
||||
const request = ++this.request;
|
||||
this.validating.next(true);
|
||||
this.isValidating.set(true);
|
||||
this.accessToken.set(undefined);
|
||||
return this.getAccessGrantForIdentity(idToken, request).pipe(
|
||||
tap({ error: () => this.validating.next(false) }),
|
||||
);
|
||||
await this.getAccessToken(idToken, request);
|
||||
this.isValidating.set(false);
|
||||
}
|
||||
|
||||
public logoutAccount(): Observable<LogoutResult> {
|
||||
const wasImpersonating = this.isImpersonating();
|
||||
|
||||
return this.authService
|
||||
.logout('body', false, { transferCache: false })
|
||||
.pipe(
|
||||
catchError((error) => {
|
||||
console.error('Backend logout failed', error);
|
||||
return of(null);
|
||||
}),
|
||||
switchMap(() => {
|
||||
if (!wasImpersonating) {
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}
|
||||
|
||||
return this.stopImpersonating().pipe(
|
||||
map(() => 'stopped-impersonating' as const),
|
||||
catchError((error) => {
|
||||
console.error('Stop impersonating after logout failed', error);
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
public async logoutAccount() {
|
||||
await firstValueFrom(this.authService.logout());
|
||||
this.clearLocalAuthState();
|
||||
}
|
||||
|
||||
public clearLocalAuthState(): void {
|
||||
this.request += 1;
|
||||
localStorage.removeItem(CredentialService.KEY_GRANT);
|
||||
this.clearTokensFromStorage();
|
||||
this.identityToken.set(undefined);
|
||||
this.accessToken.set(undefined);
|
||||
this.isAuthenticated.next(false);
|
||||
this.validating.next(false);
|
||||
this.login.next('');
|
||||
this.email.next('');
|
||||
this.organizationName.next('');
|
||||
this.isValidating.set(false);
|
||||
this.router.navigate(['/login'], { replaceUrl: true });
|
||||
}
|
||||
|
||||
public handleUnauthorized(): Observable<UnauthorizedRecoveryResult> {
|
||||
if (this.handlingUnauthorized) {
|
||||
return of('already-handling' as const);
|
||||
}
|
||||
|
||||
this.handlingUnauthorized = true;
|
||||
|
||||
const isImpersonating = this.isImpersonating();
|
||||
const identityToken = this.identityToken();
|
||||
|
||||
const recovery$ =
|
||||
isImpersonating && identityToken
|
||||
? this.stopImpersonating().pipe(
|
||||
map(() => 'stopped-impersonating' as const),
|
||||
catchError((error) => {
|
||||
console.error('Failed to stop impersonation after 401', error);
|
||||
this.clearLocalAuthState();
|
||||
return of('logged-out' as const);
|
||||
}),
|
||||
)
|
||||
: of(null).pipe(
|
||||
tap(() => this.clearLocalAuthState()),
|
||||
map(() => 'logged-out' as const),
|
||||
);
|
||||
|
||||
return recovery$.pipe(
|
||||
finalize(() => {
|
||||
this.handlingUnauthorized = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public changePassword(
|
||||
public async changePassword(
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Observable<void> {
|
||||
return this.httpClient
|
||||
.post(
|
||||
`${this.apiBasePath}/api/auth/v2/change-password`,
|
||||
{
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
},
|
||||
{ withCredentials: true },
|
||||
)
|
||||
.pipe(
|
||||
tap(() => {
|
||||
this.clearLocalAuthState();
|
||||
}),
|
||||
map(() => undefined),
|
||||
catchError((err) => {
|
||||
throw err;
|
||||
}),
|
||||
);
|
||||
): Promise<void> {
|
||||
this.isValidating.set(true);
|
||||
await firstValueFrom(
|
||||
this.authService.changePassword({
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
}),
|
||||
);
|
||||
this.clearLocalAuthState();
|
||||
this.isValidating.set(false);
|
||||
}
|
||||
|
||||
public registerAccount(_data: unknown): Observable<never> {
|
||||
return throwError(() => new Error('Registration is temporarily disabled.'));
|
||||
}
|
||||
|
||||
//review: arman (generated fix)
|
||||
public getBearerToken(): Observable<string | undefined> {
|
||||
const accessToken = this.accessToken();
|
||||
const identityToken = this.identityToken();
|
||||
|
||||
// 1. If we have a valid access token, return it immediately and complete.
|
||||
if (
|
||||
accessToken &&
|
||||
Date.now() < new Date(accessToken.expires_at).getTime()
|
||||
) {
|
||||
return of(accessToken.raw_token);
|
||||
}
|
||||
|
||||
// 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh.
|
||||
if (!this.validating.value) {
|
||||
if (!identityToken) {
|
||||
return of(undefined); // No identity token to refresh with.
|
||||
}
|
||||
this.refreshAccessToken(identityToken);
|
||||
}
|
||||
|
||||
// 3. Wait for the validation to finish, then return the resulting token.
|
||||
return this.validating.pipe(
|
||||
filter((isValidating) => !isValidating), // Wait until validating becomes false
|
||||
take(1), // Take exactly 1 emission and then automatically complete()
|
||||
map(() => this.accessToken()?.raw_token),
|
||||
);
|
||||
}
|
||||
|
||||
private getAccessGrantForIdentity(
|
||||
private async getAccessToken(
|
||||
idToken: IdToken,
|
||||
request: number,
|
||||
effectiveAccountId?: string,
|
||||
): Observable<void> {
|
||||
): Promise<void> {
|
||||
if (this.request !== request) {
|
||||
return;
|
||||
}
|
||||
|
||||
const realAccountId = idToken.real_account_id;
|
||||
const headers = new HttpHeaders({
|
||||
Authorization: `Bearer ${idToken.raw_token}`,
|
||||
});
|
||||
const payload = {
|
||||
real_account_id: realAccountId,
|
||||
effective_account_id: effectiveAccountId ?? realAccountId,
|
||||
};
|
||||
|
||||
return this.httpClient
|
||||
.post<AccessResponse>(`${this.apiBasePath}/api/auth/v2/access`, payload, {
|
||||
headers,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
tap((result: AccessResponse) => {
|
||||
if (this.request != request) return;
|
||||
const result: AccessResponse = await firstValueFrom(
|
||||
this.authService.getAccessToken({
|
||||
real_account_id: realAccountId,
|
||||
effective_account_id: effectiveAccountId ?? realAccountId,
|
||||
}),
|
||||
);
|
||||
|
||||
const accessToken = result.access_token;
|
||||
|
||||
this.accessToken.set(accessToken);
|
||||
this.isAuthenticated.next(true);
|
||||
this.validating.next(false);
|
||||
}),
|
||||
map(() => undefined),
|
||||
);
|
||||
}
|
||||
|
||||
private get apiBasePath(): string {
|
||||
return this.apiConfiguration?.basePath ?? '';
|
||||
}
|
||||
|
||||
private loadCurrentProfile(): Observable<void> {
|
||||
return this.httpClient
|
||||
.get<AccountProfile>(`${this.apiBasePath}/api/accounts/me`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
tap((profile) => {
|
||||
this.login.next(profile.name ?? profile.email ?? '');
|
||||
this.email.next(profile.email ?? '');
|
||||
this.organizationName.next(profile.organization_name ?? '');
|
||||
}),
|
||||
map(() => undefined),
|
||||
);
|
||||
this.accessToken.set(result.access_token);
|
||||
this.refreshToken.set(result.refresh_token);
|
||||
this.isValidating.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<mat-drawer-container
|
||||
class="drawer-container"
|
||||
[autosize]="!mediaQuery.matches">
|
||||
@if (credentialService.isAuthenticated | async) {
|
||||
@if (credentialService.isAuthenticated()) {
|
||||
<mat-drawer
|
||||
class="drawer"
|
||||
[class.drawer--collapsed]="isSidebarCollapsed()"
|
||||
@@ -18,7 +18,7 @@
|
||||
</mat-drawer>
|
||||
}
|
||||
<mat-drawer-content class="content-shell">
|
||||
@if (credentialService.isAuthenticated | async) {
|
||||
@if (credentialService.isAuthenticated()) {
|
||||
@if (credentialService.isImpersonating()) {
|
||||
<div class="impersonation-banner">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
|
||||
@@ -102,22 +102,21 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
|
||||
this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.credentialService.logoutAccount().subscribe({
|
||||
next: (result) => {
|
||||
if (result === 'stopped-impersonating') {
|
||||
this.router.navigate(['/accounts']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
},
|
||||
});
|
||||
async logout() {
|
||||
const isImpersonating = this.credentialService.isImpersonating();
|
||||
|
||||
await this.credentialService.stopImpersonating();
|
||||
|
||||
if (isImpersonating) {
|
||||
this.router.navigate(['/accounts']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
}
|
||||
|
||||
stopImpersonating(): void {
|
||||
this.credentialService.stopImpersonating().subscribe({
|
||||
next: () => this.router.navigate(['/accounts']),
|
||||
});
|
||||
async stopImpersonating(): Promise<void> {
|
||||
await this.credentialService.stopImpersonating();
|
||||
this.router.navigate(['/accounts']);
|
||||
}
|
||||
|
||||
navigateBack() {
|
||||
|
||||
@@ -101,13 +101,13 @@
|
||||
<div
|
||||
class="account-icon"
|
||||
[matTooltip]="
|
||||
((credentialService.login | async) || 'user') +
|
||||
(credentialService.login() || 'user') +
|
||||
' · ' +
|
||||
((credentialService.organizationName | async) || '')
|
||||
(credentialService.organizationName() || '')
|
||||
"
|
||||
matTooltipPosition="right">
|
||||
<div class="avatar">
|
||||
{{ (credentialService.login | async)?.charAt(0) }}
|
||||
{{ (credentialService.login() || 'user').charAt(0) }}
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
@@ -115,13 +115,11 @@
|
||||
<mat-card appearance="outlined" class="account-card-content">
|
||||
<mat-card-content class="account-card">
|
||||
<div class="avatar">
|
||||
{{ (credentialService.login | async)?.charAt(0) }}
|
||||
{{ (credentialService.login() || 'user').charAt(0) }}
|
||||
</div>
|
||||
<div>
|
||||
<strong>{{
|
||||
(credentialService.login | async) || 'Max Mustermann'
|
||||
}}</strong>
|
||||
<strong>{{ credentialService.organizationName | async }}</strong>
|
||||
<strong>{{ credentialService.login() || 'Max Mustermann' }}</strong>
|
||||
<strong>{{ credentialService.organizationName() }}</strong>
|
||||
</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
@@ -68,7 +68,7 @@ export class AppMenuComponent {
|
||||
icon: 'groups',
|
||||
route: '/persons',
|
||||
queryParams: {
|
||||
institutionName: this.credentialService.organizationName.value,
|
||||
institutionName: this.credentialService.organizationName(),
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
@@ -166,14 +166,8 @@ export class AppMenuComponent {
|
||||
});
|
||||
|
||||
dialogRef.componentInstance.confirmDelete.subscribe(() => {
|
||||
this.credentialService.logoutAccount().subscribe({
|
||||
next: (result) => {
|
||||
if (result === 'stopped-impersonating') {
|
||||
this.router.navigate(['/accounts']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
},
|
||||
this.credentialService.logoutAccount().then(() => {
|
||||
this.router.navigate(['/login']);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user