From 1297f85124a914cccfbfa1bd3c99db3a2a373adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 3 Jul 2026 16:56:17 +0200 Subject: [PATCH 1/6] feat(auth): started auth restructure --- webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/auth.service.ts | 10 +- webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/otkResponse.ts | 22 + webapp/src/app/app.routes.ts | 10 + .../app/modules/account/account.component.ts | 25 +- .../modules/accounts/accounts.component.html | 189 +++----- .../modules/accounts/accounts.component.scss | 5 + .../modules/accounts/accounts.component.ts | 122 ++++- .../modules/app-login/app-login.component.ts | 137 +++--- .../app-register/app-register.component.ts | 36 +- .../app/resolvers/accounts-page.resolver.ts | 19 + webapp/src/app/shared/guards/admin.guard.ts | 51 +- .../app/shared/guards/super-admin.guard.ts | 49 +- webapp/src/app/shared/guards/user.guard.ts | 37 +- .../authentication.interceptor.ts | 125 +++-- .../app/shared/services/credential.service.ts | 447 ++++++++---------- .../ui/app-layout/app-layout.component.html | 4 +- .../ui/app-layout/app-layout.component.ts | 27 +- .../ui/app-menu/app-menu.component.html | 14 +- .../shared/ui/app-menu/app-menu.component.ts | 12 +- 21 files changed, 664 insertions(+), 679 deletions(-) create mode 100644 webapp/src/app/api/model/otkResponse.ts create mode 100644 webapp/src/app/resolvers/accounts-page.resolver.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index f9eb4ffa..bc570cfd 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -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 diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 6beb60cc..ef111294 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.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; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { 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('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: bodyRequestOtk, diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 6876bbeb..6d485f3d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -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'; diff --git a/webapp/src/app/api/model/otkResponse.ts b/webapp/src/app/api/model/otkResponse.ts new file mode 100644 index 00000000..7d956289 --- /dev/null +++ b/webapp/src/app/api/model/otkResponse.ts @@ -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; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index efc1388d..c515ba70 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -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', diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts index 8b3eec70..647e5a99 100644 --- a/webapp/src/app/modules/account/account.component.ts +++ b/webapp/src/app/modules/account/account.component.ts @@ -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 }, + ); + } }, }, }, diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 6a5fdb83..f8b2263f 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -14,133 +14,64 @@ -
- - Name oder E-Mail - - - - @if (credentialService.isEffectiveSuperAdmin()) { - - 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 | role }} - - - {{ account.deleted ? 'deleted' : 'active' }} - - -
- - - -
-
Keine Accounts gefunden.
-
- - -
+
+ + +
+ + + + + + + + + {{ row.role | role }} + + + + + {{ row.deleted ? 'deleted' : 'active' }} + + + + +
+ + + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss index 53149e49..d06f840b 100644 --- a/webapp/src/app/modules/accounts/accounts.component.scss +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -145,3 +145,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index f02fa6da..17b62579 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -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(''), }); + accountColumns: GenericColumn[] = []; + accountRoleTmp = viewChild.required>('accountRoleTmp'); + accountStatusTmp = viewChild.required>('accountStatusTmp'); + accountActionsTmp = viewChild.required>('accountActionsTmp'); + + selectorOptions: SelectorOption[] = []; + + accountPage = input.required(); + + 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 { 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 { 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 7d3b0cf7..916c5a33 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, 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('', [Validators.required, Validators.email]), password: new FormControl('', [ @@ -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.'; } diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index d4169732..ff05c039 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -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 || diff --git a/webapp/src/app/resolvers/accounts-page.resolver.ts b/webapp/src/app/resolvers/accounts-page.resolver.ts new file mode 100644 index 00000000..1d4be85d --- /dev/null +++ b/webapp/src/app/resolvers/accounts-page.resolver.ts @@ -0,0 +1,19 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { AccountPage, AuthService } from '../api'; + +export const accountsPageResolver: ResolveFn = (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, + ); +}; diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 55e18ca8..a8876ced 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts index b1936483..993f00a5 100644 --- a/webapp/src/app/shared/guards/super-admin.guard.ts +++ b/webapp/src/app/shared/guards/super-admin.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 190780ae..7145e5ea 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -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((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 }, + ); + }); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 130e6c94..194799a2 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -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, + token: string, +): HttpRequest => { + return req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + token), + }); +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index f276073c..e578e992 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -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(false); - public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isValidating = signal(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(''); - public readonly email = new BehaviorSubject(''); - public readonly organizationName = new BehaviorSubject(''); + 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(undefined); - private readonly accessToken = signal(undefined); + public readonly identityToken = signal(undefined); + public readonly refreshToken = signal(undefined); + public readonly accessToken = signal(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( + toObservable(this.isAuthenticated).pipe( + switchMap((isAuthenticated) => + isAuthenticated + ? this.authService.getCurrentAccount() + : of(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 { - return this.loadCurrentProfile(); - } - - public requestOtk(email: string, password: string): Observable { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); + public async requestOtk( + email: string, + password: string, + ): Promise { + 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 { + ): Promise { 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 { + public async impersonateAccount(accountId: string): Promise { 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 { + public async stopImpersonating(): Promise { 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 { - 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 { - 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 { - 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 { + 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 { return throwError(() => new Error('Registration is temporarily disabled.')); } - //review: arman (generated fix) - public getBearerToken(): Observable { - 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 { + ): Promise { + 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(`${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 { - return this.httpClient - .get(`${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); } } 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 f4ae841c..7be187a0 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 @@ -3,7 +3,7 @@ - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { } - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { @if (credentialService.isImpersonating()) {
switch_account 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 127f842d..bee7ed7c 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 @@ -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 { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); } navigateBack() { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index b80e7271..a917f40b 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -101,13 +101,13 @@ } @else { @@ -115,13 +115,11 @@ 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 96f2bd12..8d2bea96 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 @@ -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']); }); }); } From 7b4c459fd89f8bb6be249f3bc8f775bc55b452a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 3 Jul 2026 17:00:19 +0200 Subject: [PATCH 2/6] fix(frontend/register): fixed wrong variable name --- .../src/app/modules/app-register/app-register.component.html | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html index e6349bc5..a9e758c6 100644 --- a/webapp/src/app/modules/app-register/app-register.component.html +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -84,9 +84,7 @@ mat-raised-button class="button" (click)="submit()" - [disabled]=" - !registerForm.valid || (credentialService.validating | async) - "> + [disabled]="!registerForm.valid || credentialService.isValidating()"> Registrieren From e648ea1ec460d5f23abfc38712aba041b0699759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 4 Jul 2026 22:37:34 +0200 Subject: [PATCH 3/6] feat(backend/auth): added otk response model --- service/src/main/inse/auth/model.py | 7 +++++++ service/src/main/inse/auth/router.py | 3 ++- service/src/main/inse/auth/service.py | 5 +++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index a79aa113..21d7d706 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -210,3 +210,10 @@ class AccessResponse(BaseModel): refresh_token: RefreshToken = Field( description="The refresh token issued alongside the access token for obtaining new access tokens." ) + + +class OtkResponse(BaseModel): + status: str = Field(description="The status of the one-time code (OTC) request.") + account_id: uuid.UUID = Field( + description="The unique identifier of the account for which the OTC was requested." + ) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 2ce4f52a..e80612bb 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -14,6 +14,7 @@ from inse.auth.model import ( AccessToken, IdToken, LoginResponse, + OtkResponse, RefreshToken, ) @@ -40,7 +41,7 @@ async def request_otk( session: SessionDep, email: Annotated[str, Body(description="User's email address")], password: Annotated[str, Body(description="User's password")], -): +) -> OtkResponse: return auth_service.request_otk(session=session, email=email, password=password) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 0af15a4b..dfaa1bf3 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -18,6 +18,7 @@ from inse.auth.model import ( IdToken, LoginResponse, Organization, + OtkResponse, RefreshToken, Secret, TokenType, @@ -155,7 +156,7 @@ def _verify_password(password: str, password_hash: str) -> bool: return False -def request_otk(session: Session, email: str, password: str): +def request_otk(session: Session, email: str, password: str) -> OtkResponse: """Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid. Args: @@ -236,7 +237,7 @@ def request_otk(session: Session, email: str, password: str): else: logger.info("OTK generated for account %s", account.id) - return {"status": "ok", "account_id": str(account.id)} + return OtkResponse(status="success", account_id=account.id) def login( From a464a95c4e430990d1caad61102ded24f1848416 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 00:19:06 +0200 Subject: [PATCH 4/6] fix(frontend/organizations): unfucked everything (again) --- webapp/src/app/app.routes.ts | 10 +- .../organization-dialog.component.ts | 28 ++-- .../organizations.component.html | 123 +++++----------- .../organizations.component.scss | 82 +---------- .../organizations/organizations.component.ts | 137 ++++++++++++------ ....ts => accounts-organizations.resolver.ts} | 2 +- .../organizations-organizations.resolver.ts | 12 ++ .../organization-management.service.ts | 75 ---------- 8 files changed, 171 insertions(+), 298 deletions(-) rename webapp/src/app/resolvers/{organizations.resolver.ts => accounts-organizations.resolver.ts} (85%) create mode 100644 webapp/src/app/resolvers/organizations-organizations.resolver.ts delete mode 100644 webapp/src/app/shared/services/organization-management.service.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 940130e3..ac603aae 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -20,7 +20,8 @@ import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; import { accountViewerGuard } from './shared/guards/account-viewer.guard'; import { accountsPageResolver } from './resolvers/accounts-page.resolver'; -import { organizationsResolver } from './resolvers/organizations.resolver'; +import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver'; +import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver'; export const routes: Routes = [ { @@ -117,7 +118,7 @@ export const routes: Routes = [ ), resolve: { accountPage: accountsPageResolver, - organizations: organizationsResolver, + organizations: accountsOrganizationResolver, }, runGuardsAndResolvers: 'always', }, @@ -128,7 +129,12 @@ export const routes: Routes = [ import('./modules/organizations/organizations.component').then( (mod) => mod.OrganizationsComponent, ), + resolve: { + organizationPage: organizationsOrganizationsResolver, + }, + runGuardsAndResolvers: 'always', }, + { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts index 6348c11f..a192c306 100644 --- a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts @@ -16,15 +16,22 @@ import { import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; -import type { - CreateOrganizationPayload, - OrganizationProfile, - UpdateOrganizationPayload, -} from '../../../shared/services/organization-management.service'; +import { InseOrganizationManagementModelOrganizationProfile } from '../../../api'; + +export interface CreateOrganizationPayload { + name: string; + other_inst_id?: string | null; +} + +export interface UpdateOrganizationPayload { + name?: string; + other_inst_id?: string | null; + deleted?: boolean; +} export interface OrganizationDialogData { mode: 'create' | 'edit'; - organization?: OrganizationProfile; + organization?: InseOrganizationManagementModelOrganizationProfile; } export type OrganizationDialogResult = @@ -66,10 +73,9 @@ export class OrganizationDialogComponent { nonNullable: true, validators: [Validators.required], }), - otherInstId: new FormControl( - this.data.organization?.other_inst_id ?? '', - { nonNullable: true }, - ), + otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', { + nonNullable: true, + }), deleted: new FormControl(this.data.organization?.deleted ?? false, { nonNullable: true, }), @@ -100,6 +106,6 @@ export class OrganizationDialogComponent { } protected close(): void { - this.dialogRef.close(undefined); + this.dialogRef.close(); } } diff --git a/webapp/src/app/modules/organizations/organizations.component.html b/webapp/src/app/modules/organizations/organizations.component.html index a6486b74..14853ec0 100644 --- a/webapp/src/app/modules/organizations/organizations.component.html +++ b/webapp/src/app/modules/organizations/organizations.component.html @@ -3,6 +3,7 @@

Organisationen

Mandanten, externe Institutions-IDs und Status verwalten.

+
- Seite {{ page + 1 }} - -
- + + + + + + + + + + {{ (row.deleted ? 'inactive' : 'active') | status }} + + + + +
+ + +
+
diff --git a/webapp/src/app/modules/organizations/organizations.component.scss b/webapp/src/app/modules/organizations/organizations.component.scss index b558f858..e455d7e3 100644 --- a/webapp/src/app/modules/organizations/organizations.component.scss +++ b/webapp/src/app/modules/organizations/organizations.component.scss @@ -5,15 +5,9 @@ padding: 24px; } -.page-header, -.table-header, -.pagination, -.row-actions { +.page-header { display: flex; align-items: center; -} - -.page-header { justify-content: space-between; gap: 16px; } @@ -32,60 +26,6 @@ p { margin-top: 6px; } -.table-panel { - overflow: hidden; - border: 1px solid #d7dde6; - border-radius: 8px; - background: #fff; -} - -.table-header { - justify-content: space-between; - padding: 16px; - border-bottom: 1px solid #e5e7eb; -} - -.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; -} - -.identifier { - font-family: monospace; - font-size: 12px; -} - -.link-button { - border: 0; - background: transparent; - color: #1d4ed8; - padding: 0; - font: inherit; - cursor: pointer; -} - .status { display: inline-flex; align-items: center; @@ -103,21 +43,6 @@ tr.deleted { 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) { .organizations-page { padding: 16px; @@ -128,3 +53,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/organizations/organizations.component.ts b/webapp/src/app/modules/organizations/organizations.component.ts index 0d061c50..6cbaecb4 100644 --- a/webapp/src/app/modules/organizations/organizations.component.ts +++ b/webapp/src/app/modules/organizations/organizations.component.ts @@ -1,19 +1,34 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; +import { + Component, + inject, + input, + OnInit, + TemplateRef, + viewChild, +} from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { finalize } from 'rxjs'; -import { - OrganizationManagementService, - OrganizationProfile, -} from '../../shared/services/organization-management.service'; import type { OrganizationDialogComponent, OrganizationDialogData, OrganizationDialogResult, } from './organization-dialog/organization-dialog.component'; +import { + InseOrganizationManagementModelOrganizationProfile, + OrganizationPage, + OrganizationService, +} from '../../api'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { MatCardModule } from '@angular/material/card'; +import { StatusPipe } from '../../shared/pipes/status.pipe'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { Router } from '@angular/router'; @Component({ selector: 'app-organizations', @@ -23,50 +38,81 @@ import type { MatDialogModule, MatIconModule, MatSnackBarModule, + DataTableComponent, + MatCardModule, + StatusPipe, + QueryParamPaginatorComponent, ], templateUrl: './organizations.component.html', styleUrl: './organizations.component.scss', standalone: true, }) export class OrganizationsComponent implements OnInit { - private readonly organizationService = inject(OrganizationManagementService); + private readonly router = inject(Router); private readonly dialog = inject(MatDialog); private readonly snackBar = inject(MatSnackBar); + private readonly organizationService = inject(OrganizationService); - protected organizations: OrganizationProfile[] = []; - protected total = 0; - protected page = 0; - protected readonly pageSize = 10; - protected isLoading = false; + organizationPage = input.required(); + organizationColumns: GenericColumn[] = + []; + + organizationStatusTmp = viewChild.required>( + 'organizationStatusTmp', + ); + organizationActionsTmp = viewChild.required>( + 'organizationActionsTmp', + ); ngOnInit(): void { - this.loadOrganizations(); - } - - protected loadOrganizations(page = this.page): void { - this.page = page; - this.isLoading = true; - this.organizationService - .getOrganizations(page, this.pageSize) - .pipe(finalize(() => (this.isLoading = false))) - .subscribe({ - next: (result) => { - this.organizations = result.items; - this.total = result.total; - }, - error: () => this.showError('Organisationen konnten nicht geladen werden.'), - }); + this.organizationColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', + }, + { + id: 'other_inst_id', + header: 'Externe ID', + type: 'accessor', + accessorKey: 'other_inst_id', + }, + { + id: 'member_count', + header: 'Mitglieder', + type: 'accessor', + accessorKey: 'member_count', + }, + { + id: 'deleted', + header: 'Status', + type: 'accessor', + accessorKey: 'deleted', + cellTemplate: this.organizationStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.organizationActionsTmp(), + }, + ]; } protected startCreate(): void { this.openDialog({ mode: 'create' }); } - protected startEdit(organization: OrganizationProfile): void { + protected startEdit( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { this.openDialog({ mode: 'edit', organization }); } - protected deleteOrganization(organization: OrganizationProfile): void { + protected deleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { if (organization.deleted) return; import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( @@ -87,26 +133,24 @@ export class OrganizationsComponent implements OnInit { ); } - private softDeleteOrganization(organization: OrganizationProfile): void { - this.organizationService.deleteOrganization(organization.id).subscribe({ + private softDeleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { + this.organizationService.deleteOrganisation(organization.id).subscribe({ next: () => { this.snackBar.open('Organisation wurde deaktiviert.', 'OK', { duration: 3000, }); - this.loadOrganizations(); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, - error: () => this.showError('Organisation konnte nicht deaktiviert werden.'), + error: () => + this.showError('Organisation konnte nicht deaktiviert werden.'), }); } - protected get canPageBack(): boolean { - return this.page > 0; - } - - protected get canPageForward(): boolean { - return (this.page + 1) * this.pageSize < this.total; - } - private openDialog(data: OrganizationDialogData): void { import('./organization-dialog/organization-dialog.component').then( ({ OrganizationDialogComponent }) => { @@ -130,8 +174,8 @@ export class OrganizationsComponent implements OnInit { private save(result: OrganizationDialogResult): void { const request = result.mode === 'create' - ? this.organizationService.createOrganization(result.payload) - : this.organizationService.updateOrganization( + ? this.organizationService.createOrganisation(result.payload) + : this.organizationService.updateOrganisation( result.organizationId, result.payload, ); @@ -141,7 +185,10 @@ export class OrganizationsComponent implements OnInit { this.snackBar.open('Organisation wurde gespeichert.', 'OK', { duration: 3000, }); - this.loadOrganizations(0); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: (error) => this.showError( diff --git a/webapp/src/app/resolvers/organizations.resolver.ts b/webapp/src/app/resolvers/accounts-organizations.resolver.ts similarity index 85% rename from webapp/src/app/resolvers/organizations.resolver.ts rename to webapp/src/app/resolvers/accounts-organizations.resolver.ts index 258d646c..8fb026c9 100644 --- a/webapp/src/app/resolvers/organizations.resolver.ts +++ b/webapp/src/app/resolvers/accounts-organizations.resolver.ts @@ -5,7 +5,7 @@ import { InseAccountManagementModelOrganizationProfile, } from '../api'; -export const organizationsResolver: ResolveFn< +export const accountsOrganizationResolver: ResolveFn< InseAccountManagementModelOrganizationProfile[] > = (route, state) => { return inject(AuthService).listAccountOrganizations(); diff --git a/webapp/src/app/resolvers/organizations-organizations.resolver.ts b/webapp/src/app/resolvers/organizations-organizations.resolver.ts new file mode 100644 index 00000000..70297dee --- /dev/null +++ b/webapp/src/app/resolvers/organizations-organizations.resolver.ts @@ -0,0 +1,12 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { OrganizationPage, OrganizationService } from '../api'; + +export const organizationsOrganizationsResolver: ResolveFn< + OrganizationPage +> = (route, state) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + + return inject(OrganizationService).getOrganisations(page, size); +}; diff --git a/webapp/src/app/shared/services/organization-management.service.ts b/webapp/src/app/shared/services/organization-management.service.ts deleted file mode 100644 index 9597a005..00000000 --- a/webapp/src/app/shared/services/organization-management.service.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { HttpClient, HttpParams } from '@angular/common/http'; -import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; -import { Configuration } from '../../api'; - -export interface OrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; -} - -export interface OrganizationPage { - items: OrganizationProfile[]; - total: number; - page: number; - page_size: number; -} - -export interface CreateOrganizationPayload { - name: string; - other_inst_id?: string | null; -} - -export interface UpdateOrganizationPayload { - name?: string; - other_inst_id?: string | null; - deleted?: boolean; -} - -@Injectable({ providedIn: 'root' }) -export class OrganizationManagementService { - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - - getOrganizations(page: number, pageSize: number): Observable { - const params = new HttpParams() - .set('page', page) - .set('page_size', pageSize); - return this.httpClient.get( - `${this.apiBasePath}/api/organizations`, - { params }, - ); - } - - createOrganization( - payload: CreateOrganizationPayload, - ): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/organizations`, - payload, - ); - } - - updateOrganization( - organizationId: string, - payload: UpdateOrganizationPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/organizations/${organizationId}`, - payload, - ); - } - - deleteOrganization(organizationId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/organizations/${organizationId}`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} From 0e80cc3fc36e631b7f6942ed98287184593ab9b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 15:59:34 +0200 Subject: [PATCH 5/6] feat(auth): completed auth restructure --- .../main/inse/account_management/router.py | 48 +- .../main/inse/account_management/service.py | 18 +- service/src/main/inse/auth/model.py | 67 +- service/src/main/inse/auth/router.py | 18 +- service/src/main/inse/auth/service.py | 372 ++--- .../src/main/inse/auth/test_auth_service.py | 229 +-- .../inse/organization_management/router.py | 10 +- .../inse/organization_management/service.py | 12 +- webapp/src/app/api/.openapi-generator/FILES | 3 +- webapp/src/app/api/api/api.ts | 17 +- webapp/src/app/api/api/auth.service.ts | 96 +- webapp/src/app/api/api/iNSEService.service.ts | 498 +++--- .../src/app/api/api/organization.service.ts | 36 +- webapp/src/app/api/api/patents.service.ts | 955 ++++-------- webapp/src/app/api/api/topics.service.ts | 1339 ++++++----------- webapp/src/app/api/api/works.service.ts | 980 ++++-------- webapp/src/app/api/configuration.ts | 368 +++-- webapp/src/app/api/model/accessResponse.ts | 5 - webapp/src/app/api/model/accessToken.ts | 18 +- webapp/src/app/api/model/accountProfile.ts | 1 + webapp/src/app/api/model/bodyRequestOtk.ts | 22 +- .../api/model/createOrganizationRequest.ts | 10 +- .../api/model/extractedKeywordsResponse.ts | 30 +- .../model/{idToken.ts => idTokenMetadata.ts} | 16 +- ...countManagementModelOrganizationProfile.ts | 12 +- ...ationManagementModelOrganizationProfile.ts | 16 +- webapp/src/app/api/model/keywordTopicMatch.ts | 10 +- .../app/api/model/keywordsTopicsRequest.ts | 14 +- .../app/api/model/keywordsTopicsResponse.ts | 14 +- webapp/src/app/api/model/loginResponse.ts | 16 +- webapp/src/app/api/model/matchedAuthor.ts | 10 +- webapp/src/app/api/model/models.ts | 3 +- webapp/src/app/api/model/refreshToken.ts | 55 - webapp/src/app/api/model/tokenType.ts | 6 +- .../src/app/api/model/updateAccountRequest.ts | 1 + .../api/model/updateOrganizationRequest.ts | 12 +- .../modules/app-login/app-login.component.ts | 104 +- .../authentication.interceptor.ts | 151 +- .../app/shared/services/credential.service.ts | 462 +++--- .../ui/app-layout/app-layout.component.ts | 5 +- .../shared/ui/app-menu/app-menu.component.ts | 8 +- 41 files changed, 2434 insertions(+), 3633 deletions(-) rename webapp/src/app/api/model/{idToken.ts => idTokenMetadata.ts} (72%) delete mode 100644 webapp/src/app/api/model/refreshToken.ts diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py index 82781fb0..81b22593 100644 --- a/service/src/main/inse/account_management/router.py +++ b/service/src/main/inse/account_management/router.py @@ -1,12 +1,11 @@ import uuid -from typing import Optional +from typing import Annotated, Optional -from fastapi import APIRouter, Depends, Query, Response, status -from sqlmodel import Session +from fastapi import APIRouter, Query, Response, status from inse.auth import service as auth_service -from inse.auth.model import AccessToken -from inse.database import get_session +from inse.auth.model import AccessTokenMetadata +from inse.database import SessionDep from inse.tags import Tags from . import service @@ -24,11 +23,10 @@ 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, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.get_current_account(session=session, access_token=access_token) @@ -36,16 +34,15 @@ async def get_current_account( @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, + session: SessionDep, + page: Annotated[int, Query(ge=0)] = 0, + page_size: Annotated[int, Query(ge=1, le=100)] = 10, + offset: Annotated[int, Query(ge=0)] = 0, + search: Annotated[Optional[str], Query()] = None, + organization_id: Annotated[Optional[uuid.UUID], Query()] = None, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountPage: return service.list_accounts( session=session, @@ -61,13 +58,12 @@ async def list_accounts( @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, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.create_account( session=session, @@ -79,11 +75,10 @@ async def create_account( @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, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> list[OrganizationProfile]: return service.list_organizations(session=session, access_token=access_token) @@ -91,13 +86,12 @@ async def list_organizations( @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, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.update_account( session=session, @@ -114,8 +108,8 @@ async def update_account( ) async def delete_account( account_id: uuid.UUID, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_account( session=session, diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py index 9e0362ad..b9d9dfda 100644 --- a/service/src/main/inse/account_management/service.py +++ b/service/src/main/inse/account_management/service.py @@ -5,7 +5,7 @@ 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 inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( AccountPage, @@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool: return False -def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: +def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile: organization_name = account.organization.name if account.organization else "" return AccountProfile( id=account.id, @@ -55,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account: return account -def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None: +def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata) -> None: if token.effective_role == UserRole.SUPER_ADMIN: return if ( @@ -95,14 +95,14 @@ def _ensure_email_available( ) -def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile: +def get_current_account(session: Session, access_token: AccessTokenMetadata) -> 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, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, @@ -157,7 +157,7 @@ def list_accounts( def create_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateAccountRequest, ) -> AccountProfile: if not _is_admin(access_token.effective_role): @@ -207,7 +207,7 @@ def create_account( def list_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, ) -> list[OrganizationProfile]: if access_token.effective_role == UserRole.SUPER_ADMIN: organizations = session.exec( @@ -233,7 +233,7 @@ def list_organizations( def update_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, payload: UpdateAccountRequest, ) -> AccountProfile: @@ -307,7 +307,7 @@ def update_account( def delete_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, ) -> None: account = _get_account_or_404(session, account_id) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 30888c03..fdd687a2 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -15,9 +15,9 @@ class UserRole(StrEnum): class TokenType(StrEnum): - ID_TOKEN = "ID" - REFRESH_TOKEN = "REFRESH" - ACCESS_TOKEN = "ACCESS" + ID_TOKEN = "ID_TOKEN" + REFRESH_TOKEN = "REFRESH_TOKEN" + ACCESS_TOKEN = "ACCESS_TOKEN" class Durable(SQLModel): @@ -129,37 +129,20 @@ class Secret(SQLModel, table=True): ) -class Token(BaseModel): - token_type: TokenType = Field( - description="The type of the token (ID, Refresh, or Access).", - ) +class BaseTokenData(BaseModel): real_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the real account associated with this token.", ) expires_at: datetime = Field( - index=True, - nullable=False, description="The timestamp indicating when the token will expire.", ) epoch: int = Field( default=0, - nullable=False, description="The epoch value for the token. Used for versioning of tokens.", ) - user_fingerprint_hash: str = Field( - index=True, - nullable=False, - description="A hash of the user's fingerprint to ensure the token is used by the same user.", - ) - raw_token: str = Field( - index=False, - nullable=False, - description="The raw token string.", - ) -class IdToken(Token): +class IdTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ID_TOKEN, const=True, @@ -167,24 +150,23 @@ class IdToken(Token): ) -class AccessToken(Token): +class AccessTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ACCESS_TOKEN, const=True, description="The type of the token, which is always ACCESS_TOKEN for this class.", ) + user_fingerprint_hash: str = Field( + description="A unique fingerprint of the user, used for additional security checks.", + ) effective_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", ) effective_role: UserRole = Field( default=UserRole.USER, - index=True, - nullable=False, description="The specific role this access token grants within its organization.", ) effective_organization_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the organization associated with this access token.", ) @@ -197,25 +179,46 @@ class AccessToken(Token): return self.effective_account_id != self.real_account_id -class RefreshToken(AccessToken): +class AccessToken(AccessTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.", + ) + + +class RefreshTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.REFRESH_TOKEN, const=True, description="The type of the token, which is always REFRESH_TOKEN for this class.", ) + effective_account_id: uuid.UUID = Field( + description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", + ) + effective_role: UserRole = Field( + default=UserRole.USER, + description="The specific role this access token grants within its organization.", + ) + effective_organization_id: uuid.UUID = Field( + description="The unique identifier of the organization associated with this access token.", + ) + + +class RefreshToken(RefreshTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.", + ) class LoginResponse(BaseModel): - id_token: IdToken = Field(description="The ID token issued upon successful login.") + id_token: IdTokenMetadata = Field( + description="The ID token issued upon successful login." + ) class AccessResponse(BaseModel): access_token: AccessToken = Field( description="The access token issued upon successful authentication." ) - refresh_token: RefreshToken = Field( - description="The refresh token issued alongside the access token for obtaining new access tokens." - ) class OtkResponse(BaseModel): diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index e80612bb..9c15079f 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -12,10 +12,11 @@ from inse.database import SessionDep, get_session from inse.auth.model import ( AccessResponse, AccessToken, - IdToken, + AccessTokenMetadata, + IdTokenMetadata, LoginResponse, OtkResponse, - RefreshToken, + RefreshTokenMetadata, ) logger = logging.getLogger(__name__) @@ -81,7 +82,7 @@ async def get_action_tokens( effective_account_id: Annotated[ uuid.UUID, Body(description="Effective account ID for the access token") ], - id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], + id_token: Annotated[IdTokenMetadata, auth_service.CurrentUserIdTokenPayloadDep], ) -> AccessResponse: logger.debug( "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", @@ -109,11 +110,14 @@ async def get_action_tokens( }, ) async def refresh_access_token( + response: Response, refresh_token: Annotated[ - RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep + RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep ], ) -> AccessToken: - return auth_service.refresh_access_token(refresh_token=refresh_token) + return auth_service.refresh_access_token( + response=response, refresh_token=refresh_token + ) @router.post( @@ -126,7 +130,7 @@ async def refresh_access_token( async def logout( session: Annotated[Session, Depends(get_session)], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): @@ -151,7 +155,7 @@ async def change_password( Body(description="New password", min_length=8), ], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 7ea4737f..604085ab 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,22 +4,23 @@ import json import logging import secrets import uuid -from typing import Annotated, Any, Dict, Literal, Optional +from typing import Annotated, Any, Dict, Optional import jwt from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError -from fastapi import Depends, HTTPException, Request, Response, status +from fastapi import Cookie, Depends, HTTPException, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from inse.auth.model import ( AccessResponse, AccessToken, + AccessTokenMetadata, Account, - IdToken, + IdTokenMetadata, LoginResponse, Organization, OtkResponse, - RefreshToken, + RefreshTokenMetadata, Secret, TokenType, UserRole, @@ -29,9 +30,9 @@ from inse.database import get_session from sqlmodel import Session, select, func from inse.auth.email_service import send_email -ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days -REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes -ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes +ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days +REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day +ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes OTK_EXPIRATION_MINUTES = 15 # 15 minutes @@ -42,8 +43,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id" EPOCH_KEY = "epoch" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" -ID_FP_COOKIE_KEY = "_Secure-Fgp-ID" -ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act" + +ACCESS_FP_COOKIE_KEY = "_Secure-Fgp-Acc" +ID_TOKEN_COOKIE_KEY = "id_token" +REFRESH_TOKEN_COOKIE_KEY = "refresh_token" + settings = get_settings() @@ -181,11 +185,7 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse: logger.debug("OTK request for email %s: account found: %s", email, account) - if ( - account is None - or account.deleted - or account.id is None - ): + if account is None or account.deleted or account.id is None: logger.warning("OTK request failed for email %s: account not found", email) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -332,9 +332,9 @@ def login( def _get_current_user_access_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> AccessToken: + secure_fgp: Annotated[str | None, Cookie(alias=ACCESS_FP_COOKIE_KEY)] = None, +) -> AccessTokenMetadata: """Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -345,18 +345,22 @@ def _get_current_user_access_token_payload( Returns: AccessToken: The verified access token payload. """ + if secure_fgp is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Access fingerprint cookie is missing", + ) token = credentials.credentials - access_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + access_token_payload = _verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=token, session=session, ) # If reaches here, the access token is valid and the fingerprint matches - return AccessToken( + return AccessTokenMetadata( real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -368,15 +372,13 @@ def _get_current_user_access_token_payload( access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) def _get_current_user_refresh_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> RefreshToken: + token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None, +) -> RefreshTokenMetadata: """Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -385,18 +387,20 @@ def _get_current_user_refresh_token_payload( credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token. Returns: - RefreshToken: The verified refresh token payload. + RefreshTokenData: The verified refresh token payload. """ - token = credentials.credentials + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Refresh token cookie is missing", + ) - refresh_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + refresh_token_payload = _verify_refresh_token( + raw_refresh_token=token, session=session, ) # If reaches here, the refresh token is valid and the fingerprint matches - refresh_token = RefreshToken( + refresh_token = RefreshTokenMetadata( real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -407,8 +411,6 @@ def _get_current_user_refresh_token_payload( effective_organization_id=uuid.UUID( refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), - user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) logger.debug("Extracted refresh token payload: %s", refresh_token) @@ -418,9 +420,8 @@ def _get_current_user_refresh_token_payload( def _get_current_user_id_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> IdToken: + token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None, +) -> IdTokenMetadata: """Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -431,30 +432,24 @@ def _get_current_user_id_token_payload( Returns: IdToken: The verified ID token payload. """ - logger.debug( - "Verifying ID token for request %s with credentials %s", - request.url, - credentials, - ) - token = credentials.credentials - logger.debug("Verifying ID token for request %s with token %s", request.url, token) + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="ID token cookie is missing", + ) - id_token_payload = _verify_fp_token( - request=request, - cookie_key=ID_FP_COOKIE_KEY, - token=token, + id_token_payload = _verify_id_token( + raw_id_token=token, session=session, ) # If reaches here, the ID token is valid and the fingerprint matches - return IdToken( + return IdTokenMetadata( real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( id_token_payload["exp"], tz=datetime.timezone.utc ), epoch=id_token_payload[EPOCH_KEY], - user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) @@ -583,26 +578,10 @@ def _is_valid_impersonation( def get_access_token( response: Response, session: Session, - id_token: IdToken, + id_token: IdTokenMetadata, real_account_id: uuid.UUID, effective_account_id: Optional[uuid.UUID] = None, ) -> AccessResponse: - """Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - response (Response): The FastAPI response object to which the cookies will be added. - id_token (str): The ID token to verify. - real_account_id (uuid.UUID): The unique identifier of the real account associated with this token. - effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID. - - Raises: - HTTPException: If the ID token is invalid, expired, or does not match the real account ID. - HTTPException: If impersonation is not allowed. - - Returns: - AccessResponse: An object containing the generated access and refresh tokens. - """ # IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. if real_account_id != id_token.real_account_id: @@ -617,16 +596,15 @@ def get_access_token( if effective_account_id is None: effective_account_id = real_account_id - elif effective_account_id != real_account_id: - if not _is_valid_impersonation( - session=session, - real_account_id=real_account_id, - effective_account_id=effective_account_id, - ): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Impersonation not allowed", - ) + elif effective_account_id != real_account_id and not _is_valid_impersonation( + session=session, + real_account_id=real_account_id, + effective_account_id=effective_account_id, + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Impersonation not allowed", + ) role = _get_account_role(session=session, account_id=effective_account_id) epoch = _get_account_epoch(account_id=effective_account_id, session=session) @@ -634,7 +612,7 @@ def get_access_token( session=session, account_id=effective_account_id ) - user_fingerprint_hash = _set_act_fp_cookie(response=response) + user_fingerprint_hash = _set_access_fp_cookie(response=response) access_token = _build_access_token( real_account_id=real_account_id, @@ -644,77 +622,96 @@ def get_access_token( epoch=epoch, user_fingerprint_hash=user_fingerprint_hash, ) - refresh_token = _build_refresh_token( + _set_refresh_token( + response=response, real_account_id=real_account_id, effective_account_id=effective_account_id, effective_role=role, effective_organization_id=organization_id, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, ) return AccessResponse( access_token=access_token, - refresh_token=refresh_token, ) -def _set_id_fp_cookie(response: Response) -> str: - """Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint. +def _set_id_token_cookie(response: Response, raw_id_token: str) -> None: + """Sets a secure cookie for the ID token. Args: response (Response): The FastAPI response object to which the cookie will be added. - - Returns: - str: The hashed value of the fingerprint. + raw_id_token (str): The raw string representation of the ID token. """ - return _set_fingerprint_cookie( - response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + _set_token_cookie( + response=response, + cookie_name=ID_TOKEN_COOKIE_KEY, + token=raw_id_token, + max_age=ID_TOKEN_EXPIRATION_MINUTES * 60, ) -def _set_act_fp_cookie(response: Response) -> str: +def _set_refresh_token_cookie(response: Response, raw_refresh_token: str) -> None: + """Sets a secure cookie for the refresh token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + raw_refresh_token (str): The raw string representation of the refresh token. + """ + _set_token_cookie( + response=response, + cookie_name=REFRESH_TOKEN_COOKIE_KEY, + token=raw_refresh_token, + max_age=REFRESH_TOKEN_EXPIRATION_MINUTES * 60, + ) + + +def _set_token_cookie( + response: Response, cookie_name: str, token: str, max_age: int +) -> None: + """Sets a secure cookie for the specified token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + cookie_name (str): The name of the cookie to set. + token (str): The raw string representation of the token. + max_age (int): The maximum age of the cookie in seconds. + """ + secure = False if settings.environment == "dev" else True + response.set_cookie( + key=cookie_name, + value=token, + httponly=True, + secure=secure, + samesite="strict", + max_age=max_age, + ) + + +def _set_access_fp_cookie(response: Response) -> str: """Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint. Args: response (Response): The FastAPI response object to which the cookie will be added. - Returns: - str: The hashed value of the fingerprint. - """ - return _set_fingerprint_cookie( - response, ACT_FP_COOKIE_KEY - ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. - - -def _set_fingerprint_cookie( - response: Response, - key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"], - max_age: Optional[int] = None, -) -> str: - """Sets a secure fingerprint cookie and returns the hashed value of the fingerprint. - - Args: - response (Response): The FastAPI response object to which the cookie will be added. - key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set. - max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None. - Returns: str: The hashed value of the fingerprint. """ user_fingerprint = secrets.token_hex(50) secure = False if settings.environment == "dev" else True response.set_cookie( - key=key, + key=ACCESS_FP_COOKIE_KEY, value=user_fingerprint, httponly=True, secure=secure, samesite="strict", - max_age=max_age, + max_age=None, # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. ) return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: +def refresh_access_token( + response: Response, refresh_token: RefreshTokenMetadata +) -> AccessToken: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -727,25 +724,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: """ # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. - return _refresh_access_token( - refresh_token=refresh_token, - ) - - -def _refresh_access_token( - refresh_token: RefreshToken, -) -> AccessToken: - """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - refresh_token (RefreshToken): The refresh token to verify. - current_user_epoch (int): The epoch value for the tokens. - - Returns: - AccessToken: The refreshed access token. - """ - # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. + user_fingerprint_hash = _set_access_fp_cookie(response=response) return _build_access_token( real_account_id=refresh_token.real_account_id, @@ -753,7 +732,7 @@ def _refresh_access_token( effective_role=refresh_token.effective_role, effective_organization_id=refresh_token.effective_organization_id, epoch=refresh_token.epoch, - user_fingerprint_hash=refresh_token.user_fingerprint_hash, + user_fingerprint_hash=user_fingerprint_hash, ) @@ -761,7 +740,7 @@ def _build_id_token( response: Response, real_account_id: uuid.UUID, epoch: int, -) -> IdToken: +) -> IdTokenMetadata: """Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie. Args: @@ -776,34 +755,31 @@ def _build_id_token( expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=ID_TOKEN_EXPIRATION_MINUTES ) - user_fingerprint_hash = _set_id_fp_cookie(response) payload = { REAL_ACCOUNT_ID_KEY: str(real_account_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( payload=payload, expiration_datetime=expires_at, token_type=TokenType.ID_TOKEN, ) - return IdToken( + _set_id_token_cookie(response=response, raw_id_token=raw_token) + return IdTokenMetadata( real_account_id=real_account_id, expires_at=expires_at, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) -def _build_refresh_token( +def _set_refresh_token( + response: Response, real_account_id: uuid.UUID, effective_account_id: uuid.UUID, effective_role: UserRole, effective_organization_id: uuid.UUID, epoch: int, - user_fingerprint_hash: str, -) -> RefreshToken: +) -> RefreshTokenMetadata: """Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. Args: @@ -816,7 +792,7 @@ def _build_refresh_token( user_fingerprint_hash (str): The hashed value of the user's fingerprint. Returns: - RefreshToken: The generated refresh token object. + RefreshTokenMetadata: The generated refresh token object. """ expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=REFRESH_TOKEN_EXPIRATION_MINUTES @@ -827,7 +803,6 @@ def _build_refresh_token( EFFECTIVE_ROLE_KEY: effective_role.value, EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( @@ -835,16 +810,14 @@ def _build_refresh_token( expiration_datetime=expires_at, token_type=TokenType.REFRESH_TOKEN, ) - - return RefreshToken( + _set_refresh_token_cookie(response=response, raw_refresh_token=raw_token) + return RefreshTokenMetadata( real_account_id=real_account_id, effective_account_id=effective_account_id, expires_at=expires_at, epoch=epoch, effective_role=effective_role, effective_organization_id=effective_organization_id, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) @@ -931,18 +904,57 @@ def _build_token( return token -def _verify_fp_token( - request: Request, - cookie_key: str, - token: str, - session: Session, -) -> Dict[str, Any]: - """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid. +def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided ID token and returns the decoded payload if valid. Args: - request (Request): The FastAPI request object containing the cookies. - cookie_key (str): The name of the cookie that contains the fingerprint. - token (str): The JWT token to verify. + raw_id_token (str): The JWT ID token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT ID token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_id_token) + return payload + + +def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided refresh token and returns the decoded payload if valid. + + Args: + raw_refresh_token (str): The JWT refresh token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT refresh token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_refresh_token) + return payload + + +def _verify_access_token_fp( + secure_fgp: str, + raw_access_token: str, + session: Session, +) -> Dict[str, Any]: + """Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid. + + Args: + secure_fgp (str): The secure fingerprint value. + raw_access_token (str): The JWT token to verify. + session (Session): The database session. Raises: ValueError: If the token HMAC key is not set in the configuration. @@ -954,19 +966,29 @@ def _verify_fp_token( Returns: Dict[str, Any]: The decoded payload of the JWT token if verification is successful. """ - if not settings.token_hmac_key: - raise ValueError("Token HMAC key is not set in the configuration.") - - secure_fgp = request.cookies.get(cookie_key) - if not secure_fgp: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Fingerprint cookie missing", - ) fingerprint_bytes = secure_fgp.encode("utf-8") expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest() + payload = _extract_valid_token_payload(session, raw_access_token) + + token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) + if ( + not token_fingerprint_hash + or token_fingerprint_hash != expected_fingerprint_hash + ): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid context fingerprint", + ) + + return payload + + +def _extract_valid_token_payload(session: Session, token: str): + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + try: payload = jwt.decode( token, @@ -975,23 +997,12 @@ def _verify_fp_token( issuer=settings.token_issuer_id, ) - token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) - if ( - not token_fingerprint_hash - or token_fingerprint_hash != expected_fingerprint_hash - ): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid context fingerprint", - ) - real_account_id = payload.get(REAL_ACCOUNT_ID_KEY) if not real_account_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing real account ID", ) - epoch_account_id = uuid.UUID(real_account_id) effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY) @@ -1014,7 +1025,6 @@ def _verify_fp_token( ) return payload - except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -1056,7 +1066,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: return account -def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: +def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]: """Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account. Args: @@ -1080,7 +1090,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: def change_password( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, current_password: str, new_password: str, ) -> Dict[str, str]: diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 0e61130c..728a61ee 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -14,9 +14,10 @@ from inse.auth.model import ( Account, Organization, Secret, - IdToken, AccessToken, - RefreshToken, + IdTokenMetadata, + AccessTokenMetadata, + RefreshTokenMetadata, UserRole, ) @@ -61,6 +62,19 @@ def create_org_and_account( return org, acc +def _get_cookie_value(response: Response, cookie_name: str) -> str: + for header_name, header_value in getattr(response, "raw_headers", []): + if header_name.lower() == b"set-cookie": + cookie_header = header_value.decode("latin-1") + if cookie_header.startswith(f"{cookie_name}="): + return cookie_header.split(";", 1)[0].split("=", 1)[1] + + header = response.headers.get("set-cookie") + assert header is not None + assert header.startswith(f"{cookie_name}=") + return header.split(";", 1)[0].split("=", 1)[1] + + def test_hash_and_verify_password(): pw = "s3cret-password" h = auth_service._hash_password(pw) @@ -80,8 +94,8 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): assert acc.id is not None resp = auth_service.request_otk(in_memory_session, email, password) - assert resp["status"] == "ok" - assert resp["account_id"] == str(acc.id) + assert resp.status == "success" + assert resp.account_id == acc.id secret = in_memory_session.exec( select(Secret).where(Secret.account_id == acc.id) @@ -93,9 +107,12 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): login_result = auth_service.login( in_memory_session, response, acc.id, secret.secret_value ) - assert isinstance(login_result.id_token, IdToken) + assert isinstance(login_result.id_token, IdTokenMetadata) assert login_result.id_token.real_account_id == acc.id - assert login_result.id_token.user_fingerprint_hash is not None + + raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY) + payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session) + assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): @@ -108,35 +125,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - assert isinstance(id_token, IdToken) + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) + assert isinstance(access_token, AccessToken) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - assert cookie_header is not None - cookie_value = cookie_header.split("=")[1].split(";")[0] - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}) - payload = auth_service._verify_fp_token( - request=req, - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + payload = auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) with pytest.raises(Exception): - auth_service._verify_fp_token( - request=DummyReq({}), - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="bad-fingerprint", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -158,11 +169,30 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): access_response = auth_service.get_access_token( response, in_memory_session, id_token, acc.id ) - assert isinstance(access_response.access_token, AccessToken) - assert isinstance(access_response.refresh_token, RefreshToken) + assert isinstance(access_response.access_token, AccessTokenMetadata) - refreshed = auth_service.refresh_access_token(access_response.refresh_token) - assert isinstance(refreshed, AccessToken) + raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + refresh_payload = auth_service._verify_refresh_token( + raw_refresh_token=raw_refresh_token, + session=in_memory_session, + ) + refresh_token = RefreshTokenMetadata( + real_account_id=uuid.UUID(refresh_payload[auth_service.REAL_ACCOUNT_ID_KEY]), + effective_account_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY] + ), + expires_at=_dt.datetime.fromtimestamp( + refresh_payload["exp"], tz=_dt.timezone.utc + ), + epoch=refresh_payload[auth_service.EPOCH_KEY], + effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]), + effective_organization_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ORGANIZATION_ID_KEY] + ), + ) + + refreshed = auth_service.refresh_access_token(Response(), refresh_token) + assert isinstance(refreshed, AccessTokenMetadata) assert refreshed.real_account_id == access_response.access_token.real_account_id @@ -233,6 +263,7 @@ def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_sess in_memory_session.add(account) in_memory_session.commit() + assert account.id is not None with pytest.raises(HTTPException) as error: auth_service._get_active_account(in_memory_session, account.id) @@ -268,24 +299,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="badcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -300,28 +327,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) acc.epoch += 1 in_memory_session.add(acc) in_memory_session.commit() with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -336,25 +360,21 @@ def test_invalid_token_signature_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) + secure_fgp = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp, + ) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - bad_token = id_token.raw_token + "x" + bad_token = access_token.raw_token + "x" with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=bad_token, session=in_memory_session, ) @@ -391,7 +411,7 @@ def test_impersonation_rules(in_memory_session, settings_backup): real_acc.id, effective_account_id=eff_acc.id, ) - assert isinstance(access_resp.access_token, AccessToken) + assert isinstance(access_resp.access_token, AccessTokenMetadata) def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): @@ -425,7 +445,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): login_res = auth_service.login( in_memory_session, Response(), acc.id, secret2.secret_value ) - assert isinstance(login_res.id_token, IdToken) + assert isinstance(login_res.id_token, IdTokenMetadata) def test_otk_deleted_after_login(in_memory_session, settings_backup): @@ -461,7 +481,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - raw = auth_service._set_act_fp_cookie(response) + raw_hash = auth_service._set_access_fp_cookie(response) access_token = auth_service._build_access_token( real_account_id=acc.id, @@ -469,18 +489,13 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): effective_role=acc.role, effective_organization_id=acc.organization_id, epoch=acc.epoch, - user_fingerprint_hash=raw, + user_fingerprint_hash=raw_hash, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore - cookie_key=auth_service.ACT_FP_COOKIE_KEY, - token=access_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="wrongcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -495,34 +510,26 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - cookie_raw = auth_service._set_id_fp_cookie(response) past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5) + access_fingerprint_hash = auth_service._set_access_fp_cookie(response) payload = { auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ROLE_KEY: acc.role.value, + auth_service.EFFECTIVE_ORGANIZATION_ID_KEY: str(acc.organization_id), auth_service.EPOCH_KEY: acc.epoch, - auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw, + auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash, } bad_token = auth_service._build_token( payload=payload, expiration_datetime=past, - token_type=auth_service.TokenType.ID_TOKEN, + token_type=auth_service.TokenType.ACCESS_TOKEN, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq( - { - auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"] - .split("=")[1] - .split(";")[0] - } - ), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY), + raw_access_token=bad_token, session=in_memory_session, ) diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py index 0a8b82ca..5a2db2bd 100644 --- a/service/src/main/inse/organization_management/router.py +++ b/service/src/main/inse/organization_management/router.py @@ -5,7 +5,7 @@ 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.auth.model import AccessTokenMetadata from inse.database import get_session from inse.tags import Tags @@ -26,7 +26,7 @@ async def get_organizations( page_size: int = Query(default=25, ge=1, le=100), offset: Optional[int] = Query(default=None, ge=0), session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationPage: return service.get_organizations( session=session, @@ -46,7 +46,7 @@ async def get_organizations( async def create_organization( payload: CreateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.create_organization(session, access_token, payload) @@ -60,7 +60,7 @@ async def update_organization( organization_id: uuid.UUID, payload: UpdateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.update_organization( session, access_token, organization_id, payload @@ -75,7 +75,7 @@ async def update_organization( async def delete_organization( organization_id: uuid.UUID, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_organization(session, access_token, organization_id) return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 80dd88c9..528bcf35 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -4,7 +4,7 @@ from typing import Optional from fastapi import HTTPException, status from sqlmodel import Session, func, select -from inse.auth.model import AccessToken, Account, Organization, UserRole +from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( CreateOrganizationRequest, @@ -14,7 +14,7 @@ from .model import ( ) -def _require_super_admin(access_token: AccessToken) -> None: +def _require_super_admin(access_token: AccessTokenMetadata) -> None: if access_token.effective_role != UserRole.SUPER_ADMIN: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -109,7 +109,7 @@ def _deactivate_organization_accounts( def get_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, @@ -145,7 +145,7 @@ def get_organizations( def create_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateOrganizationRequest, ) -> OrganizationProfile: _require_super_admin(access_token) @@ -164,7 +164,7 @@ def create_organization( def update_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, payload: UpdateOrganizationRequest, ) -> OrganizationProfile: @@ -191,7 +191,7 @@ def update_organization( def delete_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, ) -> None: _require_super_admin(access_token) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index e59c1083..f9ac2e32 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -113,7 +113,7 @@ model/hEUReportSummary.ts model/hEUTopic.ts model/hEUWebLink.ts model/hTTPValidationError.ts -model/idToken.ts +model/idTokenMetadata.ts model/inseAccountManagementModelOrganizationProfile.ts model/inseOrganizationManagementModelOrganizationProfile.ts model/institution.ts @@ -161,7 +161,6 @@ model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts -model/refreshToken.ts model/score.ts model/sortDirection.ts model/tokenType.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 8ea55e0b..817a3a65 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -26,19 +26,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [ - AuthService, - CompanyConnectionsService, - FundingService, - INSEServiceService, - InstitutionsService, - KeywordsService, - NewsService, - OrganizationService, - PatentsService, - PersonNetworkService, - PersonsService, - ProjectsService, - TopicsService, - WorksService, -]; +export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index ef111294..086a0e47 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -66,13 +66,14 @@ export class AuthService extends BaseService { * Change the user\'s password and invalidate existing tokens. * @endpoint post /api/auth/v2/change-password * @param bodyChangePassword + * @param secureFgpAcc * @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 changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyChangePassword === null || bodyChangePassword === undefined) { throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.'); } @@ -134,13 +135,14 @@ export class AuthService extends BaseService { * Create Account * @endpoint post /api/accounts * @param createAccountRequest + * @param secureFgpAcc * @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 createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (createAccountRequest === null || createAccountRequest === undefined) { throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.'); } @@ -202,13 +204,14 @@ export class AuthService extends BaseService { * Delete Account * @endpoint delete /api/accounts/{account_id} * @param accountId + * @param secureFgpAcc * @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 deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (accountId === null || accountId === undefined) { throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.'); } @@ -261,22 +264,20 @@ export class AuthService extends BaseService { * Retrieve an access token for the authenticated user. * @endpoint post /api/auth/v2/access * @param bodyGetAccessToken + * @param idToken * @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 getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.'); } let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -328,13 +329,14 @@ export class AuthService extends BaseService { /** * Get Current Account * @endpoint get /api/accounts/me + * @param secureFgpAcc * @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 getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -433,13 +435,14 @@ export class AuthService extends BaseService { /** * List Organizations * @endpoint get /api/accounts/organizations + * @param secureFgpAcc * @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 listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -492,13 +495,14 @@ export class AuthService extends BaseService { * @param offset * @param search * @param organizationId + * @param secureFgpAcc * @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 listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -626,13 +630,14 @@ export class AuthService extends BaseService { * Logout * Logout the authenticated user. * @endpoint post /api/auth/v2/logout + * @param secureFgpAcc * @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 logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -681,19 +686,17 @@ export class AuthService extends BaseService { * Refresh Access Token * Refresh the access token using a valid refresh token. * @endpoint post /api/auth/v2/refresh + * @param refreshToken * @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 refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -803,13 +806,14 @@ export class AuthService extends BaseService { * @endpoint put /api/accounts/{account_id} * @param accountId * @param updateAccountRequest + * @param secureFgpAcc * @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 updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (accountId === null || accountId === undefined) { throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); } diff --git a/webapp/src/app/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts index da26fff7..1149c309 100644 --- a/webapp/src/app/api/api/iNSEService.service.ts +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,355 +9,205 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class INSEServiceService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @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 buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + let localVarHeaders = this.defaultHeaders; - let localVarPath = `/api/inse-service/topics/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @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 countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @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 countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/hierarchy`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * @endpoint get /api/inse-service/topics/hierarchy - * @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 getTopicHierarchy( - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/hierarchy`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts index 2af0ed8b..14fb942d 100644 --- a/webapp/src/app/api/api/organization.service.ts +++ b/webapp/src/app/api/api/organization.service.ts @@ -47,13 +47,14 @@ export class OrganizationService extends BaseService { * Create Organization * @endpoint post /api/organizations * @param createOrganizationRequest + * @param secureFgpAcc * @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 createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (createOrganizationRequest === null || createOrganizationRequest === undefined) { throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); } @@ -115,13 +116,14 @@ export class OrganizationService extends BaseService { * Delete Organization * @endpoint delete /api/organizations/{organization_id} * @param organizationId + * @param secureFgpAcc * @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 deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (organizationId === null || organizationId === undefined) { throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); } @@ -175,13 +177,14 @@ export class OrganizationService extends BaseService { * @param page * @param pageSize * @param offset + * @param secureFgpAcc * @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 getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -240,13 +243,14 @@ export class OrganizationService extends BaseService { * @endpoint put /api/organizations/{organization_id} * @param organizationId * @param updateOrganizationRequest + * @param secureFgpAcc * @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 updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (organizationId === null || organizationId === undefined) { throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); } diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 904279c3..669a7496 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AllPatentsResponse } from '../model/allPatentsResponse'; @@ -36,657 +30,338 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class PatentsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get all patents with pagination and search. - * @endpoint get /api/inse-service/patents - * @param page - * @param size - * @param search - * @param source - * @param sortBy - * @param sortDirection - * @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 getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - source, - 'source', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortDirection, - 'sort_direction', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get all patents with pagination and search. + * @endpoint get /api/inse-service/patents + * @param page + * @param size + * @param search + * @param source + * @param sortBy + * @param sortDirection + * @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 getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + source, 'source'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Get pre-indexed org patents for an institution. + * @endpoint get /api/inse-service/institutions/{id}/org-patents + * @param id + * @param matchType Filter patents by match type. + * @param page + * @param size + * @param source + * @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 getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.'); + } - /** - * Get pre-indexed org patents for an institution. - * @endpoint get /api/inse-service/institutions/{id}/org-patents - * @param id - * @param matchType Filter patents by match type. - * @param page - * @param size - * @param source - * @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 getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getOrgPatentsByInstitution.', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + matchType, 'match_type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + source, 'source'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/org-patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - matchType, - 'match_type', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - source, - 'source', - ); + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/inse-service/patents/{identifier} + * @param identifier + * @param prefix Application Prefix (EP or US) + * @param title Do we want to fallback to title search if ID and DOI dont work? + * @param fillingDate Filling date in YYYY-MM-DD format + * @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 getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (identifier === null || identifier === undefined) { + throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + prefix, 'prefix'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fillingDate, 'filling_date'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get patents matched to an author by name. + * @endpoint get /api/inse-service/authors/{author_id}/patents + * @param authorId + * @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/org-patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Get patents matched to an institution by assignee name. + * @endpoint get /api/inse-service/institutions/{id}/patents + * @param id + * @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 getPatentsByInstitution(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentsByInstitution(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByInstitution(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByInstitution(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getPatentsByInstitution.'); + } - /** - * Returns one publication by OpenAlex ID or DOI. - * @endpoint get /api/inse-service/patents/{identifier} - * @param identifier - * @param prefix Application Prefix (EP or US) - * @param title Do we want to fallback to title search if ID and DOI dont work? - * @param fillingDate Filling date in YYYY-MM-DD format - * @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 getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (identifier === null || identifier === undefined) { - throw new Error( - 'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.', - ); + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - prefix, - 'prefix', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - title, - 'title', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - fillingDate, - 'filling_date', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get patents matched to an author by name. - * @endpoint get /api/inse-service/authors/{author_id}/patents - * @param authorId - * @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 getPatentsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPatentsByAuthor.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get patents matched to an institution by assignee name. - * @endpoint get /api/inse-service/institutions/{id}/patents - * @param id - * @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 getPatentsByInstitution( - id: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentsByInstitution( - id: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByInstitution( - id: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByInstitution( - id: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getPatentsByInstitution.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 5a51e233..ef7b0c7f 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -34,929 +28,484 @@ import { KeywordsTopicsResponse } from '../model/keywordsTopicsResponse'; import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class TopicsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns topic options for autocomplete inputs. - * @endpoint get /api/topics/autocomplete - * @param query Topic search text, for example \'machine learning\'. - * @param domainId Optional OpenAlex domain id filter. - * @param fieldId Optional OpenAlex field id filter. - * @param subfieldId Optional OpenAlex subfield id filter. - * @param limit Maximum number of autocomplete options. - * @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 autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling autocompleteTopics.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - domainId, - 'domainId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - fieldId, - 'fieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - subfieldId, - 'subfieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + domainId, 'domainId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fieldId, 'fieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + subfieldId, 'subfieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/topics/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @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 buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @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 countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + let localVarPath = `/api/topics/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @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 countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * @endpoint get /api/inse-service/topics/hierarchy - * @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 getTopicHierarchy( - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/hierarchy`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @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 listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/hierarchy`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Semantic / vector search for topics using a keyword/sentence. + * @endpoint get /api/topics/vector-search + * @param query Word or sentence to search by similarity. + * @param limit Maximum number of topics to return. + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @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 vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling vectorSearchTopics.'); + } - /** - * Returns a list of OpenAlex topics. - * @endpoint get /api/topics - * @param search Full-text search, for example \'machine learning\'. - * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'domain.id\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @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 listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filter, - 'filter', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sort, - 'sort', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - groupBy, - 'group_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - perPage, - 'per_page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - cursor, - 'cursor', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sample, - 'sample', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - select, - 'select', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchType, 'searchType'); - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/vector-search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Batch semantic / vector search for multiple keywords. + * @endpoint post /api/topics/vector-search/batch + * @param keywordsTopicsRequest + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @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 vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) { + throw new Error('Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchType, 'searchType'); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/vector-search/batch`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: keywordsTopicsRequest, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/topics`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Semantic / vector search for topics using a keyword/sentence. - * @endpoint get /api/topics/vector-search - * @param query Word or sentence to search by similarity. - * @param limit Maximum number of topics to return. - * @param searchType Search approach: \'hybrid\' or \'semantic\'. - * @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 vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling vectorSearchTopics.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'searchType', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/topics/vector-search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Batch semantic / vector search for multiple keywords. - * @endpoint post /api/topics/vector-search/batch - * @param keywordsTopicsRequest - * @param searchType Search approach: \'hybrid\' or \'semantic\'. - * @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 vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) { - throw new Error( - 'Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'searchType', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - // to determine the Content-Type header - const consumes: string[] = ['application/json']; - const httpContentTypeSelected: string | undefined = - this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Content-Type', - httpContentTypeSelected, - ); - } - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/topics/vector-search/batch`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: keywordsTopicsRequest, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index ca494a80..09641dde 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -36,664 +30,356 @@ import { WorkPage } from '../model/workPage'; import { WorksListResponse } from '../model/worksListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class WorksService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns all works for an author. - * @endpoint get /api/works/{author_id}/all - * @param authorId The author id, for example A5023888391. - * @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 getAllAuthorWorks( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAllAuthorWorks( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAllAuthorWorks.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Returns all works for an author. + * @endpoint get /api/works/{author_id}/all + * @param authorId The author id, for example A5023888391. + * @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 getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAllAuthorWorks.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/all`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - /** - * Returns a page of works for an author. - * @endpoint get /api/works/{author_id} - * @param authorId The author id, for example A5023888391. - * @param page The page number. - * @param size The page size. - * @param publicationYear Filter by publication year. Can be repeated. - * @param type Filter by publication type. Can be repeated. - * @param language Filter by language code. Can be repeated. - * @param institutionId Filter by OpenAlex institution id. Can be repeated. - * @param topicId Filter by OpenAlex topic id. Can be repeated. - * @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 getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAuthorWorks.', - ); - } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - if (publicationYear) { - publicationYear.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'publication_year', + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/all`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (type) { - type.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'type', + + /** + * Returns a page of works for an author. + * @endpoint get /api/works/{author_id} + * @param authorId The author id, for example A5023888391. + * @param page The page number. + * @param size The page size. + * @param publicationYear Filter by publication year. Can be repeated. + * @param type Filter by publication type. Can be repeated. + * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. + * @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + if (publicationYear) { + publicationYear.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_year'); + }) + } + if (type) { + type.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'type'); + }) + } + if (language) { + language.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language'); + }) + } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (language) { - language.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'language', + + /** + * Returns work counts per primary topic for an author. + * @endpoint get /api/works/{author_id}/primary-topic-counts + * @param authorId The author id, for example A5023888391. + * @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 getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-topic-counts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (institutionId) { - institutionId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'institution_id', + + /** + * Returns topics grouped by publication year for an author. + * @endpoint get /api/works/{author_id}/topics-by-time + * @param authorId The author id, for example A5023888391. + * @param maxTopicsPerYear The maximum number of topics per year. + * @param targetPublications Target number of publications used for the timeline. Complete years are always included. + * @param includeAll If true, all publications are used for the timeline. + * @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 getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + maxTopicsPerYear, 'max_topics_per_year'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + targetPublications, 'target_publications'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + includeAll, 'include_all'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/topics-by-time`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (topicId) { - topicId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic_id', + + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/works/detail/{identifier} + * @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication. + * @param title Do we want to fallback to title search if ID and DOI dont work? + * @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 getWork(identifier: string, title?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWork(identifier: string, title?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(identifier: string, title?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(identifier: string, title?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (identifier === null || identifier === undefined) { + throw new Error('Required parameter identifier was null or undefined when calling getWork.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/detail/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns work counts per primary topic for an author. - * @endpoint get /api/works/{author_id}/primary-topic-counts - * @param authorId The author id, for example A5023888391. - * @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 getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.', - ); - } - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/primary-topic-counts`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request>( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns topics grouped by publication year for an author. - * @endpoint get /api/works/{author_id}/topics-by-time - * @param authorId The author id, for example A5023888391. - * @param maxTopicsPerYear The maximum number of topics per year. - * @param targetPublications Target number of publications used for the timeline. Complete years are always included. - * @param includeAll If true, all publications are used for the timeline. - * @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 getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - maxTopicsPerYear, - 'max_topics_per_year', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - targetPublications, - 'target_publications', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - includeAll, - 'include_all', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/topics-by-time`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns one publication by OpenAlex ID or DOI. - * @endpoint get /api/works/detail/{identifier} - * @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication. - * @param title Do we want to fallback to title search if ID and DOI dont work? - * @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 getWork( - identifier: string, - title?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getWork( - identifier: string, - title?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - identifier: string, - title?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - identifier: string, - title?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (identifier === null || identifier === undefined) { - throw new Error( - 'Required parameter identifier was null or undefined when calling getWork.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - title, - 'title', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if ( - this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) - ) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } } diff --git a/webapp/src/app/api/configuration.ts b/webapp/src/app/api/configuration.ts index 17a7070e..2b8c80f7 100644 --- a/webapp/src/app/api/configuration.ts +++ b/webapp/src/app/api/configuration.ts @@ -1,219 +1,193 @@ -import { - HttpHeaders, - HttpParams, - HttpParameterCodec, -} from '@angular/common/http'; +import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import { Param } from './param'; export interface ConfigurationParameters { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Override the default method for encoding path parameters in various - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam?: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials?: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Encoding of various path parameter - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; - constructor({ - accessToken, - apiKeys, - basePath, - credentials, - encodeParam, - encoder, - password, - username, - withCredentials, - }: ConfigurationParameters = {}) { - if (apiKeys) { - this.apiKeys = apiKeys; - } - if (username !== undefined) { - this.username = username; - } - if (password !== undefined) { - this.password = password; - } - if (accessToken !== undefined) { - this.accessToken = accessToken; - } - if (basePath !== undefined) { - this.basePath = basePath; - } - if (withCredentials !== undefined) { - this.withCredentials = withCredentials; - } - if (encoder) { - this.encoder = encoder; - } - this.encodeParam = - encodeParam ?? ((param) => this.defaultEncodeParam(param)); - this.credentials = credentials ?? {}; +constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) { + if (apiKeys) { + this.apiKeys = apiKeys; + } + if (username !== undefined) { + this.username = username; + } + if (password !== undefined) { + this.password = password; + } + if (accessToken !== undefined) { + this.accessToken = accessToken; + } + if (basePath !== undefined) { + this.basePath = basePath; + } + if (withCredentials !== undefined) { + this.withCredentials = withCredentials; + } + if (encoder) { + this.encoder = encoder; + } + this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param)); + this.credentials = credentials ?? {}; - // init default HTTPBearer credential - if (!this.credentials['HTTPBearer']) { - this.credentials['HTTPBearer'] = () => { - return typeof this.accessToken === 'function' - ? this.accessToken() - : this.accessToken; - }; - } - } - - /** - * Select the correct content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param contentTypes - the array of content types that are available for selection - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderContentType(contentTypes: string[]): string | undefined { - if (contentTypes.length === 0) { - return undefined; + // init default HTTPBearer credential + if (!this.credentials['HTTPBearer']) { + this.credentials['HTTPBearer'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } } - const type = contentTypes.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return contentTypes[0]; - } - return type; - } + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } - /** - * Select the correct accept content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param accepts - the array of content types that are available for selection. - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderAccept(accepts: string[]): string | undefined { - if (accepts.length === 0) { - return undefined; + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; } - const type = accepts.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return accepts[0]; + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; } - return type; - } - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * @param mime - MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public isJsonMime(mime: string): boolean { - const jsonMime: RegExp = new RegExp( - '^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', - 'i', - ); - return ( - mime !== null && - (jsonMime.test(mime) || - mime.toLowerCase() === 'application/json-patch+json') - ); - } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } - public lookupCredential(key: string): string | undefined { - const value = this.credentials[key]; - return typeof value === 'function' ? value() : value; - } + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } - public addCredentialToHeaders( - credentialKey: string, - headerName: string, - headers: HttpHeaders, - prefix?: string, - ): HttpHeaders { - const value = this.lookupCredential(credentialKey); - return value ? headers.set(headerName, (prefix ?? '') + value) : headers; - } + public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders { + const value = this.lookupCredential(credentialKey); + return value + ? headers.set(headerName, (prefix ?? '') + value) + : headers; + } - public addCredentialToQuery( - credentialKey: string, - paramName: string, - query: HttpParams, - ): HttpParams { - const value = this.lookupCredential(credentialKey); - return value ? query.set(paramName, value) : query; - } + public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams { + const value = this.lookupCredential(credentialKey); + return value + ? query.set(paramName, value) + : query; + } - private defaultEncodeParam(param: Param): string { - // This implementation exists as fallback for missing configuration - // and for backwards compatibility to older typescript-angular generator versions. - // It only works for the 'simple' parameter style. - // Date-handling only works for the 'date-time' format. - // All other styles and Date-formats are probably handled incorrectly. - // - // But: if that's all you need (i.e.: the most common use-case): no need for customization! + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! - const value = - param.dataFormat === 'date-time' && param.value instanceof Date - ? (param.value as Date).toISOString() - : param.value; + const value = param.dataFormat === 'date-time' && param.value instanceof Date + ? (param.value as Date).toISOString() + : param.value; - return encodeURIComponent(String(value)); - } + return encodeURIComponent(String(value)); + } } diff --git a/webapp/src/app/api/model/accessResponse.ts b/webapp/src/app/api/model/accessResponse.ts index f1610895..6a36e872 100644 --- a/webapp/src/app/api/model/accessResponse.ts +++ b/webapp/src/app/api/model/accessResponse.ts @@ -7,7 +7,6 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { RefreshToken } from './refreshToken'; import { AccessToken } from './accessToken'; @@ -16,9 +15,5 @@ export interface AccessResponse { * The access token issued upon successful authentication. */ access_token: AccessToken; - /** - * The refresh token issued alongside the access token for obtaining new access tokens. - */ - refresh_token: RefreshToken; } diff --git a/webapp/src/app/api/model/accessToken.ts b/webapp/src/app/api/model/accessToken.ts index ce3ea930..2c470009 100644 --- a/webapp/src/app/api/model/accessToken.ts +++ b/webapp/src/app/api/model/accessToken.ts @@ -12,10 +12,6 @@ import { UserRole } from './userRole'; export interface AccessToken { - /** - * The type of the token, which is always ACCESS_TOKEN for this class. - */ - token_type?: TokenType; /** * The unique identifier of the real account associated with this token. */ @@ -29,13 +25,13 @@ export interface AccessToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ACCESS_TOKEN for this class. + */ + token_type?: TokenType; + /** + * A unique fingerprint of the user, used for additional security checks. */ user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; /** * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. */ @@ -48,6 +44,10 @@ export interface AccessToken { * The unique identifier of the organization associated with this access token. */ effective_organization_id: string; + /** + * The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes. + */ + raw_token: string; } export namespace AccessToken { } diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 52a9f7e6..58adefb8 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -26,3 +26,4 @@ export interface AccountProfile { export namespace AccountProfile { } + diff --git a/webapp/src/app/api/model/bodyRequestOtk.ts b/webapp/src/app/api/model/bodyRequestOtk.ts index 1600a002..ba1a396d 100644 --- a/webapp/src/app/api/model/bodyRequestOtk.ts +++ b/webapp/src/app/api/model/bodyRequestOtk.ts @@ -1,20 +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 BodyRequestOtk { - /** - * User\'s email address - */ - email: string; - /** - * User\'s password - */ - password: string; + +export interface BodyRequestOtk { + /** + * User\'s email address + */ + email: string; + /** + * User\'s password + */ + password: string; } + diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts index 94aacb80..fffb5457 100644 --- a/webapp/src/app/api/model/createOrganizationRequest.ts +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -1,14 +1,16 @@ /** * 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 CreateOrganizationRequest { - name: string; - other_inst_id?: string | null; + +export interface CreateOrganizationRequest { + name: string; + other_inst_id?: string | null; } + diff --git a/webapp/src/app/api/model/extractedKeywordsResponse.ts b/webapp/src/app/api/model/extractedKeywordsResponse.ts index 8fe10a5f..43731b7c 100644 --- a/webapp/src/app/api/model/extractedKeywordsResponse.ts +++ b/webapp/src/app/api/model/extractedKeywordsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,17 +10,19 @@ import { ExtractedKeywordsLLM } from './extractedKeywordsLLM'; import { ExtractedKeywords } from './extractedKeywords'; -export interface ExtractedKeywordsResponse { - results_llm?: ExtractedKeywordsLLM | null; - results?: ExtractedKeywords | null; - /** - * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. - */ - source: string; - source_url?: string | null; - /** - * The actual content from which keywords were extracted. - */ - source_content: string; - duration?: number | null; + +export interface ExtractedKeywordsResponse { + results_llm?: ExtractedKeywordsLLM | null; + results?: ExtractedKeywords | null; + /** + * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. + */ + source: string; + source_url?: string | null; + /** + * The actual content from which keywords were extracted. + */ + source_content: string; + duration?: number | null; } + diff --git a/webapp/src/app/api/model/idToken.ts b/webapp/src/app/api/model/idTokenMetadata.ts similarity index 72% rename from webapp/src/app/api/model/idToken.ts rename to webapp/src/app/api/model/idTokenMetadata.ts index e6a88cd3..5398083d 100644 --- a/webapp/src/app/api/model/idToken.ts +++ b/webapp/src/app/api/model/idTokenMetadata.ts @@ -10,11 +10,7 @@ import { TokenType } from './tokenType'; -export interface IdToken { - /** - * The type of the token, which is always ID_TOKEN for this class. - */ - token_type?: TokenType; +export interface IdTokenMetadata { /** * The unique identifier of the real account associated with this token. */ @@ -28,15 +24,11 @@ export interface IdToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ID_TOKEN for this class. */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; + token_type?: TokenType; } -export namespace IdToken { +export namespace IdTokenMetadata { } diff --git a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts index 47235351..c67acc71 100644 --- a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts @@ -1,15 +1,17 @@ /** * 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 InseAccountManagementModelOrganizationProfile { - id: string; - name: string; - openalex_institution_id?: string | null; + +export interface InseAccountManagementModelOrganizationProfile { + id: string; + name: string; + openalex_institution_id?: string | null; } + diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts index 8f9f0e6b..404df0f9 100644 --- a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts @@ -1,17 +1,19 @@ /** * 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 InseOrganizationManagementModelOrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; + +export interface InseOrganizationManagementModelOrganizationProfile { + id: string; + name: string; + other_inst_id?: string | null; + deleted: boolean; + member_count: number; } + diff --git a/webapp/src/app/api/model/keywordTopicMatch.ts b/webapp/src/app/api/model/keywordTopicMatch.ts index ee4c8326..f9c2ab49 100644 --- a/webapp/src/app/api/model/keywordTopicMatch.ts +++ b/webapp/src/app/api/model/keywordTopicMatch.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,7 +9,9 @@ */ import { Topic } from './topic'; -export interface KeywordTopicMatch { - keyword: string; - topic?: Topic | null; + +export interface KeywordTopicMatch { + keyword: string; + topic?: Topic | null; } + diff --git a/webapp/src/app/api/model/keywordsTopicsRequest.ts b/webapp/src/app/api/model/keywordsTopicsRequest.ts index 883ed079..8810bf5f 100644 --- a/webapp/src/app/api/model/keywordsTopicsRequest.ts +++ b/webapp/src/app/api/model/keywordsTopicsRequest.ts @@ -1,16 +1,18 @@ /** * 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 KeywordsTopicsRequest { - /** - * List of keywords/sentences to query by similarity. - */ - keywords: Array; + +export interface KeywordsTopicsRequest { + /** + * List of keywords/sentences to query by similarity. + */ + keywords: Array; } + diff --git a/webapp/src/app/api/model/keywordsTopicsResponse.ts b/webapp/src/app/api/model/keywordsTopicsResponse.ts index 78a2f9d2..4aee622f 100644 --- a/webapp/src/app/api/model/keywordsTopicsResponse.ts +++ b/webapp/src/app/api/model/keywordsTopicsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { KeywordTopicMatch } from './keywordTopicMatch'; -export interface KeywordsTopicsResponse { - /** - * Top matching topics for each keyword in the requested list. - */ - results: Array; + +export interface KeywordsTopicsResponse { + /** + * Top matching topics for each keyword in the requested list. + */ + results: Array; } + diff --git a/webapp/src/app/api/model/loginResponse.ts b/webapp/src/app/api/model/loginResponse.ts index 216d0fb0..c91eb493 100644 --- a/webapp/src/app/api/model/loginResponse.ts +++ b/webapp/src/app/api/model/loginResponse.ts @@ -1,17 +1,19 @@ /** * 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. */ -import { IdToken } from './idToken'; +import { IdTokenMetadata } from './idTokenMetadata'; -export interface LoginResponse { - /** - * The ID token issued upon successful login. - */ - id_token: IdToken; + +export interface LoginResponse { + /** + * The ID token issued upon successful login. + */ + id_token: IdTokenMetadata; } + diff --git a/webapp/src/app/api/model/matchedAuthor.ts b/webapp/src/app/api/model/matchedAuthor.ts index 311e2184..6194df94 100644 --- a/webapp/src/app/api/model/matchedAuthor.ts +++ b/webapp/src/app/api/model/matchedAuthor.ts @@ -1,14 +1,16 @@ /** * 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 MatchedAuthor { - openalex_author_id: string; - author_name: string; + +export interface MatchedAuthor { + openalex_author_id: string; + author_name: string; } + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 7868aabe..3bf537d5 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -89,7 +89,7 @@ export * from './hEUReportSummary'; export * from './hEUTopic'; export * from './hEUWebLink'; export * from './hTTPValidationError'; -export * from './idToken'; +export * from './idTokenMetadata'; export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; @@ -136,7 +136,6 @@ export * from './publicationDetailByFunder'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; -export * from './refreshToken'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/refreshToken.ts b/webapp/src/app/api/model/refreshToken.ts deleted file mode 100644 index 89506b70..00000000 --- a/webapp/src/app/api/model/refreshToken.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 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. - */ -import { TokenType } from './tokenType'; -import { UserRole } from './userRole'; - - -export interface RefreshToken { - /** - * The type of the token, which is always REFRESH_TOKEN for this class. - */ - token_type?: TokenType; - /** - * The unique identifier of the real account associated with this token. - */ - real_account_id: string; - /** - * The timestamp indicating when the token will expire. - */ - expires_at: string; - /** - * The epoch value for the token. Used for versioning of tokens. - */ - epoch?: number; - /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. - */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; - /** - * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. - */ - effective_account_id: string; - /** - * The specific role this access token grants within its organization. - */ - effective_role?: UserRole; - /** - * The unique identifier of the organization associated with this access token. - */ - effective_organization_id: string; -} -export namespace RefreshToken { -} - - diff --git a/webapp/src/app/api/model/tokenType.ts b/webapp/src/app/api/model/tokenType.ts index 06231c11..a0efdc46 100644 --- a/webapp/src/app/api/model/tokenType.ts +++ b/webapp/src/app/api/model/tokenType.ts @@ -10,9 +10,9 @@ export const TokenType = { - Id: 'ID', - Refresh: 'REFRESH', - Access: 'ACCESS' + IdToken: 'ID_TOKEN', + RefreshToken: 'REFRESH_TOKEN', + AccessToken: 'ACCESS_TOKEN' } as const; export type TokenType = typeof TokenType[keyof typeof TokenType]; diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index 1d4389f7..efc4cea6 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -23,3 +23,4 @@ export interface UpdateAccountRequest { export namespace UpdateAccountRequest { } + diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts index a56b51e7..e12063b6 100644 --- a/webapp/src/app/api/model/updateOrganizationRequest.ts +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -1,15 +1,17 @@ /** * 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 UpdateOrganizationRequest { - name?: string | null; - other_inst_id?: string | null; - deleted?: boolean | null; + +export interface UpdateOrganizationRequest { + name?: string | null; + other_inst_id?: string | null; + deleted?: boolean | null; } + 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 db6739c5..a8bd7fea 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -91,7 +91,7 @@ export class AppLoginComponent implements OnDestroy { this.stopCountdown(); } - async requestOtk() { + requestOtk() { if (this.credentialsForm.invalid || this.isSubmitting) { this.credentialsForm.markAllAsTouched(); return; @@ -103,36 +103,35 @@ export class AppLoginComponent implements OnDestroy { const email = this.credentialsForm.controls.email.value ?? ''; const password = this.credentialsForm.controls.password.value ?? ''; - 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, - }, - ); - } catch (error: unknown) { - this.credentialService.clearLocalAuthState(); - this.snackBar.open( - this.getLoginErrorMessage(error as HttpErrorResponse), - 'OK', - { - duration: 5000, - }, - ); - } finally { - this.isSubmitting = false; - this.credentialsForm.enable(); - } + this.credentialService.requestOtk(email, password).subscribe({ + next: (otkResponse) => { + 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: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.credentialsForm.enable(); + }, + }); } resendCode() { @@ -143,7 +142,7 @@ export class AppLoginComponent implements OnDestroy { this.requestOtk(); } - async login() { + login() { if (this.otkForm.invalid || this.isSubmitting) { this.otkForm.markAllAsTouched(); return; @@ -170,23 +169,30 @@ export class AppLoginComponent implements OnDestroy { const code = this.otkForm.controls.code.value ?? ''; - 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, - }, - ); - } finally { - this.isSubmitting = false; - this.otkForm.enable(); - } + this.credentialService.loginWithOtk(this.accountId, code).subscribe({ + next: () => { + this.credentialService.reauthenticateViaIdToken().subscribe({ + next: () => { + this.checkEnter(); + this.stopCountdown(); + this.router.navigate(['/dashboard']); + }, + }); + }, + error: (error: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.otkForm.enable(); + }, + }); } editCredentials() { diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 194799a2..08113260 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -5,69 +5,100 @@ import { } from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; -import { catchError, throwError } from 'rxjs'; -import { CredentialService } from '../services/credential.service'; +import { catchError, switchMap, throwError } from 'rxjs'; +import { + CredentialService, + clearStoredAuthState, + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE, +} from '../services/credential.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]; - - if (isUnauthenticatedPostRequest(req)) { - return next(req); - } - - const credentialService = inject(CredentialService); - const router = inject(Router); - - 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), - }); - - return next(authorizedRequest).pipe( - catchError((error: HttpErrorResponse) => { - console.error('Authentication error:', error); - return throwError(() => error); - }), - ); -}; - -const attachToken = ( - req: HttpRequest, +const attachBearer = ( + req: HttpRequest, token: string, -): HttpRequest => { +): HttpRequest => { + if (!token) { + return req; + } return req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token), }); }; + +const handleAccessTokenError = ( + error: unknown, + req: HttpRequest, + next: Parameters[1], + credentialService: CredentialService, + router: Router, +) => { + if (!(error instanceof HttpErrorResponse) || error.status !== 401) { + return throwError(() => error); + } + + if (!credentialService.getRawAccessToken()) { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => error); + } + + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => next(attachBearer(req, accessToken.raw_token))), + catchError((refreshError) => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => refreshError); + }), + ); +}; + +export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { + const router = inject(Router); + + const requiredType = req.context.get(REQUIRED_TOKEN_TYPE); + + if (requiredType === TOKEN_TYPE.NONE) { + return next(req); + } + + if (requiredType === TOKEN_TYPE.ID_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })).pipe( + catchError((err) => { + if (err instanceof HttpErrorResponse && err.status === 401) { + clearStoredAuthState(); + router.navigate(['/login'], { replaceUrl: true }); + } + return throwError(() => err); + }), + ); + } + + if (requiredType === TOKEN_TYPE.REFRESH_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })); + } + + const credentialService = inject(CredentialService); + + const rawAccessToken = credentialService.getRawAccessToken(); + + if (rawAccessToken && credentialService.accessTokenIsExpired()) { + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => + next(attachBearer(req, accessToken.raw_token)), + ), + catchError(() => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError( + () => new Error('Sitzung abgelaufen. Bitte erneut anmelden.'), + ); + }), + ); + } + + return next(rawAccessToken ? attachBearer(req, rawAccessToken) : req).pipe( + catchError((err) => + handleAccessTokenError(err, req, next, credentialService, router), + ), + ); +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index be87cb65..e70311a2 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,17 +1,55 @@ 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 { + catchError, + finalize, + firstValueFrom, + map, + Observable, + of, + shareReplay, + switchMap, + tap, + throwError, +} from 'rxjs'; import { AccessResponse, - AccessToken, AuthService, - IdToken, AccountProfile, - RefreshToken, OtkResponse, + IdTokenMetadata, + AccessToken, + LoginResponse, } from '../../api'; import { Router } from '@angular/router'; +import { HttpContext, HttpContextToken } from '@angular/common/http'; + +export const TOKEN_TYPE = { + ACCESS_TOKEN: 'ACCESS_TOKEN', + ID_TOKEN_COOKIE: 'ID_TOKEN_COOKIE', + REFRESH_TOKEN_COOKIE: 'REFRESH_TOKEN_COOKIE', + NONE: 'NONE', +} as const; + +export type TokenContextType = (typeof TOKEN_TYPE)[keyof typeof TOKEN_TYPE]; + +export const REQUIRED_TOKEN_TYPE = new HttpContextToken( + () => TOKEN_TYPE.ACCESS_TOKEN, +); + +const STORAGE_KEY = 'auth_state'; + +export const clearStoredAuthState = (): void => { + localStorage.removeItem(STORAGE_KEY); +}; + +export interface StoredAuthState { + idTokenMetadata: IdTokenMetadata | null; + accessToken: AccessToken | null; +} + +const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds @Injectable({ providedIn: 'root', @@ -19,10 +57,6 @@ import { Router } from '@angular/router'; export class CredentialService { private readonly authService = inject(AuthService); - 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 isValidating = signal(false); public readonly isAuthenticated = computed( () => this.accessToken() !== undefined, @@ -59,18 +93,8 @@ export class CredentialService { () => this.realAccountId() !== this.effectiveAccountId(), ); - public readonly identityToken = signal(undefined); - public readonly refreshToken = signal(undefined); public readonly accessToken = signal(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 ( @@ -80,9 +104,9 @@ export class CredentialService { }); public readonly accountProfile = toSignal( - toObservable(this.isAuthenticated).pipe( - switchMap((isAuthenticated) => - isAuthenticated + toObservable(this.accessToken).pipe( + switchMap((accessToken) => + accessToken ? this.authService.getCurrentAccount() : of(undefined), ), @@ -90,216 +114,262 @@ export class CredentialService { { initialValue: undefined }, ); + private refreshInFlight$: Observable | null = null; + 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) { - this.loadTokensFromStorage(); + this.restoreAuthState(); + effect(() => { - console.log('IdToken', this.identityToken()); - console.log('RefreshToken', this.refreshToken()); - console.log('AccessToken', this.accessToken()); + console.log('Access token changed:', this.accessToken()); }); - const id = this.identityToken(); - if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.isValidating.set(true); - setTimeout(() => this.refreshAccessToken(id), 0); + + const storedAccessToken = this.getStoredAccessToken(); + if (storedAccessToken && this.isExpired(storedAccessToken)) { + this.refreshAccessToken().subscribe({ + error: (err) => { + console.error('Error refreshing access token on init:', err); + this.logout(); + this.router.navigate(['/login'], { replaceUrl: true }); + }, + }); } } - public async requestOtk( - email: string, - password: string, - ): Promise { - this.isValidating.set(true); - this.identityToken.set(undefined); - this.accessToken.set(undefined); - - const otkResponse: OtkResponse = await firstValueFrom( - this.authService.requestOtk({ - email: email.trim().toLowerCase(), - password, - }), - ); - - this.isValidating.set(false); - return otkResponse; + private restoreAuthState(): void { + this.accessToken.set(this.getStoredAccessToken() ?? undefined); } - public async loginWithOtk( + private readAuthState(): StoredAuthState { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) { + return { idTokenMetadata: null, accessToken: null }; + } + try { + return JSON.parse(raw) as StoredAuthState; + } catch { + return { idTokenMetadata: null, accessToken: null }; + } + } + + private writeAuthState(patch: Partial): void { + const next: StoredAuthState = { + ...this.readAuthState(), + ...patch, + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } + + private persistAccessToken(accessToken: AccessToken | null): void { + this.writeAuthState({ accessToken }); + this.accessToken.set(accessToken ?? undefined); + } + + private getStoredIdTokenMetadata(): IdTokenMetadata | null { + return this.readAuthState().idTokenMetadata; + } + + private getStoredAccessToken(): AccessToken | null { + return this.readAuthState().accessToken; + } + + private isExpired(token: { expires_at: string }): boolean { + return new Date(token.expires_at).getTime() < Date.now() + EXPIRY_SKEW_MS; + } + + public accessTokenIsExpired(): boolean { + const accessToken = this.getStoredAccessToken(); + return !accessToken || this.isExpired(accessToken); + } + + public logout() { + clearStoredAuthState(); + this.accessToken.set(undefined); + this.refreshInFlight$ = null; + } + + public requestOtk(email: string, password: string): Observable { + return this.authService.requestOtk( + { + email: email.trim(), + password: password.trim(), + }, + undefined, + undefined, + { context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) }, + ); + } + + public loginWithOtk( accountId: string, emailCode: string, - ): Promise { - const request = ++this.request; - this.isValidating.set(true); + ): Observable { + return this.authService + .login( + { + account_id: accountId, + email_code: emailCode.trim(), + }, + undefined, + undefined, + { + context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE), + }, + ) + .pipe( + tap(({ id_token }) => + this.writeAuthState({ idTokenMetadata: id_token }), + ), + ); + } - const loginResponse = await firstValueFrom( - this.authService.login({ - account_id: accountId, - email_code: emailCode.trim(), + public requestAccess( + realAccountId: string, + effectiveAccountId?: string, + ): Observable { + return this.authService + .getAccessToken( + { + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, + }, + undefined, + 'body', + undefined, + { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.ID_TOKEN_COOKIE, + ), + }, + ) + .pipe( + tap(({ access_token }) => { + this.persistAccessToken(access_token); + }), + ); + } + + public changePassword( + currentPassword: string, + newPassword: string, + ): Observable { + this.isValidating.set(true); + return this.authService + .changePassword({ + current_password: currentPassword, + new_password: newPassword, + }) + .pipe( + tap(() => this.isValidating.set(false)), + catchError((err) => { + this.isValidating.set(false); + return throwError(() => err); + }), + ); + } + + public refreshAccessToken(): Observable { + if (this.refreshInFlight$) { + return this.refreshInFlight$; + } + + this.refreshInFlight$ = this.authService + .refreshAccessToken(undefined, 'body', undefined, { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.REFRESH_TOKEN_COOKIE, // 'REFRESH_TOKEN_COOKIE' and NOT 'REFRESH_COOKIE', + 30 Minutes debugging this shit, changed to types + ), + }) + .pipe( + tap((accessToken) => { + this.persistAccessToken(accessToken); + }), + catchError(() => this.reauthenticateViaIdToken()), + finalize(() => { + this.refreshInFlight$ = null; + }), + shareReplay(1), + ); + + return this.refreshInFlight$; + } + + reauthenticateViaIdToken(): Observable { + const idTokenMetadata = this.getStoredIdTokenMetadata(); + + if (!idTokenMetadata || this.isExpired(idTokenMetadata)) { + this.logout(); + return throwError( + () => new Error('No valid ID token metadata available.'), + ); + } + + return this.requestAccess( + idTokenMetadata.real_account_id, + idTokenMetadata.real_account_id, + ).pipe( + map(({ access_token }) => access_token), + catchError((err) => { + console.error('Error reauthenticating via ID token:', err); + this.logout(); + return throwError(() => err); }), ); - - const idToken = loginResponse.id_token; - this.identityToken.set(idToken); - this.storeIdentityToken(idToken); - - this.isValidating.set(false); - await this.getAccessToken(idToken, request); } - public async refreshAccessToken(identityToken: IdToken) { - const request = ++this.request; - this.isValidating.set(true); - this.accessToken.set(undefined); - - await this.getAccessToken(identityToken, request).catch((err) => { - if (this.request === request) { - this.clearLocalAuthState(); - } - throw err; - }); - - this.isValidating.set(false); + public getRawAccessToken(): string | undefined { + return this.getStoredAccessToken()?.raw_token; } - public async impersonateAccount(accountId: string): Promise { - const idToken = this.identityToken(); - - if (!idToken) { - throw new Error('No identity token available.'); + public async impersonateAccount(effectiveAccountId: string): Promise { + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); } const request = ++this.request; this.isValidating.set(true); - this.accessToken.set(undefined); - await this.getAccessToken(idToken, request, accountId).catch((err) => { - if (this.request === request) { - this.clearLocalAuthState(); + + try { + await firstValueFrom( + this.requestAccess(realAccountId, effectiveAccountId), + ); + } finally { + if (request === this.request) { + this.isValidating.set(false); } - throw err; - }); - this.isValidating.set(false); + } } public async stopImpersonating(): Promise { - const idToken = this.identityToken(); + this.isValidating.set(true); - if (!idToken) { - throw new Error('No identity token available.'); + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); } - const request = ++this.request; - this.isValidating.set(true); - this.accessToken.set(undefined); - await this.getAccessToken(idToken, request); - this.isValidating.set(false); + try { + await firstValueFrom(this.requestAccess(realAccountId, realAccountId)); + } finally { + this.isValidating.set(false); + } } - public async logoutAccount() { - await firstValueFrom(this.authService.logout()); - this.clearLocalAuthState(); - } - - public clearLocalAuthState(): void { - this.request += 1; - this.clearTokensFromStorage(); - this.identityToken.set(undefined); - this.accessToken.set(undefined); - this.isValidating.set(false); - this.router.navigate(['/login'], { replaceUrl: true }); - } - - public async changePassword( - currentPassword: string, - newPassword: string, - ): Promise { - this.isValidating.set(true); - await firstValueFrom( - this.authService.changePassword({ - current_password: currentPassword, - new_password: newPassword, - }), - ); - this.clearLocalAuthState(); - this.isValidating.set(false); + public async logoutAccount(): Promise { + try { + await firstValueFrom(this.authService.logout()); + } catch (err) { + console.error('Error logging out on the server:', err); + } finally { + this.logout(); + await this.router.navigate(['/login'], { replaceUrl: true }); + } } public registerAccount(_data: unknown): Observable { return throwError(() => new Error('Registration is temporarily disabled.')); } - - private async getAccessToken( - idToken: IdToken, - request: number, - effectiveAccountId?: string, - ): Promise { - if (this.request !== request) { - return; - } - - const realAccountId = idToken.real_account_id; - - const result: AccessResponse = await firstValueFrom( - this.authService.getAccessToken({ - real_account_id: realAccountId, - effective_account_id: effectiveAccountId ?? realAccountId, - }), - ); - - this.accessToken.set(result.access_token); - this.refreshToken.set(result.refresh_token); - this.isValidating.set(false); - } } 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 bee7ed7c..abd2f2ec 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 @@ -105,12 +105,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy { async logout() { const isImpersonating = this.credentialService.isImpersonating(); - await this.credentialService.stopImpersonating(); - if (isImpersonating) { + await this.credentialService.stopImpersonating(); this.router.navigate(['/accounts']); } else { - this.router.navigate(['/login']); + await this.credentialService.logoutAccount(); } } 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 9ce28c8d..f39ff565 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 @@ -142,9 +142,7 @@ export class AppMenuComponent { label: 'Navigation', items: this.navItems.filter( (item) => - !item.adminOnly && - !item.superAdminOnly && - !item.managerOrAdminOnly, + !item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly, ), }, { @@ -181,9 +179,7 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAccount().then(() => { - this.router.navigate(['/login']); - }); + void this.credentialService.logoutAccount(); }); } } From b2d965d60457b8e4c54849b29c7ce05a40dbdd4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 16:15:41 +0200 Subject: [PATCH 6/6] fix(frontend): added label to some query param selectors --- .../institutions/institutions.component.html | 6 ++++-- .../institutions/institutions.component.scss | 2 +- .../src/app/modules/patents/patents.component.html | 13 +++++-------- webapp/src/app/modules/patents/patents.component.ts | 11 +++++++++++ .../app/modules/projects/projects.component.html | 6 ++++-- 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 0ec24397..5edb4c3c 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -12,11 +12,13 @@
+ [queryParamKey]="'sort_by'" + label="Sortieren nach" /> + [queryParamKey]="'sorting_order'" + label="Sortierreihenfolge" />
diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 7303fdd7..8edbecef 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -25,7 +25,7 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(550px, 1fr)); padding: 0 1rem; } diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 14a37666..60086f40 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -26,14 +26,11 @@ USPTO -
- -
+ diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index adfd23e2..0eb946dc 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -15,6 +15,10 @@ import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; import { IpcClassification } from '../../api'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -44,6 +48,7 @@ const DESCRIPTION_PREVIEW_LENGTH = 140; MatProgressSpinnerModule, MatChipsModule, MatDividerModule, + QueryParamSelectorComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', @@ -71,6 +76,12 @@ export class PatentsComponent implements OnInit { private searchSubject = new Subject(); + sortingDirectionOptions: SelectorOption[] = [ + { value: '', display_name: '' }, + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; + constructor() { this.searchSubject .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 706f34fb..b2bcbddf 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -28,11 +28,13 @@
+ queryParamKey="sort_by" + label="Sortieren nach" /> + queryParamKey="sorting_order" + label="Sortierreihenfolge" />