diff --git a/service/src/main/inse/account_management/model.py b/service/src/main/inse/account_management/model.py index 2bb7613d..8b21edf7 100644 --- a/service/src/main/inse/account_management/model.py +++ b/service/src/main/inse/account_management/model.py @@ -20,6 +20,7 @@ class AccountProfile(BaseModel): organization_id: uuid.UUID organization_name: str deleted: bool + activated: bool is_current: bool = False is_real_account: bool = False is_impersonating: bool = False @@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel): password: Optional[str] = Field(default=None, min_length=8) openalex_person_id: Optional[str] = None deleted: Optional[bool] = None + activated: Optional[bool] = None diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py index 5ef45372..9e0362ad 100644 --- a/service/src/main/inse/account_management/service.py +++ b/service/src/main/inse/account_management/service.py @@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: organization_id=account.organization_id, organization_name=organization_name, deleted=account.deleted, + activated=account.activated, is_current=account.id == token.effective_account_id, is_real_account=account.id == token.real_account_id, is_impersonating=token.is_impersonating(), @@ -108,17 +109,21 @@ def list_accounts( search: Optional[str] = None, organization_id: Optional[uuid.UUID] = None, ) -> AccountPage: - if not _is_admin(access_token.effective_role): + if access_token.effective_role not in { + UserRole.SUPER_ADMIN, + UserRole.ADMIN, + UserRole.MANAGER, + }: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, - detail="Only admins can list accounts.", + detail="Only managers and admins can list accounts.", ) statement = select(Account) count_statement = select(func.count()).select_from(Account) filters = [] - if access_token.effective_role == UserRole.ADMIN: + if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}: filters.append(Account.organization_id == access_token.effective_organization_id) elif organization_id is not None: filters.append(Account.organization_id == organization_id) @@ -207,7 +212,7 @@ def list_organizations( if access_token.effective_role == UserRole.SUPER_ADMIN: organizations = session.exec( select(Organization) - .where(Organization.deleted == False) # noqa: E712 + .where(Organization.deleted.is_not(True)) .order_by(Organization.name) ).all() elif access_token.effective_role == UserRole.ADMIN: @@ -285,6 +290,15 @@ def update_account( account.deleted = payload.deleted account.epoch += 1 + if payload.activated is not None and payload.activated != account.activated: + if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only super admins can activate or deactivate other accounts.", + ) + account.activated = payload.activated + account.epoch += 1 + session.add(account) session.commit() session.refresh(account) diff --git a/service/src/main/inse/account_management/test_service.py b/service/src/main/inse/account_management/test_service.py new file mode 100644 index 00000000..b6d43714 --- /dev/null +++ b/service/src/main/inse/account_management/test_service.py @@ -0,0 +1,180 @@ +from types import SimpleNamespace + +import pytest +from fastapi import HTTPException +from sqlmodel import Session, SQLModel, create_engine + +from inse.account_management import service +from inse.account_management.model import UpdateAccountRequest +from inse.auth.model import Account, Organization, UserRole + + +@pytest.fixture() +def session(): + engine = create_engine( + "sqlite:///:memory:", connect_args={"check_same_thread": False} + ) + SQLModel.metadata.create_all(engine) + with Session(engine) as database_session: + yield database_session + + +def access_token(role, account_id, organization_id): + return SimpleNamespace( + effective_role=role, + effective_account_id=account_id, + real_account_id=account_id, + effective_organization_id=organization_id, + is_impersonating=lambda: False, + ) + + +def create_accounts(session): + organization = Organization(name="Test organization") + session.add(organization) + session.flush() + superadmin = Account( + email="superadmin@example.org", + name="Superadmin", + password_hash="hash", + organization_id=organization.id, + role=UserRole.SUPER_ADMIN, + ) + user = Account( + email="user@example.org", + name="User", + password_hash="hash", + organization_id=organization.id, + ) + session.add(superadmin) + session.add(user) + session.commit() + return organization, superadmin, user + + +def test_accounts_are_activated_by_default(session): + _, _, user = create_accounts(session) + assert user.activated is True + + +def test_superadmin_can_deactivate_and_reactivate_account(session): + organization, superadmin, user = create_accounts(session) + token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id) + + profile = service.update_account( + session, token, user.id, UpdateAccountRequest(activated=False) + ) + assert profile.activated is False + assert user.epoch == 1 + + profile = service.update_account( + session, token, user.id, UpdateAccountRequest(activated=True) + ) + assert profile.activated is True + assert user.epoch == 2 + + +def test_non_superadmin_cannot_change_activation(session): + organization, superadmin, user = create_accounts(session) + admin = Account( + email="admin@example.org", + name="Admin", + password_hash="hash", + organization_id=organization.id, + role=UserRole.ADMIN, + ) + session.add(admin) + session.commit() + + with pytest.raises(HTTPException) as error: + service.update_account( + session, + access_token(UserRole.ADMIN, admin.id, organization.id), + user.id, + UpdateAccountRequest(activated=False), + ) + + assert error.value.status_code == 403 + assert user.activated is True + + +def test_superadmin_cannot_deactivate_own_account(session): + organization, superadmin, _ = create_accounts(session) + + with pytest.raises(HTTPException) as error: + service.update_account( + session, + access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id), + superadmin.id, + UpdateAccountRequest(activated=False), + ) + + assert error.value.status_code == 403 + assert superadmin.activated is True + + +def test_manager_only_lists_accounts_from_own_organization(session): + organization, superadmin, user = create_accounts(session) + manager = Account( + email="manager@example.org", + name="Manager", + password_hash="hash", + organization_id=organization.id, + role=UserRole.MANAGER, + ) + other_organization = Organization(name="Other organization") + session.add(other_organization) + session.flush() + other_user = Account( + email="other@example.org", + name="Other User", + password_hash="hash", + organization_id=other_organization.id, + ) + session.add(manager) + session.add(other_user) + session.commit() + + result = service.list_accounts( + session, + access_token(UserRole.MANAGER, manager.id, organization.id), + page=0, + page_size=25, + organization_id=other_organization.id, + ) + + assert {profile.id for profile in result.items} == { + account.id for account in [superadmin, user, manager] + } + assert other_user.id not in {profile.id for profile in result.items} + + +def test_user_cannot_list_accounts(session): + organization, _, user = create_accounts(session) + + with pytest.raises(HTTPException) as error: + service.list_accounts( + session, + access_token(UserRole.USER, user.id, organization.id), + page=0, + page_size=25, + ) + + assert error.value.status_code == 403 + + +def test_superadmin_lists_all_active_organizations_for_selectbox(session): + first = Organization(name="Alpha") + second = Organization(name="Beta") + deleted = Organization(name="Deleted", deleted=True) + session.add(first) + session.add(second) + session.add(deleted) + session.commit() + + organizations = service.list_organizations( + session, + access_token(UserRole.SUPER_ADMIN, first.id, first.id), + ) + + assert [organization.name for organization in organizations] == ["Alpha", "Beta"] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index a79aa113..bd519058 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -77,6 +77,12 @@ class Account(Durable, table=True): nullable=False, description="The epoch value for the account. Used for versioning of tokens.", ) + activated: bool = Field( + default=True, + nullable=False, + index=True, + description="Indicates whether the account is allowed to authenticate.", + ) password_hash: str = Field( index=False, nullable=False, diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 0af15a4b..61626236 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -180,7 +180,11 @@ def request_otk(session: Session, email: str, password: str): logger.debug("OTK request for email %s: account found: %s", email, account) - if account is None or account.deleted or account.id is None: + if ( + account is None + or account.deleted + or account.id is None + ): logger.warning("OTK request failed for email %s: account not found", email) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -196,6 +200,13 @@ def request_otk(session: Session, email: str, password: str): detail="Invalid email or password", ) + if not account.activated: + logger.warning("OTK request rejected for deactivated account %s", account.id) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is deactivated and cannot log in.", + ) + otk_code = f"{secrets.randbelow(1_000_000):06d}" print(otk_code) @@ -300,7 +311,7 @@ def login( ) account = _get_active_account(session, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: logger.warning("Login failed: account is not active %s", account_id) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -469,7 +480,12 @@ def _get_account_epoch( """ account = session.get(Account, account_id) - if account is None or account.deleted or account.id is None: + if ( + account is None + or account.deleted + or not account.activated + or account.id is None + ): raise AccountNotFoundException return account.epoch @@ -487,7 +503,7 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole: """ account = session.get(Account, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: raise AccountNotFoundException return account.role @@ -505,7 +521,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U """ account = session.get(Account, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: raise AccountNotFoundException return account.organization_id @@ -525,12 +541,18 @@ def _is_valid_impersonation( bool: True if impersonation is allowed, False otherwise. """ real_account = session.get(Account, real_account_id) - if not real_account or real_account.deleted or real_account.id is None: + if ( + not real_account + or real_account.deleted + or not real_account.activated + or real_account.id is None + ): raise AccountNotFoundException effective_account = session.get(Account, effective_account_id) if ( not effective_account or effective_account.deleted + or not effective_account.activated or effective_account.id is None ): raise AccountNotFoundException @@ -980,6 +1002,9 @@ def _verify_fp_token( account_id=epoch_account_id, ) + if uuid.UUID(real_account_id) != epoch_account_id: + _get_active_account(session, uuid.UUID(real_account_id)) + token_epoch = payload.get(EPOCH_KEY) if token_epoch is None or token_epoch != current_account_epoch: raise HTTPException( @@ -1016,7 +1041,12 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: """ account = session.get(Account, account_id) - if account is None or account.deleted or account.id is None: + if ( + account is None + or account.deleted + or not account.activated + or account.id is None + ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Account is not active.", diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 7db19bb4..0e61130c 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -210,6 +210,35 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup): auth_service.request_otk(in_memory_session, email, "wrongpw") +def test_deactivated_account_cannot_request_otk(in_memory_session): + email = "inactive@example.com" + password = "rightpw" + _, account = create_org_and_account(in_memory_session, email, password) + account.activated = False + in_memory_session.add(account) + in_memory_session.commit() + + with pytest.raises(HTTPException) as error: + auth_service.request_otk(in_memory_session, email, password) + + assert error.value.status_code == 403 + assert error.value.detail == "Account is deactivated and cannot log in." + + +def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session): + _, account = create_org_and_account( + in_memory_session, "inactive-lookup@example.com", "password" + ) + account.activated = False + in_memory_session.add(account) + in_memory_session.commit() + + with pytest.raises(HTTPException) as error: + auth_service._get_active_account(in_memory_session, account.id) + + assert error.value.status_code == 403 + + def test_login_with_expired_secret(in_memory_session, settings_backup): config_module.settings.token_hmac_key = "expired-key" config_module.settings.token_issuer_id = "expired-issuer" diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py index 728b750f..39a7c24b 100644 --- a/service/src/main/inse/database.py +++ b/service/src/main/inse/database.py @@ -1,6 +1,7 @@ from typing import Annotated from fastapi import Depends +from sqlalchemy import inspect, text from sqlmodel import SQLModel, Session, create_engine from inse import config @@ -18,6 +19,15 @@ engine = create_engine( def create_db_and_tables(): """Creates the database and tables based on the SQLModel metadata.""" SQLModel.metadata.create_all(engine) + columns = {column["name"] for column in inspect(engine).get_columns("account")} + if "activated" not in columns: + with engine.begin() as connection: + connection.execute( + text( + "ALTER TABLE account ADD COLUMN activated " + "BOOLEAN NOT NULL DEFAULT TRUE" + ) + ) def get_session(): diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 56d97db2..80dd88c9 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -73,6 +73,7 @@ def _member_counts( .where( Account.organization_id.in_(organization_ids), Account.deleted == False, # noqa: E712 + Account.activated == True, # noqa: E712 ) .group_by(Account.organization_id) ).all() @@ -91,6 +92,21 @@ def _to_profile( ) +def _deactivate_organization_accounts( + session: Session, organization_id: uuid.UUID +) -> None: + accounts = session.exec( + select(Account).where( + Account.organization_id == organization_id, + Account.activated == True, # noqa: E712 + ) + ).all() + for account in accounts: + account.activated = False + account.epoch += 1 + session.add(account) + + def get_organizations( session: Session, access_token: AccessToken, @@ -162,6 +178,8 @@ def update_organization( if payload.other_inst_id is not None: organization.openalex_institution_id = payload.other_inst_id.strip() or None if payload.deleted is not None: + if payload.deleted and not organization.deleted: + _deactivate_organization_accounts(session, organization.id) organization.deleted = payload.deleted session.add(organization) @@ -178,6 +196,8 @@ def delete_organization( ) -> None: _require_super_admin(access_token) organization = _get_organization_or_404(session, organization_id) + if not organization.deleted: + _deactivate_organization_accounts(session, organization.id) organization.deleted = True session.add(organization) session.commit() diff --git a/service/src/main/inse/organization_management/test_service.py b/service/src/main/inse/organization_management/test_service.py index ce3b3e03..a7ce6ff6 100644 --- a/service/src/main/inse/organization_management/test_service.py +++ b/service/src/main/inse/organization_management/test_service.py @@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session): assert session.get(Organization, created.id).deleted is True +def test_deleting_organization_deactivates_all_its_accounts(session): + organization = Organization(name="Organization to delete") + session.add(organization) + session.flush() + active_account = Account( + email="active-delete@example.org", + name="Active", + password_hash="hash", + organization_id=organization.id, + epoch=3, + ) + inactive_account = Account( + email="inactive-delete@example.org", + name="Inactive", + password_hash="hash", + organization_id=organization.id, + activated=False, + epoch=5, + ) + session.add(active_account) + session.add(inactive_account) + session.commit() + + service.delete_organization( + session, token(UserRole.SUPER_ADMIN, organization.id), organization.id + ) + + session.refresh(active_account) + session.refresh(inactive_account) + assert active_account.activated is False + assert active_account.epoch == 4 + assert inactive_account.activated is False + assert inactive_account.epoch == 5 + + +def test_marking_organization_deleted_deactivates_its_accounts(session): + organization = Organization(name="Organization to update") + session.add(organization) + session.flush() + account = Account( + email="active-update@example.org", + name="Active", + password_hash="hash", + organization_id=organization.id, + ) + session.add(account) + session.commit() + + service.update_organization( + session, + token(UserRole.SUPER_ADMIN, organization.id), + organization.id, + UpdateOrganizationRequest(deleted=True), + ) + + session.refresh(account) + assert account.activated is False + assert account.epoch == 1 + + @pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER]) def test_only_superadmin_can_create_organizations(session, role): organization = Organization(name="Scope") diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 17a68e22..52a9f7e6 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -18,6 +18,7 @@ export interface AccountProfile { organization_id: string; organization_name: string; deleted: boolean; + activated: boolean; is_current?: boolean; is_real_account?: boolean; is_impersonating?: boolean; @@ -25,4 +26,3 @@ export interface AccountProfile { export namespace AccountProfile { } - diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index 15b0043d..1d4389f7 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -18,8 +18,8 @@ export interface UpdateAccountRequest { password?: string | null; openalex_person_id?: string | null; deleted?: boolean | null; + activated?: boolean | null; } export namespace UpdateAccountRequest { } - diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c046384c..4f8758d7 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,6 +1,5 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; -import { adminGuard } from './shared/guards/admin.guard'; import { superAdminGuard } from './shared/guards/super-admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; @@ -20,6 +19,7 @@ import { fundingProjectPageResolver } from './resolvers/funding-project-page.res import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; +import { accountViewerGuard } from './shared/guards/account-viewer.guard'; export const routes: Routes = [ { @@ -109,7 +109,7 @@ export const routes: Routes = [ }, { path: 'accounts', - canActivate: [adminGuard], + canActivate: [accountViewerGuard], loadComponent: () => import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 6a5fdb83..5f2ac458 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -2,16 +2,25 @@
@@ -35,11 +44,19 @@ }
- -
@@ -62,19 +79,28 @@ Organisation Rolle Status - Aktionen + @if (!isReadOnly) { + Aktionen + } @for (account of accounts; track account.id) { - + - + } @else { + + } {{ account.email }} {{ account.organization_name }} @@ -82,16 +108,29 @@ {{ account.role | role }} - - {{ account.deleted ? 'deleted' : 'active' }} + + {{ + account.deleted + ? 'deleted' + : account.activated + ? 'active' + : 'inactive' + }} - -
+ @if (!isReadOnly) { + +
@@ -99,24 +138,48 @@ mat-icon-button type="button" aria-label="Impersonate" + matTooltip="Als dieser Account anmelden" [disabled]="!canImpersonate(account)" (click)="impersonate(account)"> switch_account + @if (credentialService.isEffectiveSuperAdmin()) { + + } -
- +
+ + } } @empty { - Keine Accounts gefunden. + + Keine Accounts gefunden. + } @@ -127,6 +190,7 @@