From a2ed442dcc3da507866ea81465c644cafa89d053 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:38:42 +0200 Subject: [PATCH 1/9] adjusted confirmation dialog component for reusability --- .../ui/app-menu/app-menu.component.html | 5 ++-- .../shared/ui/app-menu/app-menu.component.ts | 23 ++++++++++++++-- .../confirmation-dialog.component.html | 12 ++++----- .../confirmation-dialog.component.ts | 26 ++++++++++++++++--- 4 files changed, 51 insertions(+), 15 deletions(-) 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 942b7cbd..5963c6ee 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 @@ -37,11 +37,12 @@
-
M
+
{{ (credentialService.login | async)?.charAt(0) }}
{{ (credentialService.login | async) || 'Max Mustermann' }} + {{ credentialService.organizationName | async }} Startup Coach
expand_more @@ -51,7 +52,7 @@ 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 371cedb4..f721e12d 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 @@ -1,10 +1,12 @@ -import { Component, computed } from '@angular/core'; +import { Component, computed ,inject} from '@angular/core'; import { CommonModule } from '@angular/common'; import { Router, RouterLink, RouterLinkActive } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; import { CredentialService } from '../../services/credential.service'; import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatDialog } from '@angular/material/dialog'; +import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; @Component({ selector: 'app-menu', @@ -32,7 +34,7 @@ export class AppMenuComponent { label: 'Personen', icon: 'groups', route: '/persons', - queryParams: { institutionName: 'University of Duisburg-Essen' }, + queryParams: { institutionName: this.credentialService.organizationName.value }, disabled: false, }, ]; @@ -43,4 +45,21 @@ export class AppMenuComponent { ) {} isNavigating = computed(() => !!this.router.currentNavigation()); + private readonly dialog = inject(MatDialog); + + onLogout() { + const dialogRef = this.dialog.open(ConfirmationDialogComponent, { + data: { + title: 'Abmelden', + message: 'Möchtest Du Dich wirklich abmelden?', + confirmText: 'Abmelden', + cancelText: 'Abbrechen', + }, + }); + + dialogRef.componentInstance.confirmDelete.subscribe(() => { + this.credentialService.logoutAcount(); + this.router.navigate(['/login']); + }); + } } diff --git a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.html b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.html index 4974895d..f758120a 100644 --- a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.html +++ b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.html @@ -1,13 +1,11 @@ -

Daten löschen

-Bist Du sicher, dass Du die Daten löschen möchtest? Diesen Vorgang kannst Du - nicht mehr rückgängig machen. +

{{ data.title }}

+{{ data.message }} + diff --git a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.ts b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.ts index a5198420..c9a7f14e 100644 --- a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.ts +++ b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.ts @@ -1,18 +1,25 @@ -import { Component, EventEmitter } from '@angular/core'; +import { Component, EventEmitter, inject, Inject, Optional } from '@angular/core'; import { MatDialogRef, MatDialogActions, MatDialogClose, MatDialogTitle, MatDialogContent, + MAT_DIALOG_DATA, } from '@angular/material/dialog'; import { MatButtonModule } from '@angular/material/button'; +export interface ConfirmationData { + title: string; + message: string; + confirmText: string; + cancelText: string; +} + @Component({ selector: 'app-confirmation-dialog', imports: [ MatDialogActions, - MatDialogClose, MatDialogContent, MatDialogTitle, MatButtonModule, @@ -22,9 +29,20 @@ import { MatButtonModule } from '@angular/material/button'; standalone: true, }) export class ConfirmationDialogComponent { - confirmDelete = new EventEmitter(); - constructor(public dialogRef: MatDialogRef) {} + confirmDelete = new EventEmitter(); + + constructor( + public dialogRef: MatDialogRef, + @Optional() @Inject(MAT_DIALOG_DATA) public data: ConfirmationData + ) { + this.data = data || { + title: 'Daten löschen', + message: 'Bist Du sicher, dass Du die Daten löschen möchtest? Diesen Vorgang kannst Du nicht mehr rückgängig machen.', + confirmText: 'Löschen', + cancelText: 'Abbrechen' + }; + } onCancelClick(): void { this.dialogRef.close(); -- 2.56.1 From 28b8fff4dd255a2d30d60f4143dc778d4dc46358 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:41:37 +0200 Subject: [PATCH 2/9] added users register component --- service/src/main/inse/account/logic.py | 31 +++++ service/src/main/inse/account/service.py | 47 ++++++- .../app/api/api/iNSEAccountService.service.ts | 95 +++++++++++-- webapp/src/app/api/model/bodyCreateUser.ts | 19 +++ webapp/src/app/api/model/models.ts | 2 + webapp/src/app/app.routes.ts | 7 + .../app-login/app-login.component.html | 6 + .../app-login/app-login.component.scss | 2 +- .../modules/app-login/app-login.component.ts | 3 +- .../app-register/app-register.component.html | 97 +++++++++++++ .../app-register/app-register.component.scss | 56 ++++++++ .../app-register/app-register.component.ts | 131 ++++++++++++++++++ 12 files changed, 479 insertions(+), 17 deletions(-) create mode 100644 webapp/src/app/api/model/bodyCreateUser.ts create mode 100644 webapp/src/app/modules/app-register/app-register.component.html create mode 100644 webapp/src/app/modules/app-register/app-register.component.scss create mode 100644 webapp/src/app/modules/app-register/app-register.component.ts diff --git a/service/src/main/inse/account/logic.py b/service/src/main/inse/account/logic.py index 96257b7e..b443254c 100644 --- a/service/src/main/inse/account/logic.py +++ b/service/src/main/inse/account/logic.py @@ -33,3 +33,34 @@ def validate_user(username: str, password: str) -> typing.Optional[model.User]: if user and user.password == password: return user return None + +def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]: + ''' Adds a new user to the user configuration file. ''' + users = _get_users() + if any(u.username == username for u in users): + logger.warning("Attempt to create duplicate user: %s", username) + return None + + # Determine new IDs + next_account = max((u.account for u in users), default=0) + 1 + next_org = max((u.organization for u in users), default=0) + 1 + + new_user = model.User( + username=username, + password=password, + email=email, + account=next_account, + organization=next_org, + organization_name=institution, + superadmin=superadmin + ) + + users.append(new_user) + user_file = model.UserFile(users=users) + try: + with open('../data/users.json', 'w') as file: + file.write(user_file.model_dump_json(indent=4)) + return new_user + except Exception as e: + logger.error('Could not write user configuration file.', exc_info=e) + return None diff --git a/service/src/main/inse/account/service.py b/service/src/main/inse/account/service.py index 7e67bb19..ae99cd7b 100644 --- a/service/src/main/inse/account/service.py +++ b/service/src/main/inse/account/service.py @@ -27,6 +27,7 @@ router = fastapi.APIRouter( @router.post( "/auth/id", + operation_id="getIdentityGrant", responses={ HTTP_200_OK: {"model": model.IdentityGrant}, HTTP_400_BAD_REQUEST: { @@ -55,7 +56,11 @@ async def get_identity_grant( exp = 12 * 60 * 60 token = security.id_token(user, exp=exp) account = model.AuthAccount( - i=user.account, l=user.username, o=user.organization + i=user.account, + l=user.username, + o=user.organization, + e=user.email, + on=user.organization_name, ) scope = model.AuthScope(t="ID", a=account, d=None, r=[]) grant = model.IdentityGrant( @@ -70,6 +75,7 @@ async def get_identity_grant( @router.post( "/auth/access", + operation_id="getAccessGrant", responses={ HTTP_200_OK: {"model": model.AccessGrant}, HTTP_400_BAD_REQUEST: { @@ -104,7 +110,11 @@ async def get_access_grant( token = security.access_token(user, exp=exp) refresh = security.refresh_token(user, exp=exp) auth_account = model.AuthAccount( - i=user.account, l=user.username, o=user.organization + i=user.account, + l=user.username, + o=user.organization, + e=user.email, + on=user.organization_name, ) scope = model.AuthScope( t="ACCESS", @@ -124,3 +134,36 @@ async def get_access_grant( except Exception as e: logger.error("Token generation failed (%s).", user.username, exc_info=e) raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR) + + +@router.post( + "/create", + operation_id="createUser", + responses={ + HTTP_200_OK: {"model": model.User}, + HTTP_400_BAD_REQUEST: { + "model": None, + "description": "User creation failed (e.g. duplicate username).", + }, + HTTP_500_INTERNAL_SERVER_ERROR: { + "model": None, + "description": "Internal server error.", + }, + }, +) +async def create_user( + username: typing.Annotated[str, fastapi.Body()], + password: typing.Annotated[str, fastapi.Body()], + email: typing.Annotated[str, fastapi.Body()], + institution: typing.Annotated[str, fastapi.Body()], + superadmin: typing.Annotated[bool, fastapi.Body()] = False, +): + user = logic.create_user(username, password, email, institution, superadmin) + if user is None: + logger.info("User creation failed for (%s).", username) + raise fastapi.HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="User creation failed. Username might already exist." + ) + logger.info("User created successfully (%s).", username) + return user diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts index 7b43eaa5..90181dbd 100644 --- a/webapp/src/app/api/api/iNSEAccountService.service.ts +++ b/webapp/src/app/api/api/iNSEAccountService.service.ts @@ -19,9 +19,13 @@ import { Observable } from 'rxjs'; // @ts-ignore import { AccessGrant } from '../model/accessGrant'; // @ts-ignore +import { BodyCreateUser } from '../model/bodyCreateUser'; +// @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { IdentityGrant } from '../model/identityGrant'; +// @ts-ignore +import { User } from '../model/user'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -39,6 +43,71 @@ export class INSEAccountServiceService extends BaseService { super(basePath, configuration); } + /** + * Create User + * @endpoint post /inse-account/create + * @param bodyCreateUser + * @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 createUser(bodyCreateUser: BodyCreateUser, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (bodyCreateUser === null || bodyCreateUser === undefined) { + throw new Error('Required parameter bodyCreateUser was null or undefined when calling createUser.'); + } + + 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 = `/inse-account/create`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyCreateUser, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Get Access Grant * @endpoint post /inse-account/auth/access @@ -48,18 +117,18 @@ export class INSEAccountServiceService 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 getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (secret === null || secret === undefined) { - throw new Error('Required parameter secret was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + throw new Error('Required parameter secret was null or undefined when calling getAccessGrant.'); } if (account === null || account === undefined) { - throw new Error('Required parameter account was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + throw new Error('Required parameter account was null or undefined when calling getAccessGrant.'); } if (organization === null || organization === undefined) { - throw new Error('Required parameter organization was null or undefined when calling getAccessGrantInseAccountAuthAccessPost.'); + throw new Error('Required parameter organization was null or undefined when calling getAccessGrant.'); } let localVarHeaders = this.defaultHeaders; @@ -136,15 +205,15 @@ export class INSEAccountServiceService 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 getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.'); + throw new Error('Required parameter username was null or undefined when calling getIdentityGrant.'); } if (password === null || password === undefined) { - throw new Error('Required parameter password was null or undefined when calling getIdentityGrantInseAccountAuthIdPost.'); + throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.'); } let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/bodyCreateUser.ts b/webapp/src/app/api/model/bodyCreateUser.ts new file mode 100644 index 00000000..76caab3b --- /dev/null +++ b/webapp/src/app/api/model/bodyCreateUser.ts @@ -0,0 +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 BodyCreateUser { + username: string; + password: string; + email: string; + institution: string; + superadmin?: boolean; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 8caaecfd..7b37e6c3 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -16,6 +16,7 @@ export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; +export * from './bodyCreateUser'; export * from './bundProject'; export * from './bundProjectPage'; export * from './categoryNested'; @@ -74,6 +75,7 @@ export * from './topicSubfield'; export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; +export * from './user'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index dab2a1f0..9c674dc3 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -16,6 +16,13 @@ export const routes: Routes = [ import('./modules/app-login/app-login.component').then( (mod) => mod.AppLoginComponent, ), + }, + { + path: 'register', + loadComponent: () => + import('./modules/app-register/app-register.component').then( + (mod) => mod.AppRegisterComponent, + ), }, { path: 'dashboard', diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index 4ebfd0be..957a6b5f 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -42,6 +42,12 @@ [disabled]="!loginForm.valid || (credentialService.validating | async)"> Anmelden + +
+ +

@if (credentialService.validating | async) { diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index 56b7c05a..034b92ac 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -37,7 +37,7 @@ } .field { - width: 300px; + width: 400px; } .progress { 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 17353a00..24fd129f 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -13,7 +13,7 @@ import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { Router } from '@angular/router'; +import { Router, RouterLink } from '@angular/router'; @Component({ selector: 'app-app-login', @@ -25,6 +25,7 @@ import { Router } from '@angular/router'; MatButtonModule, MatIconModule, MatSnackBarModule, + RouterLink, ], templateUrl: './app-login.component.html', styleUrl: './app-login.component.scss', diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html new file mode 100644 index 00000000..018be1bf --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -0,0 +1,97 @@ +

+
+

Konto erstellen

+

+ Bitte gib Deine Daten ein, um Dich zu registrieren. +

+ + + Benutzername + + @if (registerForm.controls['username'].hasError('required')) { + Fehler: Benutzername erforderlich. + } @else if (registerForm.controls['username'].hasError('minlength')) { + Fehler: Benutzername ist unvollständig. + } + + + + E-Mail + + @if (registerForm.controls['email'].hasError('required')) { + Fehler: E-Mail erforderlich. + } @else if (registerForm.controls['email'].hasError('email')) { + Fehler: Ungültige E-Mail Adresse. + } + + + + Passwort + + @if (showPassword) { + visibility + } @else { + visibility_off + } + @if (registerForm.controls['password'].hasError('required')) { + Fehler: Passwort erforderlich. + } @else if (registerForm.controls['password'].hasError('minlength')) { + Fehler: Passwort ist unvollständig. + } + + + + Institution + + apartment + + @if (registerForm.controls['institution'].hasError('required')) { + Fehler: Institution erforderlich. + } + + @for (institution of institutionOptions(); track institution.id) { + +
{{ institution.display_name }}
+ @if (institution.hint) { + {{ institution.hint }} + } +
+ } +
+
+ +
+ Superadmin Rechte +
+ + + +
+ +
+
+

+ +

+
\ No newline at end of file diff --git a/webapp/src/app/modules/app-register/app-register.component.scss b/webapp/src/app/modules/app-register/app-register.component.scss new file mode 100644 index 00000000..d1585259 --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.scss @@ -0,0 +1,56 @@ +.container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + background: linear-gradient(160deg, #f4f6fb, #e8ecf7); +} + +.form { + display: flex; + flex-direction: column; + align-items: center; + background: #fff; + border: none; + border-radius: 12px; + box-shadow: + 0 2px 12px #1a3a6e1a, + 0 1px 4px #0000000f; + gap: 20px; + padding: 36px 32px 28px; + + h3 { + margin: 0 0 4px; + font-weight: 600; + color: #1a3a6e; + } +} + +.button { + min-height: 48px; + min-width: 140px; + border-radius: 8px; + font-weight: 500; + letter-spacing: 0.02em; +} + +.field { + width: 400px; +} + +.checkbox-container { + display: flex; + align-items: center; + justify-content: flex-start; +} + +.progress { + padding-top: 5px; + width: 300px; + height: 2em; + text-align: center; + font-size: small; + color: #585f71; +} diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts new file mode 100644 index 00000000..d485ac42 --- /dev/null +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -0,0 +1,131 @@ +import { Component, inject, OnDestroy, signal, DestroyRef } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Router, RouterLink } from '@angular/router'; +import { + FormBuilder, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatIconModule } from '@angular/material/icon'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { CredentialService } from '../../shared/services/credential.service'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { Subscription, map, switchMap, debounceTime, distinctUntilChanged, catchError,of} from 'rxjs'; +import { MatAutocompleteModule, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; +import { InstitutionsService } from '../../api'; +@Component({ + selector: 'app-register', + standalone: true, + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatIconModule, + MatCheckboxModule, + RouterLink, + MatSnackBarModule, + MatAutocompleteModule, + ], + templateUrl: './app-register.component.html', + styleUrl: './app-register.component.scss', +}) +export class AppRegisterComponent implements OnDestroy { + private readonly fb = inject(FormBuilder); + protected readonly credentialService = inject(CredentialService); + private readonly router = inject(Router); + private readonly snackBar = inject(MatSnackBar); + private readonly destroyRef = inject(DestroyRef); + private subscription?: Subscription; + private institutionsService = inject(InstitutionsService) + registerForm: FormGroup = this.fb.group({ + username: ['', [Validators.required, Validators.minLength(4)]], + email: ['', [Validators.required, Validators.email]], + password: ['', [Validators.required, Validators.minLength(8)]], + institution: ['', [Validators.required]], + superadmin: [false], + }); + readonly institutionOptions = signal([]); + showPassword = false; + + constructor() { + this.setupInstitutionAutocomplete(); + } + + ngOnDestroy(): void { + this.subscription?.unsubscribe(); + } + + submit() { + if (this.registerForm.valid) { + this.credentialService.validating.next(true); + this.registerForm.disable(); + + this.subscription = this.credentialService + .registerAccount(this.registerForm.value) + .subscribe({ + next: () => { + this.credentialService.validating.next(false); + this.snackBar.open( + 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', + 'OK', + { duration: 5000 }, + ); + this.router.navigate(['/login']); + }, + error: (err) => { + this.credentialService.validating.next(false); + this.registerForm.enable(); + const message = + err.error?.message || + 'Fehler bei der Registrierung. Bitte versuche es später erneut.'; + this.snackBar.open(message, 'Schließen', { + panelClass: ['error-snackbar'], + duration: 5000, + }); + }, + }); + } + } + + private setupInstitutionAutocomplete(): void { + this.registerForm.controls['institution'].valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions.set([]); + return of([]); + } + + return this.searchInstitutions(query).pipe( + catchError((ev) => {console.log(ev);return of([])}), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + this.institutionOptions.set(options); + }); + } + + private searchInstitutions(query: string) { + return this.institutionsService + .autocompleteInstitutions(query, undefined, undefined, 10) + .pipe(map((response) => response.results ?? [])); + } + + onInstitutionSelected(event: MatAutocompleteSelectedEvent): void { + const val = event.option.value; + this.registerForm.controls['institution'].setValue(val, { emitEvent: false }); + this.institutionOptions.set([]); + } +} -- 2.56.1 From 3037215506b4fe941d0d2deb5abb367f15114843 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:43:47 +0200 Subject: [PATCH 3/9] added email and organization_name to user credentials --- service/src/data/users.json | 38 +++++++++------- service/src/main/inse/account/model.py | 4 ++ webapp/src/app/api/model/authAccount.ts | 2 + webapp/src/app/api/model/user.ts | 45 +++++++++++++++++++ .../app/shared/services/credential.service.ts | 45 ++++++++++--------- 5 files changed, 96 insertions(+), 38 deletions(-) create mode 100644 webapp/src/app/api/model/user.ts diff --git a/service/src/data/users.json b/service/src/data/users.json index 6d5b0836..f7311478 100644 --- a/service/src/data/users.json +++ b/service/src/data/users.json @@ -1,18 +1,22 @@ { - "users": [ - { - "account": 0, - "organization": 0, - "username": "superadmin", - "password": "superadmin", - "superadmin": true - }, - { - "account": 1, - "organization": 1, - "username": "user", - "password": "user", - "superadmin": false - } - ] -} + "users": [ + { + "username": "superadmin", + "password": "superadmin", + "email": "some_email@uni-due.de", + "account": 0, + "organization": 0, + "organization_name": "University of Duisburg-Essen", + "superadmin": true + }, + { + "username": "user", + "password": "user", + "email": "user_email@uni-due.de", + "account": 1, + "organization": 1, + "organization_name": "University of Duisburg-Essen", + "superadmin": false + } + ] +} \ No newline at end of file diff --git a/service/src/main/inse/account/model.py b/service/src/main/inse/account/model.py index dd409091..6a2cca19 100644 --- a/service/src/main/inse/account/model.py +++ b/service/src/main/inse/account/model.py @@ -13,8 +13,10 @@ class User(BaseModel): ''' An entry in the user configuration file. ''' username: str = Field(description="The username of the user.") password: str = Field(description="The password of the user.") + email: str = Field(description="The email of the user.") account: StrictInt = Field(description="The account id of the user.") organization: StrictInt = Field(description="The organization id of the user.") + organization_name: str = Field(description="The organization name of the user.") superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.") @@ -27,6 +29,8 @@ class AuthAccount(BaseModel): i: int l: str o: int + e: str + on: str class AuthScope(BaseModel): diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts index 0c76d8dc..770a61f5 100644 --- a/webapp/src/app/api/model/authAccount.ts +++ b/webapp/src/app/api/model/authAccount.ts @@ -13,5 +13,7 @@ export interface AuthAccount { i: number; l: string; o: number; + e: string; + on: string; } diff --git a/webapp/src/app/api/model/user.ts b/webapp/src/app/api/model/user.ts new file mode 100644 index 00000000..def604e1 --- /dev/null +++ b/webapp/src/app/api/model/user.ts @@ -0,0 +1,45 @@ +/** + * 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. + */ + + +/** + * An entry in the user configuration file. + */ +export interface User { + /** + * The username of the user. + */ + username: string; + /** + * The password of the user. + */ + password: string; + /** + * The email of the user. + */ + email: string; + /** + * The account id of the user. + */ + account: number; + /** + * The organization id of the user. + */ + organization: number; + /** + * The organization name of the user. + */ + organization_name: string; + /** + * Indicates whether the user is a superadmin. + */ + superadmin?: boolean; +} + diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 13bf6ad5..040eac7c 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,14 +1,15 @@ -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -//import { BehaviorSubject, Observable, takeWhile } from 'rxjs'; +import { Injectable,inject } from '@angular/core'; import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman import { Observable, of } from 'rxjs'; // review import { BehaviorSubject } from 'rxjs'; //review +import { INSEAccountServiceService, IdentityGrant as ApiIdentityGrant, AccessGrant as ApiAccessGrant } from '../../api'; export interface AuthAccount { i: number; l: string; o: number; + e: string; + on: string; } export interface AuthScope { @@ -47,6 +48,8 @@ interface TimedAccessGrant { providedIn: 'root', }) export class CredentialService { + private accountService = inject(INSEAccountServiceService); + private static readonly KEY_GRANT = 'grant'; public readonly validating = new BehaviorSubject(false); @@ -57,6 +60,8 @@ export class CredentialService { undefined, ); public readonly login = new BehaviorSubject(''); + public readonly email = new BehaviorSubject(''); + public readonly organizationName = new BehaviorSubject(''); private readonly identityToken = new BehaviorSubject< TimedIdentityGrant | undefined @@ -67,17 +72,21 @@ export class CredentialService { private request = 0; - constructor(private http: HttpClient) { + constructor() { this.accessToken.subscribe((token) => { if (token) { const r = token.grant.scope.r as string[]; this.superadmin.next(r.includes('SUPER_ADMIN')); this.universityadmin.next(r.includes('UNI_ADMIN')); this.login.next(token.grant.scope.a?.l ?? ''); + this.email.next(token.grant.scope.a?.e ?? ''); + this.organizationName.next(token.grant.scope.a?.on ?? ''); } else { this.superadmin.next(false); this.universityadmin.next(false); this.login.next(''); + this.email.next(''); + this.organizationName.next(''); } }); const data = localStorage.getItem(CredentialService.KEY_GRANT); @@ -104,15 +113,12 @@ export class CredentialService { body.set('username', login); body.set('password', password); - this.http - .post('/inse-account/auth/id', body.toString(), { - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - }) + this.accountService.getIdentityGrant(login,password) .subscribe({ next: (result) => { if (this.request != request) return; - const token = { - grant: result, + const token: TimedIdentityGrant = { + grant: result as any as IdentityGrant, expiration: result.expires_in * 1000 + now, }; this.identityToken.next(token); @@ -137,20 +143,12 @@ export class CredentialService { const uid = identityToken.grant.scope.a!.i; const org = identityToken.grant.scope.a!.o; - const body = new URLSearchParams(); - body.set('secret', identityToken.grant.access_token); - body.set('account', uid.toString()); - body.set('organization', org.toString()); - - this.http - .post('/inse-account/auth/access', body.toString(), { - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - }) + this.accountService.getAccessGrant(identityToken.grant.access_token, uid, org) .subscribe({ next: (result) => { if (this.request != request) return; - const token = { - grant: result, + const token: TimedAccessGrant = { + grant: result as any as AccessGrant, expiration: result.expires_in * 1000 + now, }; this.accessToken.next(token); @@ -180,6 +178,11 @@ export class CredentialService { this.identityToken.next(undefined); this.accessToken.next(undefined); this.validating.next(false); + + } + + public registerAccount(data: any): Observable { + return this.accountService.createUser(data) } //review: arman (generated fix) -- 2.56.1 From a34119b22cd4c9c4f98805c19cc0907a5b54a176 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:45:46 +0200 Subject: [PATCH 4/9] fixed wrong endpoint recognition in institute autocompletion --- service/src/main/inse/institutions/service.py | 47 ++++++++++--------- .../src/app/api/api/institutions.service.ts | 12 ++--- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py index dd13b718..16c7d676 100644 --- a/service/src/main/inse/institutions/service.py +++ b/service/src/main/inse/institutions/service.py @@ -18,7 +18,7 @@ from . import logic from inse.institutions.institutions_search_client import InstitutionsSearchClient -router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS]) +router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS]) @lru_cache @@ -35,28 +35,6 @@ def get_institutions_search_client() -> InstitutionsSearchClient: ) -@router.get( - "/{id}", - summary="Returns a single institution by ID.", - description="Returns a single institution by its OpenAlex ID.", - operation_id="getInstitutionById", - responses={ - status.HTTP_200_OK: { - "description": "Successful Response", - "model": Institution, - }, - status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - }, -) -async def get_institution( - id: str, - client: Annotated[ - InstitutionsSearchClient, Depends(get_institutions_search_client) - ], -) -> Institution: - return await logic.get_institution_by_id(raw_institution_id=id, client=client) - - @router.get( "/autocomplete", operation_id="autocompleteInstitutions", @@ -155,3 +133,26 @@ async def list_institutions( sample=sample, select=select, ) + + +@router.get( + "/{id}", + summary="Returns a single institution by ID.", + description="Returns a single institution by its OpenAlex ID.", + operation_id="getInstitutionById", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": Institution, + }, + status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, + }, +) +async def get_institution( + id: str, + client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], +) -> Institution: + return await logic.get_institution_by_id(raw_institution_id=id, client=client) + diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index 7a956eca..89bf1fd5 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -43,7 +43,7 @@ export class InstitutionsService extends BaseService { /** * Returns institution options for autocomplete inputs. - * @endpoint get /api/institutions/autocomplete + * @endpoint get /api/inse-service/institutions/autocomplete * @param query Institution search text, for example \'Duisburg Essen\'. * @param countryCode Optional ISO country code filter. * @param type Optional institution type filter. @@ -94,7 +94,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions/autocomplete`; + let localVarPath = `/api/inse-service/institutions/autocomplete`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -113,7 +113,7 @@ export class InstitutionsService extends BaseService { /** * Returns a single institution by ID. * Returns a single institution by its OpenAlex ID. - * @endpoint get /api/institutions/{id} + * @endpoint get /api/inse-service/institutions/{id} * @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. @@ -151,7 +151,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -168,7 +168,7 @@ export class InstitutionsService extends BaseService { /** * Returns a list of OpenAlex institutions. - * @endpoint get /api/institutions + * @endpoint get /api/inse-service/institutions * @param search Full-text search, for example \'Duisburg Essen\'. * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. * @param sort Sort field, for example \'works_count:desc\'. @@ -231,7 +231,7 @@ export class InstitutionsService extends BaseService { } } - let localVarPath = `/api/institutions`; + let localVarPath = `/api/inse-service/institutions`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { -- 2.56.1 From bd9e38c6cfcf89f5a2c75b6f2201b0dd48119c2b Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:50:07 +0200 Subject: [PATCH 5/9] fix(auth): adjust interceptor bypass rules for auth and autocomplete endpoints --- .../app/shared/interceptors/authentication.interceptor.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 788ed84a..ac649afd 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -5,8 +5,11 @@ import { switchMap, throwError } from 'rxjs'; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { if ( - req.method == 'POST' && - (req.url.endsWith('/auth/id') || req.url.endsWith('/auth/access')) + (req.method == 'POST' && + (req.url.endsWith('/auth/id') || + req.url.endsWith('/auth/access') || + req.url.endsWith('/inse-account/create'))) || + req.url.endsWith('/institutions/autocomplete') ) { return next(req); } else { -- 2.56.1 From 60ba32e5636e8ec87d8ac585db8edf32e1036e6f Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 01:50:29 +0200 Subject: [PATCH 6/9] minor layout fixes --- .../ui/app-layout/app-layout.component.html | 78 ++++++++++--------- .../ui/app-layout/app-layout.component.scss | 32 ++++++-- .../app-searchbar.component.scss | 2 +- 3 files changed, 70 insertions(+), 42 deletions(-) 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 1c3a8d9b..6de5f1f4 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 @@ -15,45 +15,51 @@ } - -
- @if ( - mediaQuery.matches && (credentialService.authenticated | async) - ) { - + } + - } - -
- -
- -
-
+
+ +
+ +
+ + }
- @if (resolverState.isResolvingFromOutside('/persons')) { - - } @else if (resolverState.isResolvingFromOutside('/person/')) { - - } @else { - - } +
+ @if (resolverState.isResolvingFromOutside('/persons')) { + + } @else if (resolverState.isResolvingFromOutside('/person/')) { + + } @else { + + } +
+ +
+ +
diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 8311f123..6556c59f 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -18,7 +18,10 @@ } .content-shell { - min-height: 100%; + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; background: var(--sg-background); } @@ -34,10 +37,9 @@ mat-toolbar.main { gap: 24px; height: 76px; padding: 0 32px; - background: rgba(255, 255, 255, 0.92); + background: var(--sg-surface-soft); border-bottom: 1px solid var(--sg-border); color: var(--sg-text); - backdrop-filter: blur(16px); box-shadow: none; } @@ -82,10 +84,30 @@ mat-toolbar.main { } .content { - min-height: calc(100svh - 76px); + display: flex; + flex-direction: column; + flex: 1; + overflow-y: auto; background: var(--sg-background); } +.main-content-body { + flex: 1; +} + +.footer-container { + flex-shrink: 0; + padding: 12px 32px; + background: var(--sg-surface-soft); + border-top: 1px solid var(--sg-border); +} + +.footer { + font-size: 12px; + color: var(--sg-text-muted); + text-align: center; +} + @media (max-width: 900px) { mat-toolbar.main { grid-template-columns: auto 1fr auto; @@ -115,7 +137,7 @@ mat-toolbar.main { } .content { - min-height: calc(100svh - 124px); + min-height: 0; } } .search-wrapper { diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss index 5572787d..2087eb9c 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss @@ -5,7 +5,7 @@ height: 44px; align-self: center; padding: 0 18px; - background: var(--sg-surface-muted); + background: white; border: 1px solid var(--sg-border); border-radius: var(--sg-radius-sm); color: var(--sg-text-soft); -- 2.56.1 From 8515a01ff4aaa16653122161750b00355eaafb1a Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 19:04:44 +0200 Subject: [PATCH 7/9] fixed institutuin autocompletion logic, used existing elastic wrapper for queries --- .../institutions_search_client.py | 223 ++++++++++++------ service/src/main/inse/institutions/logic.py | 40 ++-- service/src/main/inse/institutions/service.py | 15 +- .../src/main/inse/institutions/test_logic.py | 58 ----- .../main/inse/models/openalex/institution.py | 11 +- 5 files changed, 171 insertions(+), 176 deletions(-) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 23a736af..dd895930 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -1,79 +1,73 @@ import logging from typing import List, Set -import httpx - from inse.models.openalex.institution import Institution from inse.exceptions import NotFoundException +from inse.integrations import elasticsearch logger = logging.getLogger(__name__) class InstitutionsSearchClient: - def __init__( - self, - base_url: str, - api_key: str, - ): - self.base_url = base_url - self.api_key = api_key - self.headers = { - "Content-Type": "application/json", - "Authorization": f"ApiKey {self.api_key}", - } + def __init__(self): + """ + Initializes the client. Credentials and URLs are handled by the + centralized elasticsearch integration. + """ + pass async def get_institution_by_id(self, raw_institution_id: str) -> Institution: + """ + Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster. + """ query = { - "query": { - "match": { - "id": f"https://openalex.org/{raw_institution_id.upper()}", - } - }, - "size": 1, + "match": { + "id": f"https://openalex.org/{raw_institution_id.upper()}", + } } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=1 + ) + + hits = res.get("hits", {}).get("hits", []) + if not hits: + raise NotFoundException(f"Institution with ID '{raw_institution_id}' not found.") + authors = await self.get_authors_by_institution_id(raw_institution_id) logger.debug( "Retrieved authors for institution_id=%s: %s", raw_institution_id, authors ) - - async with httpx.AsyncClient() as client: - response = await client.post( - f"{self.base_url}/openalex-institutions/_search", - json=query, - headers=self.headers, - ) - response.raise_for_status() - hits = response.json().get("hits", {}).get("hits", []) - if not hits: - raise NotFoundException( - f"Institution with ID '{raw_institution_id}' not found." - ) - - return Institution.from_dict(hits[0]["_source"]) + + return Institution.from_dict(hits[0]["_source"]) async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]: + """ + Fetches authors associated with an institution. + Note: This query is specifically looking for current affiliations (2026). + """ query = { - "query": { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "must": [ - { - "term": { - "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" - } - }, - { - "range": { - "affiliations.years": {"gte": 2026, "lte": 2026} - } - }, - ] - } - }, - } + "nested": { + "path": "affiliations", + "query": { + "bool": { + "must": [ + { + "term": { + "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" + } + }, + { + "range": { + "affiliations.years": {"gte": 2026, "lte": 2026} + } + }, + ] + } + }, } } logger.debug( @@ -81,30 +75,103 @@ class InstitutionsSearchClient: raw_institution_id, query, ) - async with httpx.AsyncClient() as client: - response = await client.post( - "https://project.nes.uni-due.de/elastic/openalex-authors/_search", - json=query, - headers=self.headers, - ) - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - logger.exception( - "Error fetching authors for institution_id=%s: %s, response content: %s", - raw_institution_id, - str(e), - response.text, - ) - return [] - hits = response.json().get("hits", {}).get("hits", []) - authors = set() - for hit in hits: - authors.update( - auth["author"]["display_name"] - for auth in hit["_source"].get("authorships", []) - ) - return list(authors) + + res = elasticsearch.search(index="openalex-authors", query=query) + hits = res.get("hits", {}).get("hits", []) + + # Extracting display_name directly from the author document source + authors = {hit["_source"].get("display_name") for hit in hits if hit["_source"].get("display_name")} + return list(authors) + async def search_institutions( + self, + query_text: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + ) -> list[Institution]: + """ + Autocomplete search for institutions using multi_match on search_as_you_type fields. + Falls back to fuzzy match for typo tolerance on longer queries. + """ + must = [] + + if query_text: + stripped = query_text.strip() + + must.append({ + "bool": { + "should": [ + # Fast prefix matching via search_as_you_type shingles + { + "multi_match": { + "query": stripped, + "type": "bool_prefix", + "fields": [ + "display_name.search", + "display_name.search._2gram", + "display_name.search._3gram", + "display_name_alternatives.search", + "display_name_alternatives.search._2gram", + ], + "boost": 2, + } + }, + # Exact acronym match — high confidence signal + { + "term": { + "display_name_acronyms.keyword": { + "value": stripped.upper(), + "boost": 10, + } + } + }, + # Fuzzy fallback for typos (only worth it for longer input) + *( + [{ + "match": { + "display_name": { + "query": stripped, + "fuzziness": "AUTO", + "boost": 1, + } + } + }] + if len(stripped) >= 4 else [] + ), + ], + "minimum_should_match": 1, + } + }) + + filter_queries = [] + + if country_code: + filter_queries.append({"term": {"country_code": country_code.upper()}}) + + if institution_type: + filter_queries.append({"term": {"type": institution_type}}) + + query = { + "bool": { + "must": must, + "filter": filter_queries, + } + } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=limit, + # Blend relevance score with works_count popularity signal + sort=[ + {"works_count": {"order": "desc"}}, + ], + source=["id", "display_name", "country_code", "type", "works_count", "cited_by_count", "geo"], + ) + + hits = res.get("hits", {}).get("hits", []) + + return [Institution.from_dict(hit["_source"]) for hit in hits] async def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index a4f834ee..7562672e 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -114,34 +114,29 @@ async def autocomplete_institutions( country_code: str | None = None, institution_type: str | None = None, limit: int = 10, - client: OpenAlexInstitutionsClient | None = None, + client: InstitutionsSearchClient, ) -> AutocompleteResponse: - filters = [] - if country_code: - filters.append(f"country_code:{country_code}") - if institution_type: - filters.append(f"type:{institution_type}") - - response = await list_institutions( - search=query, - filter=",".join(filters) if filters else None, - sort="works_count:desc", - per_page=limit, - page=1, - select=("id,ror,display_name,country_code,type,works_count,cited_by_count,geo"), - client=client, + """ + Returns institution options for autocomplete inputs using the local + Elasticsearch cluster via the provided client. + """ + institutions = await client.search_institutions( + query_text=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, ) results = [] - for institution in response.results or []: + for institution in institutions: if not institution.id or not institution.display_name: continue hint_parts = [] - if institution.geo: - if institution.geo.city: + if hasattr(institution, "geo") and institution.geo: + if hasattr(institution.geo, "city") and institution.geo.city: hint_parts.append(institution.geo.city) - if institution.geo.country: + if hasattr(institution.geo, "country") and institution.geo.country: hint_parts.append(institution.geo.country) elif institution.country_code: hint_parts.append(institution.country_code) @@ -161,12 +156,7 @@ async def autocomplete_institutions( ) return AutocompleteResponse( - meta=AutocompleteResponseMeta( - count=response.meta.count if response.meta else len(results), - db_response_time_ms=( - response.meta.db_response_time_ms if response.meta else None - ), - ), + meta=AutocompleteResponseMeta(count=len(results)), results=results, ) diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py index 16c7d676..5c08bbdf 100644 --- a/service/src/main/inse/institutions/service.py +++ b/service/src/main/inse/institutions/service.py @@ -23,17 +23,7 @@ router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTI @lru_cache def get_institutions_search_client() -> InstitutionsSearchClient: - settings = get_settings() - if not settings.elasticsearch_url: - raise ValueError("Elasticsearch URL is missing in settings.") - if not settings.elasticsearch_api_key: - raise ValueError("Elasticsearch API key is missing in settings.") - - return InstitutionsSearchClient( - api_key=settings.elasticsearch_api_key, - base_url=settings.elasticsearch_url, - ) - + return InstitutionsSearchClient() @router.get( "/autocomplete", @@ -62,12 +52,14 @@ async def autocomplete_institutions( int, Query(description="Maximum number of autocomplete options.", ge=1, le=25), ] = 10, + client: Annotated[InstitutionsSearchClient, Depends(get_institutions_search_client)] = None, ): return await logic.autocomplete_institutions( query=query, country_code=country_code, institution_type=institution_type, limit=limit, + client=client, ) @@ -155,4 +147,3 @@ async def get_institution( ], ) -> Institution: return await logic.get_institution_by_id(raw_institution_id=id, client=client) - diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index e079ff8e..bebf52c0 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -176,61 +176,3 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" - -@pytest.mark.anyio -async def test_autocomplete_institutions_returns_frontend_options(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.url.params["search"] == "Duisburg Essen" - assert request.url.params["filter"] == "country_code:DE,type:education" - assert request.url.params["sort"] == "works_count:desc" - assert request.url.params["per_page"] == "5" - assert request.url.params["select"] == ( - "id,ror,display_name,country_code,type,works_count," - "cited_by_count,geo" - ) - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "db_response_time_ms": 12}, - "results": [ - { - "id": "https://openalex.org/I123", - "ror": "https://ror.org/04mz5ra38", - "display_name": "University of Duisburg-Essen", - "country_code": "DE", - "type": "education", - "works_count": 123, - "cited_by_count": 456, - "geo": { - "city": "Duisburg", - "country": "Germany", - }, - } - ], - }, - ) - - client = OpenAlexInstitutionsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await logic.autocomplete_institutions( - query="Duisburg Essen", - country_code="DE", - institution_type="education", - limit=5, - client=client, - ) - - assert result.meta.count == 1 - assert result.meta.db_response_time_ms == 12 - assert len(result.results) == 1 - option = result.results[0] - assert option.id == "https://openalex.org/I123" - assert option.display_name == "University of Duisburg-Essen" - assert option.hint == "Duisburg · Germany · education" - assert option.works_count == 123 - assert option.cited_by_count == 456 - assert option.entity_type == "institution" - assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index a81ae678..6121af94 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -55,13 +55,20 @@ class Institution(BaseModel): updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).") __properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"] + @field_validator('created_date', mode='before') + @classmethod + def normalize_created_date(cls, v: Any) -> Any: + if isinstance(v, str) and len(v) > 10: + return v[:10] + return v + @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): + if value not in set(['education','funder', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") return value @@ -154,5 +161,3 @@ class Institution(BaseModel): "updated_date": obj.get("updated_date") }) return _obj - - -- 2.56.1 From e52204a90da97ff931515ded3f1ef2a246164133 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 19:05:02 +0200 Subject: [PATCH 8/9] fixed routing logic --- webapp/src/app/app.routes.ts | 4 +-- .../app-register/app-register.component.ts | 25 ++++++++++++++++--- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 9c674dc3..01ca7ee8 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -8,7 +8,6 @@ import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectsResolver } from './resolvers/bund-projects.resolver'; import { euProjectsResolver } from './resolvers/eu-projects.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; - export const routes: Routes = [ { path: 'login', @@ -17,7 +16,7 @@ export const routes: Routes = [ (mod) => mod.AppLoginComponent, ), }, - { + { path: 'register', loadComponent: () => import('./modules/app-register/app-register.component').then( @@ -236,5 +235,6 @@ export const routes: Routes = [ routeMessage: 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', }, + canActivate: [userGuard], }, ]; 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 d485ac42..70b2f073 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -1,4 +1,4 @@ -import { Component, inject, OnDestroy, signal, DestroyRef } from '@angular/core'; +import { Component, inject, OnDestroy, signal, DestroyRef, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Router, RouterLink } from '@angular/router'; @@ -36,7 +36,7 @@ import { InstitutionsService } from '../../api'; templateUrl: './app-register.component.html', styleUrl: './app-register.component.scss', }) -export class AppRegisterComponent implements OnDestroy { +export class AppRegisterComponent implements OnDestroy, OnInit { private readonly fb = inject(FormBuilder); protected readonly credentialService = inject(CredentialService); private readonly router = inject(Router); @@ -57,11 +57,30 @@ export class AppRegisterComponent implements OnDestroy { constructor() { 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.authenticated.value) { + this.router.navigate(['/dashboard']); + } + } submit() { if (this.registerForm.valid) { this.credentialService.validating.next(true); -- 2.56.1 From 9de6d4408d62fd53c1e44f12e950cde889f0ba55 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 19:12:12 +0200 Subject: [PATCH 9/9] undid openapi config push --- webapp/openapi-generator-ignore | 3 --- webapp/openapitools.json | 17 +++++++---------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/webapp/openapi-generator-ignore b/webapp/openapi-generator-ignore index 844db49d..44ab4450 100644 --- a/webapp/openapi-generator-ignore +++ b/webapp/openapi-generator-ignore @@ -6,6 +6,3 @@ git_push.sh package.json ng-package.json tsconfig.json -# Ignore generated service interfaces -src/app/api/**/*Interface.ts -src/app/api/**/*.interface.ts \ No newline at end of file diff --git a/webapp/openapitools.json b/webapp/openapitools.json index 513cb883..7af6e36f 100644 --- a/webapp/openapitools.json +++ b/webapp/openapitools.json @@ -9,16 +9,13 @@ "output": "src/app/api", "ignoreFileOverride": "openapi-generator-ignore", "additionalProperties": { - "ngVersion": "21.2.14", - "providedInRoot": true, - "serviceSuffix": "Service", - "withInterfaces": false, - "generateModelDocumentation": false, - "modelPropertyNaming": "original", - "enumPropertyNaming": "original", - "fileNaming": "camelCase", - "apiModulePrefix": "" -} + "ngVersion": "21.2.14", + "providedInRoot": true, + "serviceSuffix": "Service", + "withInterfaces": true, + "enumPropertyNaming": "original", + "fileNaming": "kebab-case" + } } } } -- 2.56.1