diff --git a/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.html b/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.html new file mode 100644 index 00000000..1bf8f682 --- /dev/null +++ b/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.html @@ -0,0 +1,39 @@ +

Create workspace

+ +

+ A workspace holds its own applications, team, API keys and billing. You become its Owner and the dashboard + switches to it right away. You can switch back any time from the workspace menu. +

+
+ + Workspace name + + {{ nameMin }}–{{ nameMax }} letters, numbers, spaces or underscores + @if (form.controls.name.touched && form.controls.name.invalid) { + + @if (form.controls.name.hasError('required')) { + Name is required + } @else if (form.controls.name.hasError('minlength')) { + Use at least {{ nameMin }} characters + } @else { + Start with a letter or number; use only letters, numbers, spaces and underscores + } + + } + +
+ @if (error(); as message) { + + } +
+ + + + diff --git a/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.ts b/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.ts new file mode 100644 index 00000000..d6715aaa --- /dev/null +++ b/apps/36-blocks/src/app/panel/layout/create-workspace-dialog/create-workspace-dialog.component.ts @@ -0,0 +1,90 @@ +import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; +import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { IClient } from '@proxy/models/root-models'; +import { RootService } from '@proxy/services/proxy/root'; +import { + WORKSPACE_NAME_MAX, + WORKSPACE_NAME_MIN, + WORKSPACE_NAME_PATTERN, + errorMessages, + isForbidden, +} from '../../team/team.models'; + +/** + * Creates a new workspace (a "client") owned by the signed-in user. On success the dialog closes with the created + * workspace; the API has already switched the session into it, so the caller reloads the panel. + */ +@Component({ + selector: 'proxy-create-workspace-dialog', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatInputModule, + MatProgressSpinnerModule, + ], + templateUrl: './create-workspace-dialog.component.html', +}) +export class CreateWorkspaceDialogComponent { + private readonly dialogRef = inject>(MatDialogRef); + private readonly rootService = inject(RootService); + + protected readonly nameMin = WORKSPACE_NAME_MIN; + protected readonly nameMax = WORKSPACE_NAME_MAX; + readonly saving = signal(false); + readonly error = signal(null); + + readonly form = new FormGroup({ + name: new FormControl('', [ + Validators.required, + Validators.minLength(WORKSPACE_NAME_MIN), + Validators.maxLength(WORKSPACE_NAME_MAX), + Validators.pattern(WORKSPACE_NAME_PATTERN), + ]), + }); + + submit(): void { + if (this.saving()) return; + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + const failure = 'The workspace could not be created. Check the name and retry.'; + this.saving.set(true); + this.error.set(null); + this.dialogRef.disableClose = true; + this.rootService.createClient({ name: this.form.getRawValue().name!.trim() }).subscribe({ + next: (response) => { + if (response.hasError || !response.data) { + this.fail(errorMessages(response, failure)); + return; + } + this.saving.set(false); + this.dialogRef.close(response.data); + }, + error: (error: unknown) => + this.fail( + isForbidden(error) + ? 'You do not have permission to create a workspace.' + : errorMessages(error, failure) + ), + }); + } + + cancel(): void { + if (!this.saving()) this.dialogRef.close(); + } + + private fail(message: string): void { + this.saving.set(false); + this.dialogRef.disableClose = false; + this.error.set(message); + } +} diff --git a/apps/36-blocks/src/app/panel/layout/layout.component.html b/apps/36-blocks/src/app/panel/layout/layout.component.html index 1e32c1d9..d0b55cf4 100644 --- a/apps/36-blocks/src/app/panel/layout/layout.component.html +++ b/apps/36-blocks/src/app/panel/layout/layout.component.html @@ -16,7 +16,6 @@ } @let clientSettings = clientSettings$ | async; @let clientList = clients$ | async; - @let isMultipleClients = (clientList?.data?.length ?? 0) > 1;
@@ -41,11 +40,9 @@ > {{ clientSettings?.client?.name }} - @if (isMultipleClients) { - {{ - clientsMenuTrigger?.menuOpen ? 'keyboard_arrow_up' : 'keyboard_arrow_down' - }} - } + {{ + clientsMenuTrigger?.menuOpen ? 'keyboard_arrow_up' : 'keyboard_arrow_down' + }}
} @else { } + + + + + +@if (rolesFailed()) { + +} + +@if (loading()) { +

Loading API keys…

+} @else if (error(); as message) { + +} @else if (keys().length === 0) { +
+

This workspace has no API keys yet.

+ +
+} @else { +

+ {{ total() }} {{ total() === 1 ? 'key' : 'keys' }} · Page {{ page() }} of {{ totalPages() }} +

+
+ + + + + + + + + + + + + + @for (key of keys(); track key.id) { + + + + + + + + + } + +
+ API keys of the current workspace +
NameKeyRoleStatusCreatedActions
{{ key.name }} + {{ isRevealed(key) ? key.authkey : mask(key.authkey) }} + + + {{ roleName(key.role_id) }} + {{ key.status === 'active' ? 'Active' : 'Inactive' }} + + {{ key.created_at | date: 'mediumDate' }} + by {{ actor(key.created_by) }} + + + + +
+
+ +} + + +

{{ editing() ? 'Edit API key' : 'Create API key' }}

+ +

+ @if (editing()) { + You can rename the key or change its role. The key value itself cannot be changed; delete the key and + create a new one to rotate it. + } @else { + A secure key is generated for you. You can show and copy it from the list after it is created. + } +

+
+ + Name + + {{ nameMin }}–{{ nameMax }} letters, numbers or underscores + @if (keyForm.controls.name.touched && keyForm.controls.name.invalid) { + + @if (keyForm.controls.name.hasError('required')) { + Name is required + } @else if (keyForm.controls.name.hasError('minlength')) { + Use at least {{ nameMin }} characters + } @else { + Start with a letter or number; use only letters, numbers and underscores + } + + } + + + Role + + @for (role of assignable(); track role.id) { + {{ role.role_name }} · {{ role.permissions.length }} permissions + } + + The key can do whatever this role can do. + @if (keyForm.controls.role_id.touched && keyForm.controls.role_id.invalid) { + Choose a role + } + +
+ @if (dialogError(); as message) { + + } +
+ + + + +
diff --git a/apps/36-blocks/src/app/panel/team/api-keys/api-keys.component.ts b/apps/36-blocks/src/app/panel/team/api-keys/api-keys.component.ts new file mode 100644 index 00000000..60e24b1f --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/api-keys/api-keys.component.ts @@ -0,0 +1,359 @@ +import { DatePipe } from '@angular/common'; +import { + ChangeDetectionStrategy, + Component, + DestroyRef, + OnDestroy, + OnInit, + TemplateRef, + ViewChild, + computed, + inject, + signal, +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { ConfirmDialogComponent } from '@proxy/ui/confirm-dialog'; +import { CopyButtonComponent } from '@proxy/ui/copy-button'; +import { PrimeNgToastService } from '@proxy/ui/prime-ng-toast'; +import { Observable, Subscription } from 'rxjs'; +import { + API_KEY_NAME_MAX, + API_KEY_NAME_MIN, + API_KEY_NAME_PATTERN, + ApiKey, + OperatorRole, + assignableRoles, + errorMessages, + isForbidden, + maskSecret, +} from '../team.models'; +import { TeamResponse, TeamService } from '../team.service'; + +/** + * API keys ("authkeys") of the current workspace. A key identifies the workspace to your servers and acts with the + * permissions of its role, so the secret is masked by default and only revealed on request in this browser tab. + */ +@Component({ + selector: 'proxy-team-api-keys', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + DatePipe, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressSpinnerModule, + MatSelectModule, + MatTooltipModule, + CopyButtonComponent, + ], + templateUrl: './api-keys.component.html', + styleUrl: '../team-tab.scss', +}) +export class ApiKeysComponent implements OnInit, OnDestroy { + private readonly service = inject(TeamService); + private readonly dialog = inject(MatDialog); + private readonly toast = inject(PrimeNgToastService); + private readonly destroyRef = inject(DestroyRef); + private keysRequest?: Subscription; + private rolesRequest?: Subscription; + private saveRequest?: Subscription; + private dialogRef: MatDialogRef | null = null; + + @ViewChild('keyDialog', { static: true }) keyDialog!: TemplateRef; + + protected readonly mask = maskSecret; + protected readonly nameMin = API_KEY_NAME_MIN; + protected readonly nameMax = API_KEY_NAME_MAX; + + readonly keys = signal([]); + readonly loading = signal(false); + readonly error = signal(null); + readonly page = signal(1); + readonly totalPages = signal(0); + readonly total = signal(0); + + readonly roles = signal([]); + readonly rolesLoading = signal(false); + readonly rolesFailed = signal(false); + readonly assignable = computed(() => assignableRoles(this.roles())); + + /** Ids whose secret is currently visible. Held only in memory. */ + readonly revealed = signal>(new Set()); + readonly saving = signal(false); + readonly dialogError = signal(null); + readonly editing = signal(null); + /** Key currently being activated, deactivated or deleted. */ + readonly busyId = signal(null); + + readonly keyForm = new FormGroup({ + name: new FormControl('', [ + Validators.required, + Validators.minLength(API_KEY_NAME_MIN), + Validators.maxLength(API_KEY_NAME_MAX), + Validators.pattern(API_KEY_NAME_PATTERN), + ]), + role_id: new FormControl(null, [Validators.required]), + }); + + ngOnInit(): void { + this.load(1); + this.loadRoles(); + } + + ngOnDestroy(): void { + this.keysRequest?.unsubscribe(); + this.rolesRequest?.unsubscribe(); + this.saveRequest?.unsubscribe(); + } + + roleName(roleId: number): string { + return this.roles().find((role) => role.id === roleId)?.role_name ?? `Role #${roleId}`; + } + + actor(actor: ApiKey['created_by']): string { + return actor?.name?.trim() || actor?.email || 'Unknown'; + } + + isRevealed(key: ApiKey): boolean { + return this.revealed().has(key.id); + } + + toggleReveal(key: ApiKey): void { + const next = new Set(this.revealed()); + if (!next.delete(key.id)) next.add(key.id); + this.revealed.set(next); + } + + load(page: number): void { + this.keysRequest?.unsubscribe(); + this.loading.set(true); + this.error.set(null); + this.page.set(page); + this.keysRequest = this.service.getApiKeys(page).subscribe({ + next: (response) => { + this.loading.set(false); + if (response.hasError || !response.data || !Array.isArray(response.data.data)) { + this.keys.set([]); + this.error.set('API keys could not be loaded. Retry or contact an administrator.'); + return; + } + this.keys.set(response.data.data); + this.total.set(response.data.totalEntityCount ?? response.data.data.length); + this.totalPages.set(response.data.totalPageCount ?? 1); + }, + error: (error: unknown) => { + this.loading.set(false); + this.keys.set([]); + this.error.set( + isForbidden(error) + ? 'You need the view_authkeys permission in this workspace to see API keys. Ask a workspace Owner or Admin.' + : 'API keys could not be loaded. Check your connection and retry.' + ); + }, + }); + } + + loadRoles(refresh = false): void { + this.rolesRequest?.unsubscribe(); + this.rolesLoading.set(true); + this.rolesFailed.set(false); + this.rolesRequest = this.service.getRoles(refresh).subscribe({ + next: (response) => { + this.rolesLoading.set(false); + if (response.hasError || !Array.isArray(response.data?.data)) { + this.rolesFailed.set(true); + return; + } + this.roles.set(response.data.data); + }, + error: () => { + this.rolesLoading.set(false); + this.rolesFailed.set(true); + }, + }); + } + + openCreate(): void { + if (this.dialogRef) return; + this.editing.set(null); + this.keyForm.reset({ name: '', role_id: null }); + this.openDialog(); + } + + openEdit(key: ApiKey): void { + if (this.dialogRef) return; + this.editing.set(key); + this.keyForm.reset({ + name: key.name, + role_id: this.assignable().some((role) => role.id === key.role_id) ? key.role_id : null, + }); + this.openDialog(); + } + + submitKey(): void { + if (this.saving()) return; + if (this.keyForm.invalid) { + this.keyForm.markAllAsTouched(); + return; + } + const { name, role_id } = this.keyForm.getRawValue(); + const existing = this.editing(); + const trimmed = name!.trim(); + if (!existing) { + this.runSave(this.service.createApiKey({ name: trimmed, role_id: role_id! }), (response) => { + const created = response.data as ApiKey | undefined; + if (created?.id) this.revealed.set(new Set(this.revealed()).add(created.id)); + this.toast.success(`API key “${trimmed}” was created.`); + }); + return; + } + const changes: { name?: string; role_id?: number } = {}; + if (trimmed !== existing.name) changes.name = trimmed; + if (role_id !== existing.role_id) changes.role_id = role_id!; + if (!Object.keys(changes).length) { + this.dialogError.set('Change the name or the role before saving.'); + return; + } + this.runSave(this.service.updateApiKey(existing.id, changes), () => { + this.toast.success(`API key “${trimmed}” was updated.`); + }); + } + + closeDialog(): void { + this.dialogRef?.close(); + } + + setActive(key: ApiKey, active: boolean): void { + if (this.busyId() !== null) return; + if (active) { + this.updateStatus(key, 'active'); + return; + } + this.confirm( + `Deactivate “${key.name}”? Servers that send this key will be rejected until you activate it again.`, + 'Deactivate' + ).subscribe((action) => { + if (action === 'yes') this.updateStatus(key, 'inactive'); + }); + } + + remove(key: ApiKey): void { + if (this.busyId() !== null) return; + this.confirm( + `Delete “${key.name}”? It stops working immediately: any server still using it will be rejected. This cannot be undone.`, + 'Delete' + ).subscribe((action) => { + if (action !== 'yes') return; + this.busyId.set(key.id); + this.service.deleteApiKey(key.id).subscribe({ + next: (response) => { + this.busyId.set(null); + if (response.hasError) { + this.toast.error(errorMessages(response, 'The API key could not be deleted.')); + return; + } + this.toast.success(`API key “${key.name}” was deleted.`); + // stay on the same page unless it is now empty + this.load(this.keys().length === 1 && this.page() > 1 ? this.page() - 1 : this.page()); + }, + error: (error: unknown) => { + this.busyId.set(null); + this.toast.error(this.failure(error, 'The API key could not be deleted.')); + }, + }); + }); + } + + private updateStatus(key: ApiKey, status: 'active' | 'inactive'): void { + this.busyId.set(key.id); + this.service.updateApiKey(key.id, { status }).subscribe({ + next: (response) => { + this.busyId.set(null); + if (response.hasError) { + this.toast.error(errorMessages(response, 'The API key could not be updated.')); + return; + } + this.toast.success(`API key “${key.name}” is now ${status}.`); + this.load(this.page()); + }, + error: (error: unknown) => { + this.busyId.set(null); + this.toast.error(this.failure(error, 'The API key could not be updated.')); + }, + }); + } + + private confirm(message: string, buttonText: string): Observable<'yes' | 'no' | undefined> { + const ref: MatDialogRef = this.dialog.open(ConfirmDialogComponent, { + panelClass: ['mat-dialog'], + }); + ref.componentRef.setInput('confirmationMessage', message); + ref.componentRef.setInput('confirmButtonText', buttonText); + ref.componentRef.setInput('confirmButtonColor', 'warn'); + return ref.afterClosed(); + } + + private failure(error: unknown, fallback: string): string { + return isForbidden(error) + ? 'Your role does not allow this action. Ask a workspace Owner or Admin.' + : errorMessages(error, fallback); + } + + private runSave( + request: Observable>, + onSuccess: (response: TeamResponse) => void + ): void { + const wasEditing = !!this.editing(); + this.saving.set(true); + this.dialogError.set(null); + if (this.dialogRef) this.dialogRef.disableClose = true; + this.saveRequest = request.subscribe({ + next: (response) => { + this.saving.set(false); + if (this.dialogRef) this.dialogRef.disableClose = false; + if (response.hasError) { + this.dialogError.set(errorMessages(response, 'The API key could not be saved.')); + return; + } + onSuccess(response); + this.closeDialog(); + this.load(wasEditing ? this.page() : 1); + }, + error: (error: unknown) => { + this.saving.set(false); + if (this.dialogRef) this.dialogRef.disableClose = false; + this.dialogError.set(this.failure(error, 'The API key could not be saved.')); + }, + }); + } + + private openDialog(): void { + this.dialogError.set(null); + this.dialogRef = this.dialog.open(this.keyDialog, { + panelClass: ['mat-dialog'], + hasBackdrop: true, + autoFocus: 'input', + restoreFocus: true, + }); + this.dialogRef + .afterClosed() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.dialogRef = null; + this.editing.set(null); + this.dialogError.set(null); + }); + } +} diff --git a/apps/36-blocks/src/app/panel/team/members/members.component.html b/apps/36-blocks/src/app/panel/team/members/members.component.html new file mode 100644 index 00000000..eb8ae75e --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/members/members.component.html @@ -0,0 +1,220 @@ +
+ +
+ +
+
+ +@if (rolesFailed()) { + +} + +@if (loading()) { +

Loading team members…

+} @else if (error(); as message) { + +} @else if (members().length === 0) { +
+ @if (hasFilter()) { +

No team members match this search.

+ + } @else { +

This workspace has no team members yet.

+ } +
+} @else { +

+ {{ total() }} {{ total() === 1 ? 'person' : 'people' }} · Page {{ page() }} of {{ totalPages() }} +

+
+ + + + + + + + + + + + + @for (member of members(); track member.id) { + @let status = memberStatus(member); + + + + + + + + } + +
+ Operators of the current workspace +
MemberRoleStatusAddedActions
+ {{ memberDisplayName(member) }} + @if (isMe(member)) { + You + } + @if (memberDisplayName(member) !== member.email) { + {{ member.email }} + } + {{ roleName(member) }} + {{ status.label }} + {{ member.client_user?.created_at | date: 'mediumDate' }} + @if (status.canResend) { + + } + + + +
+
+ +} + + +

Invite a team member

+ +

+ They will receive an email with an invitation link that is valid for {{ inviteExpiryMinutes }} minutes. The + role controls what they can do on this dashboard. +

+
+ + Email address + + @if (inviteForm.controls.email.touched && inviteForm.controls.email.invalid) { + Enter a valid email address + } + + + Role + + @for (role of assignable(); track role.id) { + {{ role.role_name }} · {{ role.permissions.length }} permissions + } + + See the Roles tab for exactly what each role allows. + @if (inviteForm.controls.role_id.touched && inviteForm.controls.role_id.invalid) { + Choose a role + } + +
+ @if (dialogError(); as message) { + + } +
+ + + + +
+ + + @if (roleTarget(); as target) { +

Change role

+ +

+ Choose the dashboard role for {{ memberDisplayName(target) }} in this workspace. +

+
+ + Role + + @for (role of assignable(); track role.id) { + {{ role.role_name }} · {{ role.permissions.length }} permissions + } + + @if (roleForm.controls.role_id.touched && roleForm.controls.role_id.invalid) { + Choose a role + } + +
+ @if (dialogError(); as message) { + + } +
+ + + + + } +
diff --git a/apps/36-blocks/src/app/panel/team/members/members.component.ts b/apps/36-blocks/src/app/panel/team/members/members.component.ts new file mode 100644 index 00000000..37cfb82f --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/members/members.component.ts @@ -0,0 +1,321 @@ +import { DatePipe } from '@angular/common'; +import { + ChangeDetectionStrategy, + Component, + DestroyRef, + OnDestroy, + OnInit, + TemplateRef, + ViewChild, + computed, + inject, + signal, +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Store, select } from '@ngrx/store'; +import { PrimeNgToastService } from '@proxy/ui/prime-ng-toast'; +import { Subscription } from 'rxjs'; +import { selectLogInData } from '../../../website/home/ngrx/selector/login.selector'; +import { ILogInFeatureStateWithRootState } from '../../../website/home/ngrx/store/login.state'; +import { + INVITE_EXPIRY_MINUTES, + OperatorRole, + TeamMember, + assignableRoles, + errorMessages, + isForbidden, + memberDisplayName, + memberStatus, +} from '../team.models'; +import { TeamService } from '../team.service'; + +/** + * Operators of the current workspace: invite people, see their invitation state and change their role. + * Server authorization is authoritative; the UI only prevents obviously invalid attempts (own role, Super admin). + */ +@Component({ + selector: 'proxy-team-members', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + DatePipe, + FormsModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressSpinnerModule, + MatSelectModule, + MatTooltipModule, + ], + templateUrl: './members.component.html', + styleUrl: '../team-tab.scss', +}) +export class MembersComponent implements OnInit, OnDestroy { + private readonly service = inject(TeamService); + private readonly dialog = inject(MatDialog); + private readonly toast = inject(PrimeNgToastService); + private readonly destroyRef = inject(DestroyRef); + private readonly store = inject>(Store); + private membersRequest?: Subscription; + private rolesRequest?: Subscription; + private saveRequest?: Subscription; + private dialogRef: MatDialogRef | null = null; + + @ViewChild('inviteDialog', { static: true }) inviteDialog!: TemplateRef; + @ViewChild('roleDialog', { static: true }) roleDialog!: TemplateRef; + + protected readonly inviteExpiryMinutes = INVITE_EXPIRY_MINUTES; + protected readonly memberStatus = memberStatus; + protected readonly memberDisplayName = memberDisplayName; + + searchText = ''; + private readonly appliedSearch = signal(''); + + readonly members = signal([]); + readonly loading = signal(false); + readonly error = signal(null); + readonly page = signal(1); + readonly totalPages = signal(0); + readonly total = signal(0); + + readonly roles = signal([]); + readonly rolesLoading = signal(false); + readonly rolesFailed = signal(false); + readonly assignable = computed(() => assignableRoles(this.roles())); + + readonly myEmail = signal(''); + readonly saving = signal(false); + readonly dialogError = signal(null); + readonly resendingId = signal(null); + readonly roleTarget = signal(null); + readonly hasFilter = computed(() => this.appliedSearch().length > 0); + + readonly inviteForm = new FormGroup({ + email: new FormControl('', [Validators.required, Validators.email, Validators.maxLength(254)]), + role_id: new FormControl(null, [Validators.required]), + }); + readonly roleForm = new FormGroup({ + role_id: new FormControl(null, [Validators.required]), + }); + + constructor() { + this.store + .pipe(select(selectLogInData), takeUntilDestroyed()) + .subscribe((user) => this.myEmail.set((user?.email ?? '').trim().toLowerCase())); + } + + ngOnInit(): void { + this.load(1); + this.loadRoles(); + } + + ngOnDestroy(): void { + this.membersRequest?.unsubscribe(); + this.rolesRequest?.unsubscribe(); + this.saveRequest?.unsubscribe(); + } + + isMe(member: TeamMember): boolean { + return !!this.myEmail() && member.email.trim().toLowerCase() === this.myEmail(); + } + + roleName(member: TeamMember): string { + return member.client_user?.role?.role_name ?? 'Not assigned'; + } + + applySearch(): void { + this.appliedSearch.set(this.searchText.trim()); + this.load(1); + } + + clearSearch(): void { + this.searchText = ''; + this.applySearch(); + } + + load(page: number): void { + this.membersRequest?.unsubscribe(); + this.loading.set(true); + this.error.set(null); + this.page.set(page); + this.membersRequest = this.service.getMembers({ name: this.appliedSearch(), pageNo: page }).subscribe({ + next: (response) => { + this.loading.set(false); + if (response.hasError || !response.data || !Array.isArray(response.data.data)) { + this.members.set([]); + this.error.set('Team members could not be loaded. Retry or contact an administrator.'); + return; + } + this.members.set(response.data.data); + this.total.set(response.data.totalEntityCount ?? response.data.data.length); + this.totalPages.set(response.data.totalPageCount ?? 1); + }, + error: (error: unknown) => { + this.loading.set(false); + this.members.set([]); + this.error.set( + isForbidden(error) + ? 'You do not have permission to view the team of this workspace. Ask a workspace Owner or Admin.' + : 'Team members could not be loaded. Check your connection and retry.' + ); + }, + }); + } + + loadRoles(refresh = false): void { + this.rolesRequest?.unsubscribe(); + this.rolesLoading.set(true); + this.rolesFailed.set(false); + this.rolesRequest = this.service.getRoles(refresh).subscribe({ + next: (response) => { + this.rolesLoading.set(false); + if (response.hasError || !Array.isArray(response.data?.data)) { + this.rolesFailed.set(true); + return; + } + this.roles.set(response.data.data); + }, + error: () => { + this.rolesLoading.set(false); + this.rolesFailed.set(true); + }, + }); + } + + openInvite(): void { + if (this.dialogRef) return; + const defaultRole = this.assignable().find((role) => role.role_name.trim().toLowerCase() === 'user'); + this.inviteForm.reset({ email: '', role_id: defaultRole?.id ?? null }); + this.openDialog(this.inviteDialog); + } + + submitInvite(): void { + if (this.saving()) return; + if (this.inviteForm.invalid) { + this.inviteForm.markAllAsTouched(); + return; + } + const { email, role_id } = this.inviteForm.getRawValue(); + this.runSave( + this.service.inviteMember({ email: email!.trim(), role_id: role_id! }), + `Invitation sent to ${email!.trim()}. The link is valid for ${INVITE_EXPIRY_MINUTES} minutes.`, + 'The invitation could not be sent. Check the email address and your permissions, then retry.' + ); + } + + resend(member: TeamMember): void { + const roleId = member.client_user?.role?.id; + if (this.resendingId() !== null || !roleId) return; + this.resendingId.set(member.id); + this.service.inviteMember({ email: member.email, role_id: roleId }).subscribe({ + next: (response) => { + this.resendingId.set(null); + if (response.hasError) { + this.toast.error(errorMessages(response, 'The invitation could not be sent again.')); + return; + } + this.toast.success(`Invitation sent again to ${member.email}.`); + this.load(this.page()); + }, + error: (error: unknown) => { + this.resendingId.set(null); + this.toast.error(errorMessages(error, 'The invitation could not be sent again.')); + }, + }); + } + + openRoleChange(member: TeamMember): void { + if (this.dialogRef || this.isMe(member)) return; + this.roleTarget.set(member); + const current = member.client_user?.role?.id ?? null; + this.roleForm.reset({ role_id: this.assignable().some((role) => role.id === current) ? current : null }); + this.openDialog(this.roleDialog); + } + + submitRoleChange(): void { + const target = this.roleTarget(); + if (!target || this.saving()) return; + if (this.roleForm.invalid) { + this.roleForm.markAllAsTouched(); + return; + } + const roleId = this.roleForm.getRawValue().role_id!; + if (roleId === target.client_user?.role?.id) { + this.dialogError.set('That is already this person’s role.'); + return; + } + this.runSave( + this.service.updateMemberRole({ user_id: target.id, role_id: roleId }), + `${memberDisplayName(target)}’s role was updated.`, + 'The role could not be changed. You may not have permission to change roles in this workspace.' + ); + } + + closeDialog(): void { + this.dialogRef?.close(); + } + + private runSave( + request: ReturnType, + successMessage: string, + failureMessage: string + ): void { + this.saving.set(true); + this.dialogError.set(null); + if (this.dialogRef) this.dialogRef.disableClose = true; + this.saveRequest = request.subscribe({ + next: (response) => { + this.finishSave(); + if (response.hasError) { + this.dialogError.set(errorMessages(response, failureMessage)); + return; + } + this.toast.success(successMessage); + this.closeDialog(); + this.load(this.page()); + }, + error: (error: unknown) => { + this.finishSave(); + this.dialogError.set( + isForbidden(error) + ? 'Your role does not allow this action. Ask a workspace Owner or Admin.' + : errorMessages(error, failureMessage) + ); + }, + }); + } + + private finishSave(): void { + this.saving.set(false); + if (this.dialogRef) this.dialogRef.disableClose = false; + } + + private openDialog(template: TemplateRef): void { + this.dialogError.set(null); + this.dialogRef = this.dialog.open(template, { + panelClass: ['mat-dialog'], + hasBackdrop: true, + autoFocus: 'input', + restoreFocus: true, + }); + this.dialogRef + .afterClosed() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.dialogRef = null; + this.roleTarget.set(null); + this.dialogError.set(null); + }); + } +} diff --git a/apps/36-blocks/src/app/panel/team/roles/roles.component.html b/apps/36-blocks/src/app/panel/team/roles/roles.component.html new file mode 100644 index 00000000..26ba48e7 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/roles/roles.component.html @@ -0,0 +1,61 @@ +
+

+ Dashboard roles define what an operator can do here. They are the same for every workspace. + Assign them from Members or when creating an + API key. Roles for the end users of an application are configured per block + under People → Management. +

+
+ +@if (loading()) { +

Loading roles…

+} @else if (error(); as message) { + +} @else if (roles().length === 0) { +

No roles were returned.

+} @else { + @let view = matrix(); +
+ + + + + + @for (role of view.roles; track role.id) { + + } + + + + @for (row of view.rows; track row.permission) { + + + @for (role of view.roles; track role.id) { + + } + + } + +
+ Permissions granted to each dashboard role +
Permission + {{ role.role_name }} + @if (role.id === superAdminId) { + Platform role; cannot be assigned here + } @else { + {{ role.permissions.length }} permissions + } +
{{ row.permission }} + @if (row.grants[role.id]) { + + Allowed + } @else { + + Not allowed + } +
+
+} diff --git a/apps/36-blocks/src/app/panel/team/roles/roles.component.ts b/apps/36-blocks/src/app/panel/team/roles/roles.component.ts new file mode 100644 index 00000000..8ee23243 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/roles/roles.component.ts @@ -0,0 +1,58 @@ +import { ChangeDetectionStrategy, Component, OnDestroy, OnInit, computed, inject, signal } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { Subscription } from 'rxjs'; +import { OperatorRole, SUPER_ADMIN_ROLE_ID, buildPermissionMatrix, isForbidden } from '../team.models'; +import { TeamService } from '../team.service'; + +/** Read-only "what can each dashboard role do" reference. Roles are managed by the platform, not per workspace. */ +@Component({ + selector: 'proxy-team-roles', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [RouterLink, MatButtonModule, MatIconModule], + templateUrl: './roles.component.html', + styleUrl: '../team-tab.scss', +}) +export class RolesComponent implements OnInit, OnDestroy { + private readonly service = inject(TeamService); + private request?: Subscription; + + protected readonly superAdminId = SUPER_ADMIN_ROLE_ID; + readonly roles = signal([]); + readonly loading = signal(false); + readonly error = signal(null); + readonly matrix = computed(() => buildPermissionMatrix(this.roles())); + + ngOnInit(): void { + this.load(); + } + + ngOnDestroy(): void { + this.request?.unsubscribe(); + } + + load(refresh = false): void { + this.request?.unsubscribe(); + this.loading.set(true); + this.error.set(null); + this.request = this.service.getRoles(refresh).subscribe({ + next: (response) => { + this.loading.set(false); + if (response.hasError || !Array.isArray(response.data?.data)) { + this.error.set('Roles could not be loaded. Retry or contact an administrator.'); + return; + } + this.roles.set(response.data.data); + }, + error: (error: unknown) => { + this.loading.set(false); + this.error.set( + isForbidden(error) + ? 'You do not have permission to view roles in this workspace.' + : 'Roles could not be loaded. Check your connection and retry.' + ); + }, + }); + } +} diff --git a/apps/36-blocks/src/app/panel/team/team-tab.scss b/apps/36-blocks/src/app/panel/team/team-tab.scss new file mode 100644 index 00000000..5d7cab20 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team-tab.scss @@ -0,0 +1,172 @@ +/* Styles shared by the Members, Roles and API keys tabs. */ +:host { + display: block; +} +.tab-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.75rem 1rem; + margin-bottom: 1rem; +} +.tab-toolbar__lead { + max-width: 70ch; + margin: 0; +} +.tab-toolbar__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; +} +.search-form { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + mat-form-field { + min-width: 260px; + } +} +.table-scroll { + overflow-x: auto; + border: 1px solid var(--mat-sys-outline-variant, #888); + border-radius: 0.5rem; +} +table.team-table { + border-collapse: collapse; + width: 100%; + text-align: left; + th, + td { + padding: 0.75rem 1rem; + vertical-align: middle; + border-bottom: 1px solid var(--mat-sys-outline-variant, #888); + } + thead th { + white-space: nowrap; + font-weight: 600; + } + tbody tr:last-child td { + border-bottom: 0; + } + small { + display: block; + margin-top: 0.2rem; + opacity: 0.75; + } + .actions { + text-align: right; + white-space: nowrap; + > * + * { + margin-left: 0.5rem; + } + } +} +.row-inactive td:not(.actions) { + opacity: 0.65; +} +.you-badge { + margin-left: 0.4rem; + padding: 0.05rem 0.45rem; + border-radius: 999px; + font-size: 0.7rem; + font-weight: 600; + border: 1px solid var(--mat-sys-outline-variant, #888); +} +.status-pill { + display: inline-flex; + align-items: center; + gap: 0.4rem; + padding: 0.1rem 0.65rem; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + &::before { + content: ''; + width: 7px; + height: 7px; + border-radius: 50%; + background: currentColor; + } + &--good { + color: #15803d; + background: color-mix(in srgb, #22c55e 18%, transparent); + } + &--wait { + color: #a16207; + background: color-mix(in srgb, #eab308 22%, transparent); + } + &--bad { + color: #b91c1c; + background: color-mix(in srgb, #ef4444 16%, transparent); + } + &--muted { + color: #6b7280; + background: color-mix(in srgb, #9ca3af 22%, transparent); + } +} +.state-block { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; + padding: 1.25rem; + border: 1px solid var(--mat-sys-outline-variant, #888); + border-radius: 0.5rem; + p { + margin: 0; + } +} +.pagination { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; + margin-top: 1rem; +} +.banner { + display: flex; + gap: 0.5rem; + align-items: flex-start; + padding: 0.75rem 1rem; + margin: 0 0 1rem; + border-radius: 0.5rem; + border: 1px solid var(--mat-sys-outline-variant, #888); + font-size: 0.875rem; + &--warn { + border-color: #eab308; + background: color-mix(in srgb, #eab308 12%, transparent); + } + &--ok { + border-color: #22c55e; + background: color-mix(in srgb, #22c55e 12%, transparent); + } +} +.dialog-error { + margin: 0.5rem 0 0; + color: var(--mat-sys-error, #b91c1c); + font-size: 0.875rem; +} +.dialog-form { + display: flex; + flex-direction: column; + gap: 0.25rem; + min-width: min(420px, 80vw); +} +.mono { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 0.8125rem; + letter-spacing: 0.02em; + word-break: break-all; +} +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} diff --git a/apps/36-blocks/src/app/panel/team/team.component.html b/apps/36-blocks/src/app/panel/team/team.component.html new file mode 100644 index 00000000..ac66fdfd --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.component.html @@ -0,0 +1,29 @@ +
+
+
+ WHO CAN OPERATE THIS WORKSPACE +

Team & access

+

+ Manage the people who sign in to this dashboard, what each role allows, and the API keys your servers + use. These are operators of the workspace, not the end users of your applications (find + those under People). +

+
+
+ + + + + +
diff --git a/apps/36-blocks/src/app/panel/team/team.component.scss b/apps/36-blocks/src/app/panel/team/team.component.scss new file mode 100644 index 00000000..c399e2f3 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.component.scss @@ -0,0 +1,18 @@ +:host { + display: block; +} +.team-page { + max-width: 1500px; + margin: auto; +} +h1 { + font-size: 1.75rem; + margin-bottom: 0.5rem; +} +header p { + max-width: 80ch; +} +.team-panel { + display: block; + padding-top: 1.25rem; +} diff --git a/apps/36-blocks/src/app/panel/team/team.component.ts b/apps/36-blocks/src/app/panel/team/team.component.ts new file mode 100644 index 00000000..7afe5cf9 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.component.ts @@ -0,0 +1,19 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; +import { MatTabsModule } from '@angular/material/tabs'; + +/** Shell for the operator "Team & access" area: members, roles and API keys of the current workspace. */ +@Component({ + selector: 'proxy-team', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [RouterLink, RouterLinkActive, RouterOutlet, MatTabsModule], + templateUrl: './team.component.html', + styleUrl: './team.component.scss', +}) +export class TeamComponent { + protected readonly tabs = [ + { path: 'members', label: 'Members' }, + { path: 'roles', label: 'Roles' }, + { path: 'api-keys', label: 'API keys' }, + ]; +} diff --git a/apps/36-blocks/src/app/panel/team/team.models.ts b/apps/36-blocks/src/app/panel/team/team.models.ts new file mode 100644 index 00000000..4745a4b6 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.models.ts @@ -0,0 +1,219 @@ +/** + * Operator team & access models. + * + * "Operators" are the people who sign in to this dashboard (the `User`/`ClientUser`/`Role` records of the + * backend). They are NOT the end users of a connected application (see People) and the roles here are NOT + * the per-block end-user roles. Keep that distinction visible in every label. + */ + +/** Seeded dashboard role ids. The backend refuses to assign Super admin through invite / role change / API keys. */ +export const SUPER_ADMIN_ROLE_ID = 1; +/** Invitation links expire after this many minutes (backend `InviteRequest::INVITE_EXPIRY_MINUTES`). */ +export const INVITE_EXPIRY_MINUTES = 15; +export const TEAM_PAGE_SIZE = 25; + +export const API_KEY_NAME_MIN = 3; +export const API_KEY_NAME_MAX = 50; +/** Mirrors the server rule so mistakes are caught before a round trip. The server stays authoritative. */ +export const API_KEY_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_]+$/; + +export const WORKSPACE_NAME_MIN = 3; +export const WORKSPACE_NAME_MAX = 50; +export const WORKSPACE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_\s]+$/; + +export interface OperatorRolePermission { + permission: string; +} + +export interface OperatorRole { + id: number; + role_name: string; + permissions: OperatorRolePermission[]; +} + +export type InviteStatus = 'pending' | 'accepted' | 'rejected'; +export type MembershipStatus = 'enabled' | 'disabled'; + +export interface TeamMember { + id: number; + email: string; + fname: string | null; + lname: string | null; + mobile: string | null; + is_registered: boolean; + stage: string | null; + created_at: string; + client_user?: { + id: number; + status: MembershipStatus; + invite_status: InviteStatus; + created_at: string; + updated_at: string; + role?: { id: number; role_name: string } | null; + } | null; +} + +export type ApiKeyStatus = 'active' | 'inactive'; + +export interface ApiKeyActor { + id: number; + name: string | null; + email: string | null; +} + +export interface ApiKey { + id: number; + name: string; + /** The backend returns the full secret on every read; treat it as sensitive. */ + authkey: string; + role_id: number; + status: ApiKeyStatus; + created_at: string; + updated_at: string; + created_by?: ApiKeyActor | null; + updated_by?: ApiKeyActor | null; +} + +export interface InviteMemberRequest { + email: string; + role_id: number; +} + +export interface UpdateMemberRoleRequest { + user_id: number; + role_id: number; +} + +export interface CreateApiKeyRequest { + name: string; + role_id: number; +} + +export interface UpdateApiKeyRequest { + name?: string; + role_id?: number; + status?: ApiKeyStatus; +} + +export interface CreateWorkspaceRequest { + name: string; +} + +export function memberDisplayName(member: Pick): string { + const name = [member.fname, member.lname] + .map((part) => (part ?? '').trim()) + .filter(Boolean) + .join(' '); + return name || member.email; +} + +export type MemberStatusKey = 'active' | 'disabled' | 'invited' | 'invite-expired' | 'declined' | 'unknown'; + +export interface MemberStatus { + key: MemberStatusKey; + label: string; + /** True when the invitation can be sent again (declined or expired). */ + canResend: boolean; +} + +/** + * Collapses the membership `status` + `invite_status` pair (plus invite age) into one label. + * A pending invite older than the expiry window is shown as expired because the accept link no longer works. + */ +export function memberStatus(member: TeamMember, now: number = Date.now()): MemberStatus { + const membership = member.client_user; + if (!membership) return { key: 'unknown', label: 'Unknown', canResend: false }; + if (membership.invite_status === 'rejected') { + return { key: 'declined', label: 'Invitation declined', canResend: true }; + } + if (membership.invite_status === 'pending') { + const sentAt = Date.parse(membership.updated_at); + const expired = Number.isFinite(sentAt) && now - sentAt > INVITE_EXPIRY_MINUTES * 60_000; + return expired + ? { key: 'invite-expired', label: 'Invitation expired', canResend: true } + : { key: 'invited', label: 'Invitation pending', canResend: false }; + } + return membership.status === 'enabled' + ? { key: 'active', label: 'Active', canResend: false } + : { key: 'disabled', label: 'Disabled', canResend: false }; +} + +/** Roles an operator may be given through invite, role change or an API key (Super admin is excluded server-side). */ +export function assignableRoles(roles: OperatorRole[]): OperatorRole[] { + return roles.filter((role) => role.id !== SUPER_ADMIN_ROLE_ID).sort((a, b) => a.id - b.id); +} + +export interface PermissionMatrixRow { + permission: string; + grants: Record; +} + +export interface PermissionMatrix { + roles: OperatorRole[]; + rows: PermissionMatrixRow[]; +} + +/** One row per permission, one column per role (lowest id first), so "what can this role do" reads across. */ +export function buildPermissionMatrix(roles: OperatorRole[]): PermissionMatrix { + const ordered = [...roles].sort((a, b) => a.id - b.id); + const names = new Set(); + for (const role of ordered) { + for (const item of role.permissions ?? []) names.add(item.permission); + } + const rows = [...names] + .sort((a, b) => a.localeCompare(b)) + .map((permission) => ({ + permission, + grants: Object.fromEntries( + ordered.map((role) => [ + role.id, + (role.permissions ?? []).some((item) => item.permission === permission), + ]) + ) as Record, + })); + return { roles: ordered, rows }; +} + +/** Shows only the end of a secret. The value is never logged or stored by the UI. */ +export function maskSecret(value: string, visible = 4): string { + if (!value) return ''; + return `••••••••••••${value.length > visible * 2 ? value.slice(-visible) : ''}`; +} + +/** The shared interceptor uses errorCode; direct HttpClient failures retain status. */ +export function isForbidden(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + (('status' in error && error.status === 403) || ('errorCode' in error && error.errorCode === 403)) + ); +} + +function collectMessages(value: unknown, out: string[], depth = 0): void { + if (depth > 4 || value === null || value === undefined) return; + if (typeof value === 'string') { + if (value.trim()) out.push(value.trim()); + } else if (Array.isArray(value)) { + value.forEach((item) => collectMessages(item, out, depth + 1)); + } else if (typeof value === 'object') { + Object.values(value as Record).forEach((item) => collectMessages(item, out, depth + 1)); + } +} + +/** + * Pulls readable validation/denial messages out of the several error envelopes the API and the shared + * interceptor produce (`{errors}`, `{errors: {field: [..]}}`, `{data: {message}}`, plain strings). + */ +export function errorMessages(error: unknown, fallback: string): string { + const messages: string[] = []; + if (typeof error === 'string') { + collectMessages(error, messages); + } else if (typeof error === 'object' && error !== null) { + const body = error as Record; + collectMessages(body['errors'], messages); + if (!messages.length) + collectMessages((body['data'] as Record | undefined)?.['message'], messages); + if (!messages.length) collectMessages(body['message'], messages); + } + return [...new Set(messages)].join(' ') || fallback; +} diff --git a/apps/36-blocks/src/app/panel/team/team.routes.ts b/apps/36-blocks/src/app/panel/team/team.routes.ts new file mode 100644 index 00000000..dd184c9d --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.routes.ts @@ -0,0 +1,23 @@ +import { Route } from '@angular/router'; + +export const teamRoutes: Route[] = [ + { + path: '', + loadComponent: () => import('./team.component').then((c) => c.TeamComponent), + children: [ + { path: '', redirectTo: 'members', pathMatch: 'full' }, + { + path: 'members', + loadComponent: () => import('./members/members.component').then((c) => c.MembersComponent), + }, + { + path: 'roles', + loadComponent: () => import('./roles/roles.component').then((c) => c.RolesComponent), + }, + { + path: 'api-keys', + loadComponent: () => import('./api-keys/api-keys.component').then((c) => c.ApiKeysComponent), + }, + ], + }, +]; diff --git a/apps/36-blocks/src/app/panel/team/team.service.ts b/apps/36-blocks/src/app/panel/team/team.service.ts new file mode 100644 index 00000000..6ce79dfe --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.service.ts @@ -0,0 +1,80 @@ +import { Inject, Injectable, inject } from '@angular/core'; +import { BaseResponse, IPaginatedResponse, ProxyBaseUrls } from '@proxy/models/root-models'; +import { HttpWrapperService } from '@proxy/services/httpWrapper'; +import { Observable, shareReplay, tap } from 'rxjs'; +import { + ApiKey, + CreateApiKeyRequest, + InviteMemberRequest, + OperatorRole, + TEAM_PAGE_SIZE, + TeamMember, + UpdateApiKeyRequest, + UpdateMemberRoleRequest, +} from './team.models'; +import { TeamUrls } from './team.urls'; + +export type TeamResponse = BaseResponse; +export type TeamPage = TeamResponse>; + +@Injectable({ providedIn: 'root' }) +export class TeamService { + private readonly http = inject(HttpWrapperService); + private roles$?: Observable>; + + constructor(@Inject(ProxyBaseUrls.BaseURL) private readonly baseUrl: string) {} + + getMembers(params: { name?: string; pageNo: number }): Observable> { + const query: Record = { pageNo: params.pageNo, itemsPerPage: TEAM_PAGE_SIZE }; + if (params.name?.trim()) query['name'] = params.name.trim(); + return this.http.get>(TeamUrls.members(this.baseUrl), query); + } + + inviteMember(body: InviteMemberRequest): Observable> { + return this.http.post>(TeamUrls.invite(this.baseUrl), body); + } + + updateMemberRole(body: UpdateMemberRoleRequest): Observable> { + return this.http.put>(TeamUrls.updateMemberRole(this.baseUrl), body); + } + + /** + * Roles are global (not per workspace) and rarely change, so one request is shared by the tabs of a visit. + * A failed request is not cached; pass `refresh` to force a new one (retry). + */ + getRoles(refresh = false): Observable> { + if (!this.roles$ || refresh) { + const request$ = this.http + .get>(TeamUrls.rolePermissions(this.baseUrl), { itemsPerPage: 100, pageNo: 1 }) + .pipe( + tap({ + error: () => { + if (this.roles$ === request$) this.roles$ = undefined; + }, + }), + shareReplay({ bufferSize: 1, refCount: false }) + ); + this.roles$ = request$; + } + return this.roles$; + } + + getApiKeys(pageNo: number): Observable> { + return this.http.get>(TeamUrls.apiKeys(this.baseUrl), { + pageNo, + itemsPerPage: TEAM_PAGE_SIZE, + }); + } + + createApiKey(body: CreateApiKeyRequest): Observable> { + return this.http.post>(TeamUrls.apiKeys(this.baseUrl), body); + } + + updateApiKey(id: number, body: UpdateApiKeyRequest): Observable> { + return this.http.put>(TeamUrls.apiKey(this.baseUrl, id), body); + } + + deleteApiKey(id: number): Observable> { + return this.http.delete>(TeamUrls.apiKey(this.baseUrl, id)); + } +} diff --git a/apps/36-blocks/src/app/panel/team/team.urls.ts b/apps/36-blocks/src/app/panel/team/team.urls.ts new file mode 100644 index 00000000..efa25ef1 --- /dev/null +++ b/apps/36-blocks/src/app/panel/team/team.urls.ts @@ -0,0 +1,10 @@ +import { createUrl } from '@proxy/service'; + +export const TeamUrls = { + members: (baseUrl: string) => createUrl(baseUrl, 'users'), + invite: (baseUrl: string) => createUrl(baseUrl, 'invite'), + updateMemberRole: (baseUrl: string) => createUrl(baseUrl, 'updateUserRole'), + rolePermissions: (baseUrl: string) => createUrl(baseUrl, 'rolePermissions'), + apiKeys: (baseUrl: string) => createUrl(baseUrl, 'authentications'), + apiKey: (baseUrl: string, id: number) => createUrl(baseUrl, `authentications/${encodeURIComponent(String(id))}`), +}; diff --git a/apps/36-blocks/src/review/fixtures.ts b/apps/36-blocks/src/review/fixtures.ts index 777d9a2d..dd8d647a 100644 --- a/apps/36-blocks/src/review/fixtures.ts +++ b/apps/36-blocks/src/review/fixtures.ts @@ -81,7 +81,76 @@ const operations = [ audit_context: null, }, ]; +const permissionNames = [ + 'View client users', + 'Create client user', + 'Update user role', + 'View authkeys', + 'Create authkey', + 'Edit authkey', + 'Delete authkey', +]; +const operatorRoles = [ + { id: 4, role_name: 'User', permissions: permissionNames.slice(0, 1).concat(permissionNames.slice(3, 4)) }, + { id: 3, role_name: 'Admin', permissions: permissionNames.slice(0, 6) }, + { id: 2, role_name: 'Owner', permissions: permissionNames }, + { id: 1, role_name: 'Super admin', permissions: permissionNames }, +].map((role) => ({ ...role, permissions: role.permissions.map((permission) => ({ permission })) })); +const teamMember = ( + id: number, + fname: string, + lname: string, + role: { id: number; role_name: string }, + invite_status: string, + updated_at: string +) => ({ + id, + email: `${fname.toLowerCase()}@example.test`, + fname, + lname, + mobile: null, + is_registered: invite_status === 'accepted', + stage: invite_status === 'accepted' ? 'onboarded' : 'invited', + created_at: '2026-10-20T08:00:00Z', + client_user: { + id: 100 + id, + status: invite_status === 'accepted' ? 'enabled' : 'disabled', + invite_status, + created_at: '2026-10-20T08:00:00Z', + updated_at, + role, + }, +}); +const teamMembers = [ + teamMember(2, 'Review', 'Admin', { id: 3, role_name: 'Admin' }, 'accepted', '2026-10-20T08:00:00Z'), + teamMember(3, 'Morgan', 'Chen', { id: 4, role_name: 'User' }, 'accepted', '2026-10-21T08:00:00Z'), + teamMember(4, 'Jordan', '', { id: 4, role_name: 'User' }, 'pending', '2020-01-01T00:00:00Z'), + teamMember(5, 'Casey', 'Lopez', { id: 3, role_name: 'Admin' }, 'rejected', '2026-10-22T08:00:00Z'), +]; +const apiKeys = [ + { id: 21, name: 'default', authkey: '0123456789abcdef0123456789abcdef', role_id: 2, status: 'active' }, + { id: 22, name: 'backend_sync', authkey: 'fedcba9876543210fedcba9876543210', role_id: 3, status: 'inactive' }, +].map((key) => ({ + ...key, + created_at: '2026-10-20T08:00:00Z', + updated_at: '2026-10-20T08:00:00Z', + created_by: { id: 2, name: 'Review Admin', email: 'admin@example.test' }, + updated_by: { id: 2, name: 'Review Admin', email: 'admin@example.test' }, +})); export function reviewData(path: string, params: HttpParams): any { + if (path === 'users') { + const term = params.get('name')?.toLowerCase(); + return page( + teamMembers.filter( + (member) => + !term || + `${member.fname} ${member.lname}`.toLowerCase().includes(term) || + member.email.toLowerCase().includes(term) + ) + ); + } + if (path === 'rolePermissions') return page(operatorRoles); + if (path === 'authentications') return page(apiKeys); if (path === 'getClientSettings') return { client, role: { id: 3, role_name: 'Admin' } }; if (path === 'clients') return page([client]); if (path === 'features') diff --git a/libs/services/proxy/root/src/lib/services-proxy-root.module.ts b/libs/services/proxy/root/src/lib/services-proxy-root.module.ts index e1730370..3df38816 100644 --- a/libs/services/proxy/root/src/lib/services-proxy-root.module.ts +++ b/libs/services/proxy/root/src/lib/services-proxy-root.module.ts @@ -33,6 +33,11 @@ export class RootService { ); } + // Create a workspace (client) owned by the signed-in user. The API also switches the session into it. + public createClient(body: { name: string }): Observable> { + return this.http.post>(RootUrls.createClient(this.baseUrl), body); + } + public generateToken(params: { [key: string]: any } = {}): Observable> { return this.http.get>(RootUrls.generateToken(this.baseUrl), params); } diff --git a/libs/urls/root-urls/src/index.ts b/libs/urls/root-urls/src/index.ts index 7679db6e..9b1bec1d 100644 --- a/libs/urls/root-urls/src/index.ts +++ b/libs/urls/root-urls/src/index.ts @@ -3,6 +3,7 @@ import { createUrl } from '@proxy/service'; export const RootUrls = { getClientSettings: (baseUrl) => createUrl(baseUrl, 'getClientSettings'), getClients: (baseUrl) => createUrl(baseUrl, 'clients'), + createClient: (baseUrl) => createUrl(baseUrl, 'clients'), switchClient: (baseUrl) => createUrl(baseUrl, 'switchclient'), generateToken: (baseUrl) => createUrl(baseUrl, 'generateToken'), getProject: (baseUrl) => createUrl(baseUrl, 'projects'), diff --git a/tools/tests/team-access.test.cjs b/tools/tests/team-access.test.cjs new file mode 100644 index 00000000..b6c1f823 --- /dev/null +++ b/tools/tests/team-access.test.cjs @@ -0,0 +1,435 @@ +// Run: node --test tools/tests/team-access.test.cjs +// Exercises the actual Team & access TypeScript (models, service, members and API-key components) with RxJS. +// Angular DI, signals and forms are hosted locally. Browser rendering and backend authorization are separate checks. +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const path = require('node:path'); +const { test } = require('node:test'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { Subject, of, throwError } = require('rxjs'); + +function load(relative, dependencies = {}) { + const source = readFileSync(path.resolve(__dirname, '../..', relative), 'utf8'); + const compiled = ts.transpileModule(source, { + compilerOptions: { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.CommonJS, + experimentalDecorators: true, + }, + }).outputText; + const module = { exports: {} }; + vm.runInNewContext(compiled, { + module, + exports: module.exports, + URL, + Set, + Date, + require: (name) => { + if (Object.hasOwn(dependencies, name)) return dependencies[name]; + if (name === 'rxjs') return require(name); + if (name.startsWith('@angular/') || name.startsWith('@proxy/') || name.startsWith('@ngrx/')) return {}; + throw new Error(`Unexpected runtime dependency: ${name}`); + }, + }); + return module.exports; +} + +const team = 'apps/36-blocks/src/app/panel/team'; +const models = load(`${team}/team.models.ts`); + +const member = (over = {}) => ({ + id: 3, + email: 'morgan@example.test', + fname: 'Morgan', + lname: 'Chen', + client_user: { + id: 1, + status: 'enabled', + invite_status: 'accepted', + updated_at: '2026-10-20T08:00:00Z', + role: { id: 4, role_name: 'User' }, + }, + ...over, +}); + +test('member status separates active, pending, expired, declined and disabled', () => { + const now = Date.parse('2026-10-20T08:10:00Z'); + const withInvite = (invite_status, status, updated_at) => + member({ client_user: { ...member().client_user, invite_status, status, updated_at } }); + assert.equal(models.memberStatus(member(), now).key, 'active'); + const pending = models.memberStatus(withInvite('pending', 'disabled', '2026-10-20T08:00:00Z'), now); + assert.equal(pending.key, 'invited'); + assert.equal(pending.canResend, false); + const expired = models.memberStatus(withInvite('pending', 'disabled', '2026-10-20T07:00:00Z'), now); + assert.equal(expired.key, 'invite-expired'); + assert.equal(expired.canResend, true); + const declined = models.memberStatus(withInvite('rejected', 'disabled', '2026-10-20T08:00:00Z'), now); + assert.equal(declined.key, 'declined'); + assert.equal(declined.canResend, true); + assert.equal(models.memberStatus(withInvite('accepted', 'disabled', '2026-10-20T08:00:00Z'), now).key, 'disabled'); + assert.equal(models.memberStatus(member({ client_user: null }), now).key, 'unknown'); +}); + +test('display name falls back to the email; Super admin is never assignable', () => { + assert.equal(models.memberDisplayName(member()), 'Morgan Chen'); + assert.equal(models.memberDisplayName(member({ fname: null, lname: ' ' })), 'morgan@example.test'); + const roles = [ + { id: 4, role_name: 'User', permissions: [] }, + { id: 1, role_name: 'Super admin', permissions: [] }, + { id: 2, role_name: 'Owner', permissions: [] }, + ]; + assert.deepEqual([...models.assignableRoles(roles).map((role) => role.id)], [2, 4]); +}); + +test('permission matrix has one row per permission and one column per role', () => { + const roles = [ + { id: 4, role_name: 'User', permissions: [{ permission: 'View authkeys' }] }, + { id: 2, role_name: 'Owner', permissions: [{ permission: 'View authkeys' }, { permission: 'Create authkey' }] }, + ]; + const matrix = models.buildPermissionMatrix(roles); + assert.deepEqual([...matrix.roles.map((role) => role.id)], [2, 4]); + assert.deepEqual([...matrix.rows.map((row) => row.permission)], ['Create authkey', 'View authkeys']); + assert.deepEqual({ ...matrix.rows[0].grants }, { 2: true, 4: false }); + assert.deepEqual({ ...matrix.rows[1].grants }, { 2: true, 4: true }); +}); + +test('secrets are masked and never reveal more than the last four characters', () => { + const secret = '0123456789abcdef0123456789abcdef'; + const masked = models.maskSecret(secret); + assert.equal(masked.endsWith('cdef'), true); + assert.equal(masked.includes('0123'), false); + assert.equal(models.maskSecret('abc'), '••••••••••••'); + assert.equal(models.maskSecret(''), ''); +}); + +test('name rules match the server rules', () => { + assert.equal(models.API_KEY_NAME_PATTERN.test('backend_sync'), true); + assert.equal(models.API_KEY_NAME_PATTERN.test('_leading'), false); + assert.equal(models.API_KEY_NAME_PATTERN.test('has space'), false); + assert.equal(models.WORKSPACE_NAME_PATTERN.test('Acme Corp 2'), true); + assert.equal(models.WORKSPACE_NAME_PATTERN.test(' Acme'), false); +}); + +test('error messages read every envelope the API and interceptor produce', () => { + assert.equal(models.errorMessages({ errors: { name: ['Taken.'], role_id: ['Invalid.'] } }, 'x'), 'Taken. Invalid.'); + assert.equal(models.errorMessages({ errors: ['One'] }, 'x'), 'One'); + assert.equal(models.errorMessages({ data: { message: 'Already pending.' } }, 'x'), 'Already pending.'); + assert.equal(models.errorMessages('Plain', 'x'), 'Plain'); + assert.equal(models.errorMessages(null, 'fallback'), 'fallback'); + assert.equal(models.errorMessages({ errors: [] }, 'fallback'), 'fallback'); + assert.equal(models.isForbidden({ errorCode: 403 }), true); + assert.equal(models.isForbidden({ status: 403 }), true); + assert.equal(models.isForbidden({ errorCode: 422 }), false); +}); + +// ---- service ------------------------------------------------------------------------------------------------- +const createUrl = (base, p) => `${base}/${p}`; +const urls = load(`${team}/team.urls.ts`, { '@proxy/service': { createUrl } }).TeamUrls; + +function createService(http) { + const { TeamService } = load(`${team}/team.service.ts`, { + '@angular/core': { Inject: () => () => {}, Injectable: () => (t) => t, inject: () => http }, + '@proxy/models/root-models': { ProxyBaseUrls: { BaseURL: 'BASE' } }, + './team.models': models, + './team.urls': { TeamUrls: urls }, + }); + return new TeamService('https://api.test'); +} + +test('service sends the documented routes, bodies and paging', () => { + const calls = []; + const record = + (method) => + (url, ...rest) => { + calls.push({ method, url, rest }); + return of({ hasError: false, data: {} }); + }; + const service = createService({ + get: record('get'), + post: record('post'), + put: record('put'), + delete: record('delete'), + }); + service.getMembers({ name: ' jane ', pageNo: 2 }).subscribe(); + service.getMembers({ pageNo: 1 }).subscribe(); + service.inviteMember({ email: 'a@b.test', role_id: 4 }).subscribe(); + service.updateMemberRole({ user_id: 9, role_id: 3 }).subscribe(); + service.getApiKeys(3).subscribe(); + service.createApiKey({ name: 'abc', role_id: 3 }).subscribe(); + service.updateApiKey(21, { status: 'inactive' }).subscribe(); + service.deleteApiKey(21).subscribe(); + const [members, noName, invite, role, keys, create, update, del] = calls; + assert.equal(members.url, 'https://api.test/users'); + assert.deepEqual({ ...members.rest[0] }, { pageNo: 2, itemsPerPage: 25, name: 'jane' }); + assert.equal(Object.hasOwn(noName.rest[0], 'name'), false); + assert.equal(invite.method, 'post'); + assert.equal(invite.url, 'https://api.test/invite'); + assert.deepEqual({ ...invite.rest[0] }, { email: 'a@b.test', role_id: 4 }); + assert.equal(role.method, 'put'); + assert.equal(role.url, 'https://api.test/updateUserRole'); + assert.equal(keys.url, 'https://api.test/authentications'); + assert.equal(keys.rest[0].pageNo, 3); + assert.equal(create.method, 'post'); + assert.equal(update.url, 'https://api.test/authentications/21'); + assert.deepEqual({ ...update.rest[0] }, { status: 'inactive' }); + assert.equal(del.method, 'delete'); + assert.equal(del.url, 'https://api.test/authentications/21'); +}); + +test('roles are fetched once per visit, failures are not cached, refresh forces a new request', () => { + let count = 0; + let fail = true; + const service = createService({ + get: () => { + count++; + return fail ? throwError(() => ({ errorCode: 500 })) : of({ hasError: false, data: { data: [] } }); + }, + }); + service.getRoles().subscribe({ error: () => {} }); + assert.equal(count, 1); + fail = false; + service.getRoles().subscribe(); + assert.equal(count, 2, 'a failed request must not be cached'); + service.getRoles().subscribe(); + service.getRoles().subscribe(); + assert.equal(count, 2, 'a successful request is shared'); + service.getRoles(true).subscribe(); + assert.equal(count, 3); +}); + +// ---- components ---------------------------------------------------------------------------------------------- +const signal = (initial) => { + let value = initial; + const get = () => value; + get.set = (next) => { + value = next; + }; + return get; +}; +const computed = (fn) => () => fn(); +class FormControl { + constructor(value) { + this.value = value; + this.touched = false; + this.invalid = false; + } +} +class FormGroup { + constructor(controls) { + this.controls = controls; + } + get invalid() { + return Object.values(this.controls).some((c) => c.invalid); + } + reset(values) { + for (const [k, v] of Object.entries(values)) this.controls[k].value = v; + } + getRawValue() { + return Object.fromEntries(Object.entries(this.controls).map(([k, c]) => [k, c.value])); + } + markAllAsTouched() {} +} +const forms = { + FormControl, + FormGroup, + Validators: { required: 1, email: 1, minLength: () => 1, maxLength: () => 1, pattern: () => 1 }, +}; +const core = { + Component: () => (t) => t, + ChangeDetectionStrategy: {}, + ViewChild: () => () => {}, + signal, + computed, + inject: () => undefined, + DestroyRef: class {}, +}; + +function buildMembers(service, myEmail) { + const toasts = []; + const dialog = { open: () => ({ afterClosed: () => new Subject(), close() {}, disableClose: false }) }; + const toast = { success: (m) => toasts.push(['success', m]), error: (m) => toasts.push(['error', m]) }; + const store = { pipe: () => of({ email: myEmail ?? 'me@example.test' }) }; + const { MembersComponent } = load(`${team}/members/members.component.ts`, { + '@angular/core': { + ...core, + inject: (t) => + ({ TeamService: service, MatDialog: dialog, PrimeNgToastService: toast, Store: store })[t.name], + }, + '@angular/core/rxjs-interop': { takeUntilDestroyed: () => (source) => source }, + '@angular/forms': forms, + '@angular/material/dialog': { MatDialog: class MatDialog {} }, + '@ngrx/store': { Store: class Store {}, select: () => (s) => s }, + '@proxy/ui/prime-ng-toast': { PrimeNgToastService: class PrimeNgToastService {} }, + '../../../website/home/ngrx/selector/login.selector': { selectLogInData: {} }, + '../team.models': models, + '../team.service': { TeamService: class TeamService {} }, + }); + return { component: new MembersComponent(), toasts }; +} + +const page = (data) => ({ + hasError: false, + data: { data, totalEntityCount: data.length, totalPageCount: data.length ? 1 : 0 }, +}); + +test('members distinguish denied, failed and empty and recover on retry', () => { + let response = throwError(() => ({ errorCode: 403 })); + const { component } = buildMembers({ + getMembers: () => response, + getRoles: () => of(page([])), + }); + component.ngOnInit(); + assert.match(component.error(), /permission to view the team/); + response = of({ hasError: true }); + component.load(1); + assert.match(component.error(), /could not be loaded/); + response = of(page([])); + component.load(1); + assert.equal(component.error(), null); + assert.equal(component.members().length, 0); + assert.equal(component.loading(), false); +}); + +test('members: search applies from page one, newer requests cancel older ones, own role is not changeable', () => { + const requests = []; + const first = new Subject(); + let n = 0; + const { component } = buildMembers( + { + getMembers: (p) => { + requests.push(p); + return ++n === 1 ? first : of(page([member()])); + }, + getRoles: () => of(page([])), + }, + 'Morgan@Example.test' + ); + component.ngOnInit(); + component.searchText = ' jane '; + component.applySearch(); + assert.equal(first.observers.length, 0, 'older request is cancelled'); + assert.deepEqual({ ...requests[1] }, { name: 'jane', pageNo: 1 }); + assert.equal(component.hasFilter(), true); + component.load(2); + assert.equal(requests[2].name, 'jane', 'paging keeps the applied search, not unsaved edits'); + assert.equal(component.isMe(member({ email: 'morgan@example.test' })), true); + assert.equal(component.isMe(member({ email: 'other@example.test' })), false); + component.clearSearch(); + assert.equal(requests[3].name, ''); +}); + +test('members: resending an invitation reuses the existing role and reports failures', () => { + const sent = []; + let result = of({ hasError: false, data: { message: 'ok' } }); + const { component, toasts } = buildMembers({ + getMembers: () => of(page([])), + getRoles: () => of(page([])), + inviteMember: (body) => { + sent.push(body); + return result; + }, + }); + const declined = member({ client_user: { ...member().client_user, invite_status: 'rejected' } }); + component.resend(declined); + assert.deepEqual({ ...sent[0] }, { email: 'morgan@example.test', role_id: 4 }); + assert.equal(toasts[0][0], 'success'); + result = throwError(() => ({ errors: { email: ['Invitation already pending for this user.'] } })); + component.resend(declined); + assert.equal(toasts[1][0], 'error'); + assert.match(toasts[1][1], /already pending/); + assert.equal(component.resendingId(), null); + component.resend(member({ client_user: { ...member().client_user, role: null } })); + assert.equal(sent.length, 2, 'no request without a known role'); +}); + +function buildKeys(service, { confirm = 'yes' } = {}) { + const toasts = []; + const dialogRef = { + componentRef: { setInput() {} }, + afterClosed: () => of(confirm), + close() {}, + disableClose: false, + }; + const dialog = { open: () => dialogRef }; + const toast = { success: (m) => toasts.push(['success', m]), error: (m) => toasts.push(['error', m]) }; + const { ApiKeysComponent } = load(`${team}/api-keys/api-keys.component.ts`, { + '@angular/core': { + ...core, + inject: (t) => ({ TeamService: service, MatDialog: dialog, PrimeNgToastService: toast })[t.name], + }, + '@angular/core/rxjs-interop': { takeUntilDestroyed: () => (source) => source }, + '@angular/forms': forms, + '@angular/material/dialog': { MatDialog: class MatDialog {} }, + '@proxy/ui/confirm-dialog': { ConfirmDialogComponent: class {} }, + '@proxy/ui/copy-button': {}, + '@proxy/ui/prime-ng-toast': { PrimeNgToastService: class PrimeNgToastService {} }, + '../team.models': models, + '../team.service': { TeamService: class TeamService {} }, + }); + return { component: new ApiKeysComponent(), toasts }; +} + +const key = (over = {}) => ({ + id: 21, + name: 'backend_sync', + authkey: '0123456789abcdef0123456789abcdef', + role_id: 3, + status: 'active', + ...over, +}); + +test('API keys are masked until revealed, and reveal is per key', () => { + const { component } = buildKeys({ getApiKeys: () => of(page([key()])), getRoles: () => of(page([])) }); + assert.equal(component.isRevealed(key()), false); + component.toggleReveal(key()); + assert.equal(component.isRevealed(key()), true); + assert.equal(component.isRevealed(key({ id: 22 })), false); + component.toggleReveal(key()); + assert.equal(component.isRevealed(key()), false); +}); + +test('API keys: edit sends only changed fields; deactivate and delete need confirmation', () => { + const updates = []; + const deletes = []; + const service = { + getApiKeys: () => of(page([key()])), + getRoles: () => of(page([{ id: 3, role_name: 'Admin', permissions: [] }])), + updateApiKey: (id, body) => { + updates.push([id, body]); + return of({ hasError: false, data: key() }); + }, + deleteApiKey: (id) => { + deletes.push(id); + return of({ hasError: false }); + }, + }; + const { component, toasts } = buildKeys(service); + component.ngOnInit(); + component.setActive(key(), false); + assert.deepEqual(JSON.parse(JSON.stringify(updates)), [[21, { status: 'inactive' }]]); + component.setActive(key({ status: 'inactive' }), true); + assert.equal(updates[1][1].status, 'active', 'activating needs no confirmation and sends only status'); + component.remove(key()); + assert.deepEqual(deletes, [21]); + assert.equal( + toasts.some(([kind]) => kind === 'success'), + true + ); + + const declined = buildKeys(service, { confirm: 'no' }); + declined.component.setActive(key(), false); + declined.component.remove(key()); + assert.equal(updates.length, 2); + assert.equal(deletes.length, 1); +}); + +test('API keys: denied list is distinct from a failed one', () => { + let response = throwError(() => ({ errorCode: 403 })); + const { component } = buildKeys({ getApiKeys: () => response, getRoles: () => of(page([])) }); + component.ngOnInit(); + assert.match(component.error(), /view_authkeys/); + response = throwError(() => ({ errorCode: 500 })); + component.load(1); + assert.match(component.error(), /Check your connection/); +});