added users register component

This commit is contained in:
2026-06-15 01:41:37 +02:00
parent a2ed442dcc
commit 28b8fff4dd
12 changed files with 479 additions and 17 deletions
+31
View File
@@ -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
+45 -2
View File
@@ -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
@@ -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<User>;
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<User>>;
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<User>>;
public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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<User>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyCreateUser,
responseType: <any>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<AccessGrant>;
public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessGrant>>;
public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessGrant>>;
public getAccessGrantInseAccountAuthAccessPost(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessGrant>;
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessGrant>>;
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessGrant>>;
public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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<IdentityGrant>;
public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<IdentityGrant>>;
public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<IdentityGrant>>;
public getIdentityGrantInseAccountAuthIdPost(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<IdentityGrant>;
public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<IdentityGrant>>;
public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<IdentityGrant>>;
public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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;
@@ -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;
}
+2
View File
@@ -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';
+7
View File
@@ -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',
@@ -42,6 +42,12 @@
[disabled]="!loginForm.valid || (credentialService.validating | async)">
Anmelden
</button>
<div class="field" style="text-align: center; margin-top: -10px;">
<button mat-button type="button" routerLink="/register">
Noch kein Konto? <b>Registrieren</b>
</button>
</div>
</form>
<p class="progress">
@if (credentialService.validating | async) {
@@ -37,7 +37,7 @@
}
.field {
width: 300px;
width: 400px;
}
.progress {
@@ -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',
@@ -0,0 +1,97 @@
<div class="container">
<form class="form" [formGroup]="registerForm">
<h3>Konto erstellen</h3>
<p class="field">
Bitte gib Deine Daten ein, um Dich zu registrieren.
</p>
<mat-form-field class="field">
<mat-label>Benutzername</mat-label>
<input matInput formControlName="username" />
@if (registerForm.controls['username'].hasError('required')) {
<mat-error>Fehler: <b>Benutzername</b> erforderlich.</mat-error>
} @else if (registerForm.controls['username'].hasError('minlength')) {
<mat-error>Fehler: <b>Benutzername</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>E-Mail</mat-label>
<input matInput type="email" formControlName="email" />
@if (registerForm.controls['email'].hasError('required')) {
<mat-error>Fehler: <b>E-Mail</b> erforderlich.</mat-error>
} @else if (registerForm.controls['email'].hasError('email')) {
<mat-error>Fehler: Ungültige <b>E-Mail</b> Adresse.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Passwort</mat-label>
<input
matInput
[type]="showPassword ? 'text' : 'password'"
formControlName="password" />
@if (showPassword) {
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
} @else {
<mat-icon matSuffix (click)="showPassword = true"
>visibility_off</mat-icon
>
}
@if (registerForm.controls['password'].hasError('required')) {
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
} @else if (registerForm.controls['password'].hasError('minlength')) {
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
}
</mat-form-field>
<mat-form-field class="field">
<mat-label>Institution</mat-label>
<mat-icon matPrefix>apartment</mat-icon>
<input
type="text"
matInput
formControlName="institution"
[matAutocomplete]="auto"
placeholder="Institution suchen..."
/>
@if (registerForm.controls['institution'].hasError('required')) {
<mat-error>Fehler: <b>Institution</b> erforderlich.</mat-error>
}
<mat-autocomplete
#auto="matAutocomplete"
(optionSelected)="onInstitutionSelected($event)">
@for (institution of institutionOptions(); track institution.id) {
<mat-option [value]="institution.display_name" style="font-size: 16px;">
<div><span>{{ institution.display_name }}</span></div>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
}
</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<div class="field checkbox-container">
<mat-checkbox formControlName="superadmin">Superadmin Rechte</mat-checkbox>
</div>
<button
mat-raised-button
class="button"
(click)="submit()"
[disabled]="!registerForm.valid || (credentialService.validating | async)">
Registrieren
</button>
<div class="field" style="text-align: center; margin-top: -10px;">
<button mat-button type="button" routerLink="/login">
Bereits ein Konto? <b>Anmelden</b>
</button>
</div>
</form>
<p class="progress">
<!-- Statusanzeige analog zum Login-Formular -->
</p>
</div>
@@ -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;
}
@@ -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<any[]>([]);
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([]);
}
}