diff --git a/service/src/data/users.json b/service/src/data/users.json deleted file mode 100644 index 450db22c..00000000 --- a/service/src/data/users.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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 - } - ] -} diff --git a/service/src/main/inse/account/__init__.py b/service/src/main/inse/account/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/service/src/main/inse/account/logic.py b/service/src/main/inse/account/logic.py deleted file mode 100644 index b443254c..00000000 --- a/service/src/main/inse/account/logic.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module contains the validation logic for - user names and passwords. -""" -import typing -import logging -from . import model - -logger = logging.getLogger(__name__) - -def _get_users() -> typing.List[model.User]: - ''' Returns the list of users from the user configuration file. ''' - try: - with open('../data/users.json') as file: - config = model.UserFile.model_validate_json(file.read()) - return config.users - except Exception as e: - logger.error('Could not read user configuration file.', exc_info=e) - return [] - -def get_user(username: str) -> typing.Optional[model.User]: - ''' Returns the user with the given username. ''' - for user in _get_users(): - if user.username == username: - return user - return None - -def validate_user(username: str, password: str) -> typing.Optional[model.User]: - ''' Validates the user with the given username and password. ''' - user = get_user(username) - 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/model.py b/service/src/main/inse/account/model.py deleted file mode 100644 index 6a2cca19..00000000 --- a/service/src/main/inse/account/model.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Data models for the standalone account sub-app. -""" -from pydantic import BaseModel -from pydantic import Field -from pydantic import StrictInt -from typing import List, Optional - - -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.") - - -class UserFile(BaseModel): - ''' The data model for the file containing the user configuration. ''' - users: List[User] = Field(default=[], description="The list of users.") - - -class AuthAccount(BaseModel): - i: int - l: str - o: int - e: str - on: str - - -class AuthScope(BaseModel): - t: str - a: AuthAccount - d: Optional[int] = None - r: List[str] = [] - - -class IdentityGrant(BaseModel): - token_type: str - access_token: str - expires_in: int - scope: AuthScope - - -class AccessGrant(BaseModel): - token_type: str - access_token: str - expires_in: int - scope: AuthScope - refresh_token: str - diff --git a/service/src/main/inse/account/security.py b/service/src/main/inse/account/security.py deleted file mode 100644 index 44fdb5dd..00000000 --- a/service/src/main/inse/account/security.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module defines the security-related code. -""" -from typing import Optional -from typing import Dict -from typing import Literal -import jwt -import time -import logging -from .. import config -from .. import security -from . import model - -logger = logging.getLogger(__name__) - -def principal(id_token: str) -> Optional[security.Principal]: - ''' Extracts the principal from the id token. ''' - return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH']) - -def id_token(user: model.User, exp: int) -> str: - ''' Creates a new identity token for the specified user. ''' - return _encode(_payload(user, 'ID', exp)) - -def access_token(user: model.User, exp: int) -> str: - ''' Creates a new access token for the specified user. ''' - return _encode(_payload(user, 'ACCESS', exp)) - -def refresh_token(user: model.User, exp: int) -> str: - ''' Creates a new refresh token for the specified user. ''' - return _encode(_payload(user, 'REFRESH', exp)) - -def _encode(payload: Dict[str, any]) -> str: - ''' Creates a valid web token that encodes the contents with the symmetric key. ''' - headers = { - "kid" : "sym", - } - return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers) - -def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str: - ''' Creates the payload of the token for the specified user and token type. ''' - now = int(time.time()) - roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ] - payload = { - "iss" : "my-app", - "exp" : now + exp, - "iat" : now, - "nbf" : now, - "inse" : { - "t" : type, - "a" : { - "i" : user.account, - "l" : user.username, - "o" : user.organization - }, - "d" : None, - "r" : roles if type == 'ACCESS' else [] - } - } - return payload - diff --git a/service/src/main/inse/account/service.py b/service/src/main/inse/account/service.py deleted file mode 100644 index ae99cd7b..00000000 --- a/service/src/main/inse/account/service.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -Standalone account service that provides identity and access -token endpoints for authentication. -""" - -import logging -import fastapi -import typing -from . import logic -from . import model -from . import security -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_403_FORBIDDEN -from starlette.status import HTTP_200_OK -from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR - -logger = logging.getLogger(__name__) - -router = fastapi.APIRouter( - prefix="/inse-account", - tags=["INSE Account Service"], - responses={404: {"description": "Not found"}}, -) - - -@router.post( - "/auth/id", - operation_id="getIdentityGrant", - responses={ - HTTP_200_OK: {"model": model.IdentityGrant}, - HTTP_400_BAD_REQUEST: { - "model": None, - "description": "Invalid request parameters.", - }, - HTTP_403_FORBIDDEN: { - "model": None, - "description": "Account login not successful.", - }, - HTTP_500_INTERNAL_SERVER_ERROR: { - "model": None, - "description": "Token generation failed.", - }, - }, -) -async def get_identity_grant( - username: typing.Annotated[str, fastapi.Form()], - password: typing.Annotated[str, fastapi.Form()], -): - user = logic.validate_user(username, password) - if user is None: - logger.info("Invalid login attempt (%s).", username) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - try: - exp = 12 * 60 * 60 - token = security.id_token(user, exp=exp) - account = model.AuthAccount( - 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( - token_type="bearer", access_token=token, expires_in=exp, scope=scope - ) - logger.info("Identity token generated (%s).", username) - return grant - except Exception as e: - logger.error("Token generation failed (%s).", username, exc_info=e) - raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR) - - -@router.post( - "/auth/access", - operation_id="getAccessGrant", - responses={ - HTTP_200_OK: {"model": model.AccessGrant}, - HTTP_400_BAD_REQUEST: { - "model": None, - "description": "Invalid request parameters.", - }, - HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."}, - HTTP_500_INTERNAL_SERVER_ERROR: { - "model": None, - "description": "Token generation failed.", - }, - }, -) -async def get_access_grant( - secret: typing.Annotated[str, fastapi.Form()], - account: typing.Annotated[int, fastapi.Form()], - organization: typing.Annotated[int, fastapi.Form()], -): - principal = security.principal(secret) - if principal is None: - logger.info("Invalid access attempt without principal (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST) - user = logic.get_user(principal.account.login) - if user is None: - logger.info("Invalid access attempt without user (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - if user.organization != organization or user.account != account: - logger.info("Invalid personation attempt (%s).", account) - raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN) - try: - exp = 10 * 60 - 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, - e=user.email, - on=user.organization_name, - ) - scope = model.AuthScope( - t="ACCESS", - a=auth_account, - d=None, - r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"], - ) - grant = model.AccessGrant( - token_type="bearer", - access_token=token, - expires_in=exp, - scope=scope, - refresh_token=refresh, - ) - logger.info("Access token generated (%s).", user.username) - return 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/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index c772012f..d8da0821 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,9 +1,9 @@ import datetime import hashlib import json +import logging import secrets import uuid -import logging from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from typing import Annotated, Any, Dict, Literal, Optional @@ -25,7 +25,7 @@ from inse.auth.model import ( ) from inse.config import get_settings from inse.database import get_session -from sqlmodel import Session, select, func +from sqlmodel import Session, func, select ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -142,6 +142,7 @@ def _verify_password(password: str, password_hash: str) -> bool: except (VerifyMismatchError, VerificationError, InvalidHashError): return False + def request_otk(session: Session, email: str, password: str): """Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid. @@ -507,11 +508,12 @@ def _is_valid_impersonation( ]: return True # Admins can impersonate managers and users within the same organization - if ( - real_account.role == UserRole.MANAGER - and effective_account.role == UserRole.USER - ): - return True # Managers can impersonate users within the same organization + # if ( + # real_account.role == UserRole.MANAGER + # and effective_account.role == UserRole.USER + # ): + # return True # Managers can impersonate users within the same organization + # # They can't tho? return False @@ -547,7 +549,13 @@ def get_access_token( detail="Real account ID does not match ID token", ) - if effective_account_id: + # The new frontend explicitly sends the real account as the effective account. + # That is self-access, not impersonation; otherwise normal login fails for users + # because they do not have impersonation permissions. + 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, @@ -557,9 +565,6 @@ def get_access_token( status_code=status.HTTP_403_FORBIDDEN, detail="Impersonation not allowed", ) - else: - # No impersonation, set effective_account_id to real_account_id - effective_account_id = real_account_id role = _get_account_role(session=session, account_id=effective_account_id) epoch = _get_account_epoch(account_id=effective_account_id, session=session) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 71d27db6..443107d7 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -36,7 +36,6 @@ from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from . import config -from .account.service import router as account_router from .service import router as service_router @@ -73,7 +72,6 @@ app.include_router(persons_service_router) app.include_router(funders_service_router) app.include_router(news_service_router) app.include_router(company_connections_router) -app.include_router(account_router) app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) diff --git a/service/src/main/inse/security.py b/service/src/main/inse/security.py deleted file mode 100644 index d6495cb9..00000000 --- a/service/src/main/inse/security.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -This module defines the security-related code. -""" - -from typing import Optional -from typing import List -from typing import Callable -from typing import Literal -from starlette.status import HTTP_403_FORBIDDEN -from fastapi import Depends -from fastapi.security import HTTPBearer -from fastapi.security import HTTPAuthorizationCredentials -from fastapi import HTTPException -from pydantic import BaseModel -from pydantic import Field -import jwt -import logging -from . import config -from . import database - - -class Account(BaseModel): - id: int = Field(description="The id of the account.") - login: Optional[str] = Field(description="The optional login of the account.") - organization: int = Field(description="The organization id of the account.") - - -class Principal(BaseModel): - account: Account = Field(description="The account of the principal.") - delegate: Optional[Account] = Field( - default=None, description="The optional delegate of the principal." - ) - roles: List[str] = Field(description="The roles of the principal.") - - -logger = logging.getLogger(__name__) - -bearer = HTTPBearer( - bearerFormat="JWT", - scheme_name="bearer", - description="JSON Web Token provided via bearer authorization.", - auto_error=False, -) - - -def principal( - db: database.SessionDep, - credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), -) -> Optional[Principal]: - if config.settings.auth_disabled: - account = Account(id=0, login="AUTH_DISABLED", organization=0) - return Principal(account=account, delegate=None, roles=["SUPER_ADMIN"]) - if credentials is None or credentials.credentials is None: - return None - return _extract_principal( - credentials.credentials, config.settings.auth_secret, "HS256" - ) - - -def _extract_principal( - token: str, - secret_key, - algorithm: Literal["RS256", "HS256"], - token_types: List[Literal["ID", "ACCESS", "REFRESH"]] = ["ACCESS"], -) -> Optional[Principal]: - try: - content = jwt.decode( - token, - secret_key, - verify=True, - issuer="my-app", - algorithms=[algorithm], - options={"require": ["iss", "iat", "nbf", "exp", "inse"]}, - ) - except jwt.exceptions.ExpiredSignatureError as e: - logger.info(f"Received expired token, ignoring content ({e}).") - return None - except Exception as e: - logger.info(f"Received invalid token content, ignoring content ({e}).") - return None - scope = content.get("inse") - if scope is None: - return None - token_type = scope.get("t") - if token_type not in token_types: - logger.info( - f"Received invalid token type, ignoring content (Type was {token_type})" - ) - return None - a = scope.get("a", {}) - account = Account(id=a.get("i", 0), login=a.get("l"), organization=a.get("o", 0)) - delegate = None - d = scope.get("d") - if d is not None: - delegate = Account( - id=d.get("i", 0), login=d.get("l"), organization=d.get("o", 0) - ) - return Principal(account=account, delegate=delegate, roles=scope.get("r", [])) - - -def roles_allowed(roles: List[str] | str) -> Callable[[Optional[Principal]], Principal]: - if isinstance(roles, str): - roles = [roles] - if len(roles) < 1: - raise ValueError("Must specify at least one role in roles_allowed.") - - def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal: - if principal is None: - logger.info("Rejecting call due to missing principal.") - raise HTTPException(status_code=HTTP_403_FORBIDDEN) - for role in roles: - if role in principal.roles: - return principal - logger.info("Rejecting call due to missing roles.") - raise HTTPException(status_code=HTTP_403_FORBIDDEN) - - return verify_roles diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 49ac1868..a2407030 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -7,7 +7,6 @@ api/api.ts api/auth.service.ts api/companyConnections.service.ts api/funding.service.ts -api/iNSEAccountService.service.ts api/iNSEService.service.ts api/institutions.service.ts api/news.service.ts @@ -21,9 +20,6 @@ configuration.ts encoder.ts git_push.sh index.ts -model/accessGrant.ts -model/authAccount.ts -model/authScope.ts model/author.ts model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts @@ -40,7 +36,6 @@ model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts model/bodyChangePassword.ts -model/bodyCreateUser.ts model/bodyGetAccessToken.ts model/bodyLogin.ts model/bodyRequestOtk.ts @@ -76,7 +71,6 @@ model/fundingProjectPage.ts model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts -model/identityGrant.ts model/institution.ts model/institutionFunderSummary.ts model/institutionGeo.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index dda89ae3..f78dee69 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -4,8 +4,6 @@ export * from './companyConnections.service'; import { CompanyConnectionsService } from './companyConnections.service'; export * from './funding.service'; import { FundingService } from './funding.service'; -export * from './iNSEAccountService.service'; -import { INSEAccountServiceService } from './iNSEAccountService.service'; export * from './iNSEService.service'; import { INSEServiceService } from './iNSEService.service'; export * from './institutions.service'; @@ -24,4 +22,17 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; +export const APIS = [ + AuthService, + CompanyConnectionsService, + FundingService, + INSEServiceService, + InstitutionsService, + NewsService, + PatentsService, + PersonNetworkService, + PersonsService, + ProjectsService, + TopicsService, + WorksService, +]; diff --git a/webapp/src/app/api/api/iNSEAccountService.service.ts b/webapp/src/app/api/api/iNSEAccountService.service.ts deleted file mode 100644 index 90181dbd..00000000 --- a/webapp/src/app/api/api/iNSEAccountService.service.ts +++ /dev/null @@ -1,282 +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. - */ -/* 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'; - -// @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'; -import { Configuration } from '../configuration'; -import { BaseService } from '../api.base.service'; - - - -@Injectable({ - providedIn: 'root' -}) -export class INSEAccountServiceService extends BaseService { - - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - 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 - * @param secret - * @param account - * @param organization - * @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 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 getAccessGrant.'); - } - if (account === null || account === undefined) { - 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 getAccessGrant.'); - } - - 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/x-www-form-urlencoded' - ]; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any; }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({encoder: this.encoder}); - } - - if (secret !== undefined) { - localVarFormParams = localVarFormParams.append('secret', secret) as any || localVarFormParams; - } - if (account !== undefined) { - localVarFormParams = localVarFormParams.append('account', account) as any || localVarFormParams; - } - if (organization !== undefined) { - localVarFormParams = localVarFormParams.append('organization', organization) as any || localVarFormParams; - } - - 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/auth/access`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - - /** - * Get Identity Grant - * @endpoint post /inse-account/auth/id - * @param username - * @param password - * @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 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 getIdentityGrant.'); - } - if (password === null || password === undefined) { - throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.'); - } - - 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/x-www-form-urlencoded' - ]; - - const canConsumeForm = this.canConsumeForm(consumes); - - let localVarFormParams: { append(param: string, value: any): any; }; - let localVarUseForm = false; - let localVarConvertFormParamsToString = false; - if (localVarUseForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new HttpParams({encoder: this.encoder}); - } - - if (username !== undefined) { - localVarFormParams = localVarFormParams.append('username', username) as any || localVarFormParams; - } - if (password !== undefined) { - localVarFormParams = localVarFormParams.append('password', password) as any || localVarFormParams; - } - - 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/auth/id`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); - } - -} diff --git a/webapp/src/app/api/model/accessGrant.ts b/webapp/src/app/api/model/accessGrant.ts deleted file mode 100644 index ad1f537a..00000000 --- a/webapp/src/app/api/model/accessGrant.ts +++ /dev/null @@ -1,20 +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 { AuthScope } from './authScope'; - - -export interface AccessGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; - refresh_token: string; -} - diff --git a/webapp/src/app/api/model/authAccount.ts b/webapp/src/app/api/model/authAccount.ts deleted file mode 100644 index 770a61f5..00000000 --- a/webapp/src/app/api/model/authAccount.ts +++ /dev/null @@ -1,19 +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. - */ - - -export interface AuthAccount { - i: number; - l: string; - o: number; - e: string; - on: string; -} - diff --git a/webapp/src/app/api/model/authScope.ts b/webapp/src/app/api/model/authScope.ts deleted file mode 100644 index 65ffa9b5..00000000 --- a/webapp/src/app/api/model/authScope.ts +++ /dev/null @@ -1,19 +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 { AuthAccount } from './authAccount'; - - -export interface AuthScope { - t: string; - a: AuthAccount; - d?: number | null; - r?: Array; -} - diff --git a/webapp/src/app/api/model/bodyCreateUser.ts b/webapp/src/app/api/model/bodyCreateUser.ts deleted file mode 100644 index 76caab3b..00000000 --- a/webapp/src/app/api/model/bodyCreateUser.ts +++ /dev/null @@ -1,19 +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. - */ - - -export interface BodyCreateUser { - username: string; - password: string; - email: string; - institution: string; - superadmin?: boolean; -} - diff --git a/webapp/src/app/api/model/identityGrant.ts b/webapp/src/app/api/model/identityGrant.ts deleted file mode 100644 index 9ec3fe50..00000000 --- a/webapp/src/app/api/model/identityGrant.ts +++ /dev/null @@ -1,19 +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 { AuthScope } from './authScope'; - - -export interface IdentityGrant { - token_type: string; - access_token: string; - expires_in: number; - scope: AuthScope; -} - diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 3690cd69..5680353b 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -1,6 +1,3 @@ -export * from './accessGrant'; -export * from './authAccount'; -export * from './authScope'; export * from './author'; export * from './authorAffiliationsInner'; export * from './authorCountsByYearInner'; @@ -17,7 +14,6 @@ export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; export * from './bodyChangePassword'; -export * from './bodyCreateUser'; export * from './bodyGetAccessToken'; export * from './bodyLogin'; export * from './bodyRequestOtk'; @@ -53,7 +49,6 @@ export * from './fundingProjectPage'; export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; -export * from './identityGrant'; export * from './institution'; export * from './institutionFunderSummary'; export * from './institutionGeo'; @@ -98,7 +93,6 @@ export * from './topicsByYear'; export * from './topicsListResponse'; export * from './universityRanking'; export * from './universityTopicData'; -export * from './user'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; diff --git a/webapp/src/app/api/model/user.ts b/webapp/src/app/api/model/user.ts deleted file mode 100644 index def604e1..00000000 --- a/webapp/src/app/api/model/user.ts +++ /dev/null @@ -1,45 +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. - */ - - -/** - * 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/app.routes.ts b/webapp/src/app/app.routes.ts index 1204da01..ac7dbf07 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,5 +1,6 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; +import { adminGuard } from './shared/guards/admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; import { personBioResolver } from './resolvers/person-bio.resolver'; @@ -92,7 +93,7 @@ export const routes: Routes = [ }, { path: 'accounts', - canActivate: [userGuard], + canActivate: [adminGuard], loadComponent: () => import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts index 784a2474..a10cff43 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.ts +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -55,9 +55,10 @@ export type AccountDialogResult = standalone: true, }) export class AccountDialogComponent { - private readonly dialogRef = inject< - MatDialogRef - >(MatDialogRef); + private readonly dialogRef = + inject< + MatDialogRef + >(MatDialogRef); protected readonly data = inject(MAT_DIALOG_DATA); protected readonly form = new FormGroup({ @@ -73,7 +74,9 @@ export class AccountDialogComponent { ]), organizationId: new FormControl( this.data.account?.organization_id ?? - (this.data.organizations.length === 1 ? this.data.organizations[0].id : ''), + (this.data.organizations.length === 1 + ? this.data.organizations[0].id + : ''), [Validators.required], ), password: new FormControl('', [ @@ -104,16 +107,43 @@ export class AccountDialogComponent { return; } + const account = this.data.account!; + const payload: AccountPayload = {}; + + const email = (value.email ?? '').trim(); + const name = (value.name ?? '').trim(); + const role = value.role ?? account.role; + const organizationId = value.organizationId ?? account.organization_id; + const password = value.password?.trim() ?? ''; + + if (email !== account.email) { + payload.email = email; + } + + if (name !== account.name) { + payload.name = name; + } + + if (role !== account.role) { + payload.role = role; + } + + if (password) { + payload.password = password; + } + + if ( + this.data.canSelectOrganization && + organizationId && + organizationId !== account.organization_id + ) { + payload.organization_id = organizationId; + } + this.dialogRef.close({ mode: 'edit', - accountId: this.data.account!.id, - payload: { - email: value.email ?? '', - name: value.name ?? '', - role: value.role ?? 'USER', - organization_id: value.organizationId ?? '', - password: value.password || undefined, - }, + accountId: account.id, + payload, }); } diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index dc99bd2e..87865007 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -10,9 +10,7 @@ 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 { AccountManagementService } from '../../shared/services/account-management.service'; import type { AccountProfile, AccountRole, @@ -48,12 +46,13 @@ export class AccountsComponent implements OnInit { private readonly router = inject(Router); private readonly dialog = inject(MatDialog); - protected readonly roles: AccountRole[] = [ - 'SUPER_ADMIN', - 'ADMIN', - 'MANAGER', - 'USER', - ]; + protected get availableRoles(): AccountRole[] { + if (this.credentialService.superadmin.value) { + return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER']; + } + + return ['MANAGER', 'USER']; + } protected accounts: AccountProfile[] = []; protected organizations: OrganizationProfile[] = []; protected total = 0; @@ -150,14 +149,14 @@ export class AccountsComponent implements OnInit { }): void { import('./account-dialog.component').then(({ AccountDialogComponent }) => { const dialogRef = this.dialog.open< - AccountDialogComponent, - { - mode: 'create' | 'edit'; - account?: AccountProfile; - organizations: OrganizationProfile[]; - canSelectOrganization: boolean; - roles: AccountRole[]; - }, + AccountDialogComponent, + { + mode: 'create' | 'edit'; + account?: AccountProfile; + organizations: OrganizationProfile[]; + canSelectOrganization: boolean; + roles: AccountRole[]; + }, AccountDialogResult | undefined >(AccountDialogComponent, { width: '760px', @@ -166,7 +165,7 @@ export class AccountsComponent implements OnInit { ...data, organizations: this.organizations, canSelectOrganization: this.credentialService.superadmin.value, - roles: this.roles, + roles: this.availableRoles, }, }); @@ -211,9 +210,13 @@ export class AccountsComponent implements OnInit { this.router.navigate(['/dashboard']); }, error: () => { - this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', { - duration: 5000, - }); + this.snackBar.open( + 'Impersonation konnte nicht gestartet werden.', + 'OK', + { + duration: 5000, + }, + ); }, }); } @@ -236,7 +239,7 @@ export class AccountsComponent implements OnInit { } return ( - this.credentialService.universityadmin.value && + this.credentialService.admin.value && (account.role === 'MANAGER' || account.role === 'USER') ); } diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index eecd2512..21fb3e79 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -137,7 +137,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { ); }, error: (error: HttpErrorResponse) => { - this.credentialService.logoutAcount(); + this.credentialService.clearLocalAuthState(); this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { duration: 5000, }); @@ -169,11 +169,9 @@ export class AppLoginComponent implements OnInit, OnDestroy { } if (!this.accountId) { - this.snackBar.open( - 'Bitte fordere zuerst einen neuen Code an.', - 'OK', - { duration: 5000 }, - ); + this.snackBar.open('Bitte fordere zuerst einen neuen Code an.', 'OK', { + duration: 5000, + }); return; } @@ -197,7 +195,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.router.navigate(['/dashboard']); }, error: (error: HttpErrorResponse) => { - this.credentialService.logoutAcount(); + this.credentialService.clearLocalAuthState(); this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { duration: 5000, }); diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index b5b48337..06b7f24c 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -1,23 +1,35 @@ import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; +import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { Observable, of, switchMap, takeWhile } from 'rxjs'; -export const adminGuard: CanActivateFn = (route, state) => { - let credentialService = inject(CredentialService); - let router = inject(Router); - return new Observable((subscriber) => { - credentialService.validating - .pipe(takeWhile((validating) => validating)) - .subscribe({ - complete: () => { - if (!credentialService.superadmin.value) { - router.navigate(['/login']); - return subscriber.next(false); - } else { - return subscriber.next(true); +export const adminGuard: CanActivateFn = () => { + const credentialService = inject(CredentialService); + const router = inject(Router); + + return credentialService.validating.pipe( + filter((validating) => !validating), + take(1), + switchMap(() => { + if (!credentialService.authenticated.value) { + void router.navigate(['/login']); + return of(false); + } + + return credentialService.validateCurrentSession().pipe( + switchMap(() => { + if ( + !credentialService.superadmin.value && + !credentialService.admin.value + ) { + void router.navigate(['/dashboard']); + return of(false); } - }, - }); - }); + + return of(true); + }), + catchError(() => of(false)), + ); + }), + ); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index c64e9cbc..6be9e6e0 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -1,26 +1,25 @@ import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; +import { catchError, filter, map, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { Observable, of, switchMap, takeWhile } from 'rxjs'; -export const userGuard: CanActivateFn = (route, state) => { - let credentialService = inject(CredentialService); - let router = inject(Router); - return new Observable((subscriber) => { - credentialService.validating - .pipe(takeWhile((validating) => validating)) - .subscribe({ - complete: () => { - if ( - !credentialService.superadmin.value && - !credentialService.universityadmin.value - ) { - router.navigate(['/login']); - return subscriber.next(false); - } else { - return subscriber.next(true); - } - }, - }); - }); +export const userGuard: CanActivateFn = () => { + const credentialService = inject(CredentialService); + const router = inject(Router); + + return credentialService.validating.pipe( + filter((validating) => !validating), + take(1), + switchMap(() => { + if (!credentialService.authenticated.value) { + void router.navigate(['/login']); + return of(false); + } + + return credentialService.validateCurrentSession().pipe( + map(() => true), + catchError(() => of(false)), + ); + }), + ); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 6cbac0b4..130e6c94 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -1,41 +1,86 @@ import { HttpErrorResponse, HttpInterceptorFn } 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 { CredentialService } from '../services/credential.service'; -import { switchMap, throwError } from 'rxjs'; +import { UiFocusService } from '../services/ui-focus.service'; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { - if ( - (req.method == 'POST' && - (req.url.endsWith('/auth/id') || - req.url.endsWith('/auth/access') || - req.url.endsWith('/api/auth/v2/request-otk') || - req.url.endsWith('/api/auth/v2/login') || - req.url.endsWith('/api/auth/v2/access') || - req.url.endsWith('/api/auth/v2/refresh') || - req.url.endsWith('/inse-account/create') || - req.url.endsWith('/auth/v2/request-otk'))) || - req.url.endsWith('/institutions/autocomplete') - ) { - return next(req); - } else { - const credentialService = inject(CredentialService); - const tokenProvider = credentialService.getBearerToken(); + const url = req.url.split('?')[0]; + const uiFocusService = inject(UiFocusService); - return tokenProvider.pipe( - switchMap((response) => { - if (response == undefined) { - return throwError( - () => - new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), - ); - } else { - return next( - req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + response), - }), - ); - } - }), - ); + 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')) { + 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(); + + 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); + }), + ); + }), + ); }; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index ce13f616..6ae05269 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,14 +1,14 @@ import { Injectable, inject } from '@angular/core'; -import { filter, take, map } from 'rxjs/operators'; //TODO: review by arman -import { Observable, of, switchMap, tap, throwError } from 'rxjs'; // review -import { BehaviorSubject } from 'rxjs'; //review +import { filter, take, map, catchError, finalize } from 'rxjs/operators'; import { - AuthService, - Configuration, - INSEAccountServiceService, - IdentityGrant as ApiIdentityGrant, - AccessGrant as ApiAccessGrant, -} from '../../api'; + BehaviorSubject, + Observable, + of, + switchMap, + tap, + throwError, +} from 'rxjs'; +import { AuthService, Configuration } from '../../api'; import { HttpClient, HttpHeaders } from '@angular/common/http'; export interface AuthAccount { @@ -54,21 +54,27 @@ interface TimedAccessGrant { effectiveAccountId: string; } +type LogoutResult = 'logged-out' | 'stopped-impersonating'; +type UnauthorizedRecoveryResult = + | 'logged-out' + | 'stopped-impersonating' + | 'already-handling'; + @Injectable({ providedIn: 'root', }) export class CredentialService { - private accountService = inject(INSEAccountServiceService); private authService = inject(AuthService); private httpClient = inject(HttpClient); private apiConfiguration = inject(Configuration, { optional: true }); + private handlingUnauthorized = false; private static readonly KEY_GRANT = 'grant'; public readonly validating = new BehaviorSubject(false); public readonly authenticated = new BehaviorSubject(false); public readonly superadmin = new BehaviorSubject(false); - public readonly universityadmin = new BehaviorSubject(false); + public readonly admin = new BehaviorSubject(false); public readonly organization = new BehaviorSubject( undefined, ); @@ -93,16 +99,18 @@ export class CredentialService { if (token) { const r = token.grant.scope.r as string[]; this.superadmin.next(r.includes('SUPER_ADMIN')); - this.universityadmin.next(r.includes('UNI_ADMIN') || r.includes('ADMIN')); + this.admin.next(r.includes('ADMIN')); this.login.next(token.grant.scope.a?.l ?? ''); this.email.next(token.grant.scope.a?.e ?? ''); this.organizationName.next(token.grant.scope.a?.on ?? ''); - this.impersonating.next(token.realAccountId !== token.effectiveAccountId); + this.impersonating.next( + token.realAccountId !== token.effectiveAccountId, + ); this.realAccountId.next(token.realAccountId); this.effectiveAccountId.next(token.effectiveAccountId); } else { this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.login.next(''); this.email.next(''); this.organizationName.next(''); @@ -120,13 +128,19 @@ export class CredentialService { } } + public validateCurrentSession(): Observable { + return this.httpClient + .get(`${this.apiBasePath}/api/accounts/me`, { withCredentials: true }) + .pipe(map(() => undefined)); + } + public requestOtk(email: string, password: string): Observable { const request = ++this.request; this.validating.next(true); this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); @@ -134,10 +148,17 @@ export class CredentialService { .requestOtk({ email: email.trim().toLowerCase(), password }) .pipe( map((response: { account_id?: string }) => { - if (this.request != request) return ''; - this.validating.next(false); + if (this.request !== request) { + return ''; + } + return response.account_id ?? ''; }), + finalize(() => { + if (this.request === request) { + this.validating.next(false); + } + }), ); } @@ -151,7 +172,7 @@ export class CredentialService { this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); @@ -166,7 +187,10 @@ export class CredentialService { grant: { token_type: 'ID', access_token: response.id_token, - expires_in: Math.max(payload.exp - Math.floor(Date.now() / 1000), 0), + expires_in: Math.max( + payload.exp - Math.floor(Date.now() / 1000), + 0, + ), scope: this.buildIdentityScope(accountId, email), }, expiration: payload.exp * 1000, @@ -181,43 +205,6 @@ export class CredentialService { ); } - public loginAccount(login: string, password: string) { - const request = ++this.request; - const now = Date.now(); - this.validating.next(true); - this.authenticated.next(false); - this.organization.next(undefined); - this.superadmin.next(false); - this.universityadmin.next(false); - this.identityToken.next(undefined); - this.accessToken.next(undefined); - - const body = new URLSearchParams(); - body.set('username', login); - body.set('password', password); - - this.accountService.getIdentityGrant(login, password).subscribe({ - next: (result) => { - if (this.request != request) return; - const token: TimedIdentityGrant = { - grant: result as any as IdentityGrant, - expiration: result.expires_in * 1000 + now, - accountId: String((result as any).scope?.a?.i ?? ''), - }; - this.identityToken.next(token); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(token), - ); - this.refreshAccessToken(token); - }, - error: () => { - if (this.request != request) return; - this.validating.next(false); - }, - }); - } - public refreshAccessToken(identityToken: TimedIdentityGrant) { const request = ++this.request; this.validating.next(true); @@ -229,7 +216,7 @@ export class CredentialService { this.organization.next(undefined); this.authenticated.next(false); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.validating.next(false); }, }); @@ -265,20 +252,96 @@ export class CredentialService { ).pipe(tap({ error: () => this.validating.next(false) })); } - public logoutAcount() { + public logoutAccount(): Observable { + const wasImpersonating = this.impersonating.value; + + 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 clearLocalAuthState(): void { this.request += 1; localStorage.removeItem(CredentialService.KEY_GRANT); this.authenticated.next(false); this.organization.next(undefined); this.superadmin.next(false); - this.universityadmin.next(false); + this.admin.next(false); this.identityToken.next(undefined); this.accessToken.next(undefined); this.validating.next(false); } - public registerAccount(data: any): Observable { - return this.accountService.createUser(data); + public handleUnauthorized(): Observable { + if (this.handlingUnauthorized) { + return of('already-handling' as const); + } + + this.handlingUnauthorized = true; + + const recovery$ = + this.impersonating.value && this.identityToken.value + ? 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( + 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), + ); + } + + public registerAccount(_data: unknown): Observable { + return throwError(() => new Error('Registration is temporarily disabled.')); } //review: arman (generated fix) @@ -388,7 +451,8 @@ export class CredentialService { } private buildAccessScope(payload: any, email: string): AuthScope { - const accountId = payload.effective_account_id ?? payload.real_account_id ?? ''; + const accountId = + payload.effective_account_id ?? payload.real_account_id ?? ''; const organizationId = payload.organization_id ?? ''; const role = String(payload.effective_role ?? ''); @@ -405,32 +469,4 @@ export class CredentialService { }, }; } - /* Old version with added complete statements to resolve loading spinner issue - public getBearerToken(): Observable { - return new Observable((observer) => { - if (this.validating.value) { - this.validating.pipe(takeWhile((validating) => validating)).subscribe({ - complete: () => { - observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined); - observer.complete(); // added complete - } - }); - } else if (!this.accessToken.value) { - observer.next(undefined); - observer.complete(); // added complete - } else if (Date.now() < this.accessToken.value.expiration) { - observer.next(this.accessToken.value.grant.access_token); - observer.complete(); // added complete - } else { - this.refreshAccessToken(this.identityToken.value!); - this.validating.pipe(takeWhile((validating) => validating)).subscribe({ - complete: () => { - observer.next(this.accessToken.value ? this.accessToken.value.grant.access_token : undefined); - observer.complete(); // added complete - } - }); - } - }); - } - */ } diff --git a/webapp/src/app/shared/services/ui-focus.service.ts b/webapp/src/app/shared/services/ui-focus.service.ts new file mode 100644 index 00000000..ba149da8 --- /dev/null +++ b/webapp/src/app/shared/services/ui-focus.service.ts @@ -0,0 +1,14 @@ +import { Injectable } from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class UiFocusService { + public blurActiveElement(): void { + const activeElement = document.activeElement; + + if (activeElement instanceof HTMLElement) { + activeElement.blur(); + } + } +} 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 e299503c..3de4c98b 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,11 +3,7 @@ - @if ( - (credentialService.authenticated | async) && - ((credentialService.superadmin | async) || - (credentialService.universityadmin | async)) - ) { + @if (credentialService.authenticated | async) { { + if (result === 'stopped-impersonating') { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } + }, + }); } stopImpersonating(): void { 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 ab143d54..7a766163 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 @@ -42,31 +42,37 @@ @for (item of navItems; track item.label) { - @if (collapsed()) { - - {{ item.icon }} - - } @else { - - {{ item.icon }} - {{ item.label }} - + @if ( + !item.adminOnly || + (credentialService.superadmin | async) || + (credentialService.admin | async) + ) { + @if (collapsed()) { + + {{ item.icon }} + + } @else { + + {{ item.icon }} + {{ item.label }} + + } } } 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 ca664e06..37eaaca7 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 @@ -15,6 +15,15 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatDialog } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; +type NavItem = { + label: string; + icon: string; + route: string; + disabled: boolean; + queryParams?: Record; + adminOnly?: boolean; +}; + @Component({ selector: 'app-menu', imports: [ @@ -41,7 +50,7 @@ export class AppMenuComponent { matrixParams: 'ignored', fragment: 'ignored', }; - navItems = [ + navItems: NavItem[] = [ { label: 'Dashboard', icon: 'dashboard', @@ -95,6 +104,7 @@ export class AppMenuComponent { icon: 'manage_accounts', route: '/accounts', disabled: false, + adminOnly: true, }, ]; @@ -117,8 +127,15 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAcount(); - this.router.navigate(['/login']); + this.credentialService.logoutAccount().subscribe({ + next: (result) => { + if (result === 'stopped-impersonating') { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } + }, + }); }); } }