From d5de4f5104badc85f6c77449bbb8770727e649d7 Mon Sep 17 00:00:00 2001 From: Dan Percic Date: Sun, 26 Sep 2021 10:36:28 +0300 Subject: [PATCH] UserWrapper => User --- .../app/models/file/annotation.permissions.ts | 4 +- .../src/app/models/file/file-data.model.ts | 4 +- apps/red-ui/src/app/models/user.ts | 28 ++++++++++ .../add-edit-user-dialog.component.ts | 4 +- .../reset-password.component.ts | 7 +-- .../user-details/user-details.component.ts | 9 ++-- .../confirm-delete-users-dialog.component.ts | 4 +- .../user-listing-screen.component.ts | 21 ++++---- .../dossier-details.component.ts | 7 +-- .../file-preview-screen.component.ts | 5 +- .../assign-user-dropdown.component.ts | 19 +++---- .../initials-avatar.component.ts | 5 +- .../src/app/modules/shared/pipes/name.pipe.ts | 5 +- apps/red-ui/src/app/services/user.service.ts | 51 +++++------------- .../src/lib/api/userController.service.ts | 54 +++++++++---------- libs/red-ui-http/src/lib/model/user.ts | 14 ++--- 16 files changed, 124 insertions(+), 117 deletions(-) create mode 100644 apps/red-ui/src/app/models/user.ts diff --git a/apps/red-ui/src/app/models/file/annotation.permissions.ts b/apps/red-ui/src/app/models/file/annotation.permissions.ts index 431ad80da..e8bdc1fd0 100644 --- a/apps/red-ui/src/app/models/file/annotation.permissions.ts +++ b/apps/red-ui/src/app/models/file/annotation.permissions.ts @@ -1,6 +1,6 @@ -import { UserWrapper } from '@services/user.service'; import { AnnotationWrapper } from './annotation.wrapper'; import { isArray } from 'rxjs/internal-compatibility'; +import { User } from '@models/user'; export class AnnotationPermissions { canUndo = true; @@ -14,7 +14,7 @@ export class AnnotationPermissions { canChangeLegalBasis = true; canRecategorizeImage = true; - static forUser(isApprover: boolean, user: UserWrapper, annotations: AnnotationWrapper | AnnotationWrapper[]) { + static forUser(isApprover: boolean, user: User, annotations: AnnotationWrapper | AnnotationWrapper[]) { if (!isArray(annotations)) { annotations = [annotations]; } diff --git a/apps/red-ui/src/app/models/file/file-data.model.ts b/apps/red-ui/src/app/models/file/file-data.model.ts index 4a44df195..eee719700 100644 --- a/apps/red-ui/src/app/models/file/file-data.model.ts +++ b/apps/red-ui/src/app/models/file/file-data.model.ts @@ -1,10 +1,10 @@ import { RedactionChangeLog, RedactionLog, ViewedPages } from '@redaction/red-ui-http'; import { FileStatusWrapper } from './file-status.wrapper'; -import { UserWrapper } from '@services/user.service'; import { AnnotationWrapper } from './annotation.wrapper'; import { RedactionLogEntryWrapper } from './redaction-log-entry.wrapper'; import { ViewMode } from './view-mode'; import { TypeValue } from './type-value'; +import { User } from '@models/user'; export class AnnotationData { visibleAnnotations: AnnotationWrapper[]; @@ -22,7 +22,7 @@ export class FileDataModel { getAnnotations( dictionaryData: { [p: string]: TypeValue }, - currentUser: UserWrapper, + currentUser: User, viewMode: ViewMode, areDevFeaturesEnabled: boolean ): AnnotationData { diff --git a/apps/red-ui/src/app/models/user.ts b/apps/red-ui/src/app/models/user.ts new file mode 100644 index 000000000..24bb45dd4 --- /dev/null +++ b/apps/red-ui/src/app/models/user.ts @@ -0,0 +1,28 @@ +import { IUser, List } from '@redaction/red-ui-http'; +import { IListable } from '@iqser/common-ui'; +import { KeycloakProfile } from 'keycloak-js'; + +export class User implements IUser, IListable { + readonly email: string; + readonly username: string; + readonly firstName: string; + readonly lastName: string; + readonly name: string; + readonly searchKey: string; + + readonly isActive = this.roles.length > 0; + readonly isManager = this.roles.indexOf('RED_MANAGER') >= 0; + readonly isUserAdmin = this.roles.indexOf('RED_USER_ADMIN') >= 0; + readonly isUser = this.roles.indexOf('RED_USER') >= 0; + readonly isAdmin = this.roles.indexOf('RED_ADMIN') >= 0; + readonly hasAnyREDRoles = this.isUser || this.isManager || this.isAdmin || this.isUserAdmin; + + constructor(user: KeycloakProfile | IUser, readonly roles: List, readonly id: string) { + this.email = user.email; + this.username = user.username || this.email; + this.firstName = user.firstName; + this.lastName = user.lastName; + this.name = this.firstName && this.lastName ? `${this.firstName} ${this.lastName}` : this.username; + this.searchKey = this.name + this.username + this.email; + } +} diff --git a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/add-edit-user-dialog.component.ts b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/add-edit-user-dialog.component.ts index 8753a57bc..95222870a 100644 --- a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/add-edit-user-dialog.component.ts +++ b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/add-edit-user-dialog.component.ts @@ -1,6 +1,6 @@ import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { UserWrapper } from '@services/user.service'; +import { User } from '@models/user'; @Component({ selector: 'redaction-add-edit-user-dialog', @@ -10,7 +10,7 @@ import { UserWrapper } from '@services/user.service'; export class AddEditUserDialogComponent { resettingPassword = false; - constructor(readonly dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) readonly user: UserWrapper) {} + constructor(readonly dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) readonly user: User) {} toggleResetPassword() { this.resettingPassword = !this.resettingPassword; diff --git a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/reset-password/reset-password.component.ts b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/reset-password/reset-password.component.ts index 7dfb3d7b3..a8a7b7c96 100644 --- a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/reset-password/reset-password.component.ts +++ b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/reset-password/reset-password.component.ts @@ -1,8 +1,9 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { UserControllerService } from '@redaction/red-ui-http'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { LoadingService } from '@iqser/common-ui'; +import { User } from '@models/user'; @Component({ selector: 'redaction-reset-password', @@ -13,8 +14,8 @@ export class ResetPasswordComponent { readonly passwordForm = this._formBuilder.group({ temporaryPassword: [null, Validators.required] }); - @Input() user: UserWrapper; - @Output() toggleResetPassword = new EventEmitter(); + @Input() user: User; + @Output() readonly toggleResetPassword = new EventEmitter(); constructor( private readonly _formBuilder: FormBuilder, diff --git a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/user-details/user-details.component.ts b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/user-details/user-details.component.ts index f9165c1ee..a9a6f9406 100644 --- a/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/user-details/user-details.component.ts +++ b/apps/red-ui/src/app/modules/admin/dialogs/add-edit-user-dialog/user-details/user-details.component.ts @@ -4,8 +4,8 @@ import { UserControllerService } from '@redaction/red-ui-http'; import { AdminDialogService } from '../../../services/admin-dialog.service'; import { IconButtonTypes, LoadingService, Toaster } from '@iqser/common-ui'; import { rolesTranslations } from '../../../../../translations/roles-translations'; -import { UserWrapper } from '@services/user.service'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; +import { User } from '@models/user'; @Component({ selector: 'redaction-user-details', @@ -15,9 +15,10 @@ import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; export class UserDetailsComponent implements OnInit { readonly iconButtonTypes = IconButtonTypes; - @Input() user: UserWrapper; - @Output() toggleResetPassword = new EventEmitter(); - @Output() closeDialog = new EventEmitter(); + @Input() user: User; + @Output() readonly toggleResetPassword = new EventEmitter(); + @Output() readonly closeDialog = new EventEmitter(); + userForm: FormGroup; readonly ROLES = ['RED_USER', 'RED_MANAGER', 'RED_USER_ADMIN', 'RED_ADMIN']; readonly translations = rolesTranslations; diff --git a/apps/red-ui/src/app/modules/admin/dialogs/confirm-delete-users-dialog/confirm-delete-users-dialog.component.ts b/apps/red-ui/src/app/modules/admin/dialogs/confirm-delete-users-dialog/confirm-delete-users-dialog.component.ts index e70d72999..bd63dad28 100644 --- a/apps/red-ui/src/app/modules/admin/dialogs/confirm-delete-users-dialog/confirm-delete-users-dialog.component.ts +++ b/apps/red-ui/src/app/modules/admin/dialogs/confirm-delete-users-dialog/confirm-delete-users-dialog.component.ts @@ -4,7 +4,7 @@ import { UserControllerService } from '@redaction/red-ui-http'; import { AppStateService } from '@state/app-state.service'; import { LoadingService } from '@iqser/common-ui'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; -import { UserWrapper } from '@services/user.service'; +import { User } from '@models/user'; @Component({ selector: 'redaction-confirm-delete-users-dialog', @@ -24,7 +24,7 @@ export class ConfirmDeleteUsersDialogComponent { private readonly _loadingService: LoadingService, private readonly _userControllerService: UserControllerService, readonly dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) readonly users: UserWrapper[] + @Inject(MAT_DIALOG_DATA) readonly users: User[] ) { this.dossiersCount = this._appStateService.allDossiers.filter(dw => { for (const user of this.users) { diff --git a/apps/red-ui/src/app/modules/admin/screens/user-listing/user-listing-screen.component.ts b/apps/red-ui/src/app/modules/admin/screens/user-listing/user-listing-screen.component.ts index 0bb3f1e65..fa92bdd2f 100644 --- a/apps/red-ui/src/app/modules/admin/screens/user-listing/user-listing-screen.component.ts +++ b/apps/red-ui/src/app/modules/admin/screens/user-listing/user-listing-screen.component.ts @@ -1,5 +1,5 @@ import { Component, forwardRef, Injector, OnInit, QueryList, TemplateRef, ViewChild, ViewChildren } from '@angular/core'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { UserControllerService } from '@redaction/red-ui-http'; import { AdminDialogService } from '../../services/admin-dialog.service'; import { TranslateService } from '@ngx-translate/core'; @@ -18,27 +18,27 @@ import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { rolesTranslations } from '../../../../translations/roles-translations'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; +import { User } from '@models/user'; @Component({ templateUrl: './user-listing-screen.component.html', styleUrls: ['./user-listing-screen.component.scss'], providers: [...DefaultListingServices, { provide: ListingComponent, useExisting: forwardRef(() => UserListingScreenComponent) }] }) -export class UserListingScreenComponent extends ListingComponent implements OnInit { +export class UserListingScreenComponent extends ListingComponent implements OnInit { readonly translations = rolesTranslations; readonly iconButtonTypes = IconButtonTypes; readonly circleButtonTypes = CircleButtonTypes; readonly currentUser = this.userService.currentUser; readonly canDeleteSelected$ = this._canDeleteSelected$; readonly tableHeaderLabel = _('user-listing.table-header.title'); - tableColumnConfigs: TableColumnConfig[]; + tableColumnConfigs: TableColumnConfig[]; collapsedDetails = false; chartData: DoughnutChartConfig[] = []; @ViewChild('nameTemplate', { static: true }) nameTemplate: TemplateRef; @ViewChild('emailTemplate', { static: true }) emailTemplate: TemplateRef; @ViewChild('activeTemplate', { static: true }) activeTemplate: TemplateRef; @ViewChild('rolesTemplate', { static: true }) rolesTemplate: TemplateRef; - protected readonly _primaryKey = 'id'; @ViewChildren(InitialsAvatarComponent) private readonly _avatars: QueryList; @@ -62,22 +62,21 @@ export class UserListingScreenComponent extends ListingComponent im async ngOnInit() { this._configureTableColumns(); await this._loadData(); - this.searchService.setSearchKey('searchKey'); } - openAddEditUserDialog($event: MouseEvent, user?: UserWrapper) { + openAddEditUserDialog($event: MouseEvent, user?: User) { this._dialogService.openDialog('addEditUser', $event, user, async () => { await this._loadData(); }); } - openDeleteUsersDialog(users: UserWrapper[], $event?: MouseEvent) { + openDeleteUsersDialog(users: User[], $event?: MouseEvent) { this._dialogService.openDialog('deleteUsers', $event, users, async () => { await this._loadData(); }); } - getDisplayRoles(user: UserWrapper) { + getDisplayRoles(user: User) { const separator = ', '; return ( user.roles.map(role => this._translateService.instant(this.translations[role])).join(separator) || @@ -85,10 +84,10 @@ export class UserListingScreenComponent extends ListingComponent im ); } - async toggleActive(user: UserWrapper) { + async toggleActive(user: User) { this._loadingService.start(); - user.roles = user.isActive ? [] : ['RED_USER']; - await this._userControllerService.updateProfile(user, user.id).toPromise(); + const requestBody = { ...user, roles: user.isActive ? [] : ['RED_USER'] }; + await this._userControllerService.updateProfile(requestBody, user.id).toPromise(); await this._loadData(); this._avatars.find(item => item.userId === user.id).detectChanges(); } diff --git a/apps/red-ui/src/app/modules/dossier/components/dossier-details/dossier-details.component.ts b/apps/red-ui/src/app/modules/dossier/components/dossier-details/dossier-details.component.ts index a58f64dd6..77a8f78b0 100644 --- a/apps/red-ui/src/app/modules/dossier/components/dossier-details/dossier-details.component.ts +++ b/apps/red-ui/src/app/modules/dossier/components/dossier-details/dossier-details.component.ts @@ -4,12 +4,13 @@ import { groupBy } from '@utils/functions'; import { DoughnutChartConfig } from '@shared/components/simple-doughnut-chart/simple-doughnut-chart.component'; import { TranslateChartService } from '@services/translate-chart.service'; import { StatusSorter } from '@utils/sorters/status-sorter'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { FilterService, Toaster } from '@iqser/common-ui'; import { DossierAttributeWithValue } from '@models/dossier-attributes.model'; import { fileStatusTranslations } from '../../translations/file-status-translations'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { List } from '@redaction/red-ui-http'; +import { User } from '@models/user'; @Component({ selector: 'redaction-dossier-details', @@ -18,7 +19,7 @@ import { List } from '@redaction/red-ui-http'; }) export class DossierDetailsComponent implements OnInit { documentsChartData: DoughnutChartConfig[] = []; - owner: UserWrapper; + owner: User; editingOwner = false; @Input() dossierAttributes: DossierAttributeWithValue[]; @Output() readonly openAssignDossierMembersDialog = new EventEmitter(); @@ -79,7 +80,7 @@ export class DossierDetailsComponent implements OnInit { this._changeDetectorRef.detectChanges(); } - async assignOwner(user: UserWrapper | string) { + async assignOwner(user: User | string) { this.owner = typeof user === 'string' ? this._userService.getRedUserById(user) : user; const dw = { ...this.appStateService.activeDossier, ownerId: this.owner.id }; await this.appStateService.createOrUpdateDossier(dw); diff --git a/apps/red-ui/src/app/modules/dossier/screens/file-preview-screen/file-preview-screen.component.ts b/apps/red-ui/src/app/modules/dossier/screens/file-preview-screen/file-preview-screen.component.ts index 4a2191a29..bea731c7d 100644 --- a/apps/red-ui/src/app/modules/dossier/screens/file-preview-screen/file-preview-screen.component.ts +++ b/apps/red-ui/src/app/modules/dossier/screens/file-preview-screen/file-preview-screen.component.ts @@ -25,7 +25,7 @@ import { FileStatusWrapper } from '@models/file/file-status.wrapper'; import { PermissionsService } from '@services/permissions.service'; import { timer } from 'rxjs'; import { UserPreferenceService } from '@services/user-preference.service'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { FileManagementControllerService, FileStatus, @@ -45,6 +45,7 @@ import { fileStatusTranslations } from '../../translations/file-status-translati import { handleFilterDelta } from '@utils/filter-utils'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { FileActionsComponent } from '../../components/file-actions/file-actions.component'; +import { User } from '@models/user'; import Annotation = Core.Annotations.Annotation; const ALL_HOTKEY_ARRAY = ['Escape', 'F', 'f']; @@ -495,7 +496,7 @@ export class FilePreviewScreenComponent extends AutoUnsubscribe implements OnIni }); } - async assignReviewer(user: UserWrapper | string) { + async assignReviewer(user: User | string) { const reviewerId = typeof user === 'string' ? user : user.id; const reviewerName = this.userService.getNameForId(reviewerId); diff --git a/apps/red-ui/src/app/modules/shared/components/assign-user-dropdown/assign-user-dropdown.component.ts b/apps/red-ui/src/app/modules/shared/components/assign-user-dropdown/assign-user-dropdown.component.ts index f203f4b8e..fd20f27b9 100644 --- a/apps/red-ui/src/app/modules/shared/components/assign-user-dropdown/assign-user-dropdown.component.ts +++ b/apps/red-ui/src/app/modules/shared/components/assign-user-dropdown/assign-user-dropdown.component.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { List } from '@redaction/red-ui-http'; +import { User } from '@models/user'; @Component({ selector: 'redaction-assign-user-dropdown', @@ -9,27 +10,27 @@ import { List } from '@redaction/red-ui-http'; changeDetection: ChangeDetectionStrategy.OnPush }) export class AssignUserDropdownComponent { - oldUser: UserWrapper | string; - @Input() options: List; - @Output() save = new EventEmitter(); - @Output() cancel = new EventEmitter(); - private _currentUser: UserWrapper | string; + oldUser: User | string; + @Input() options: List; + @Output() readonly save = new EventEmitter(); + @Output() readonly cancel = new EventEmitter(); + private _currentUser: User | string; constructor(private readonly _userService: UserService) {} - get value(): UserWrapper | string { + get value(): User | string { return this._currentUser; } @Input() - set value(value: UserWrapper | string) { + set value(value: User | string) { if (this.oldUser === undefined) { this.oldUser = value; } this._currentUser = value; } - getContext(user: UserWrapper | string) { + getContext(user: User | string) { return { userId: typeof user === 'string' ? user : user?.id }; } } diff --git a/apps/red-ui/src/app/modules/shared/components/initials-avatar/initials-avatar.component.ts b/apps/red-ui/src/app/modules/shared/components/initials-avatar/initials-avatar.component.ts index cd85fa28f..288f70a62 100644 --- a/apps/red-ui/src/app/modules/shared/components/initials-avatar/initials-avatar.component.ts +++ b/apps/red-ui/src/app/modules/shared/components/initials-avatar/initials-avatar.component.ts @@ -1,7 +1,8 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy } from '@angular/core'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { TranslateService } from '@ngx-translate/core'; import { AutoUnsubscribe } from '@iqser/common-ui'; +import { User } from '@models/user'; @Component({ selector: 'redaction-initials-avatar', @@ -20,7 +21,7 @@ export class InitialsAvatarComponent extends AutoUnsubscribe implements OnChange displayName: string; initials: string; colorClass: string; - user: UserWrapper; + user: User; constructor( private readonly _userService: UserService, diff --git a/apps/red-ui/src/app/modules/shared/pipes/name.pipe.ts b/apps/red-ui/src/app/modules/shared/pipes/name.pipe.ts index b95d4e83c..d0618c670 100644 --- a/apps/red-ui/src/app/modules/shared/pipes/name.pipe.ts +++ b/apps/red-ui/src/app/modules/shared/pipes/name.pipe.ts @@ -1,6 +1,7 @@ import { Pipe, PipeTransform } from '@angular/core'; -import { UserService, UserWrapper } from '@services/user.service'; +import { UserService } from '@services/user.service'; import { TranslateService } from '@ngx-translate/core'; +import { User } from '@models/user'; @Pipe({ name: 'name' @@ -8,7 +9,7 @@ import { TranslateService } from '@ngx-translate/core'; export class NamePipe implements PipeTransform { constructor(private readonly _userService: UserService, private readonly _translateService: TranslateService) {} - transform(value: UserWrapper | string): string { + transform(value: User | string): string { if (typeof value === 'string') { return this._userService.getNameForId(value) || this._translateService.instant('unknown'); } diff --git a/apps/red-ui/src/app/services/user.service.ts b/apps/red-ui/src/app/services/user.service.ts index 157500e5a..5d159d8ed 100644 --- a/apps/red-ui/src/app/services/user.service.ts +++ b/apps/red-ui/src/app/services/user.service.ts @@ -1,12 +1,11 @@ import { Inject, Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angular'; -import { KeycloakProfile } from 'keycloak-js'; import jwt_decode from 'jwt-decode'; -import { User, UserControllerService } from '@redaction/red-ui-http'; +import { IUser, UserControllerService } from '@redaction/red-ui-http'; import { wipeCaches } from '@redaction/red-cache'; import { BASE_HREF } from '../tokens'; import { Subject } from 'rxjs'; -import { IListable } from '@iqser/common-ui'; +import { User } from '@models/user'; export interface ProfileModel { username?: string; @@ -16,31 +15,13 @@ export interface ProfileModel { language: string; } -export class UserWrapper implements IListable { - constructor(private readonly _user: KeycloakProfile | User, public roles: string[], public id: string) {} - - email = this._user.email; - username = this._user.username || this.email; - firstName = this._user.firstName; - lastName = this._user.lastName; - name = this.firstName && this.lastName ? `${this.firstName} ${this.lastName}` : this.username; - searchKey = this.name + this.username + this.email; - - isActive = this.roles.length > 0; - isManager = this.roles.indexOf('RED_MANAGER') >= 0; - isUserAdmin = this.roles.indexOf('RED_USER_ADMIN') >= 0; - isUser = this.roles.indexOf('RED_USER') >= 0; - isAdmin = this.roles.indexOf('RED_ADMIN') >= 0; - hasAnyREDRoles = this.isUser || this.isManager || this.isAdmin || this.isUserAdmin; -} - @Injectable({ providedIn: 'root' }) export class UserService { usersReloaded$ = new Subject(); - private _currentUser: UserWrapper; - private _allUsers: UserWrapper[]; + private _currentUser: User; + private _allUsers: User[]; constructor( @Inject(BASE_HREF) private readonly _baseHref: string, @@ -48,17 +29,17 @@ export class UserService { private readonly _userControllerService: UserControllerService ) {} - private _allRedUsers: UserWrapper[]; + private _allRedUsers: User[]; - get managerUsers(): UserWrapper[] { + get managerUsers(): User[] { return this._allRedUsers.filter(user => user.isManager); } - get eligibleUsers(): UserWrapper[] { + get eligibleUsers(): User[] { return this._allRedUsers.filter(user => user.isUser || user.isManager); } - get currentUser(): UserWrapper { + get currentUser(): User { return this._currentUser; } @@ -74,13 +55,13 @@ export class UserService { } async loadAllUsers() { - let allUsers: User[]; + let allUsers: IUser[]; if (this._currentUser.isUserAdmin) { allUsers = await this._userControllerService.getAllUsers().toPromise(); } else { allUsers = await this._userControllerService.getUsers().toPromise(); } - this._allUsers = allUsers.map(user => new UserWrapper(user, user.roles, user.userId)); + this._allUsers = allUsers.map(user => new User(user, user.roles, user.userId)); this._allRedUsers = this._allUsers.filter(user => user.hasAnyREDRoles); this.usersReloaded$.next(); return this._allUsers; @@ -90,11 +71,7 @@ export class UserService { const token = await this._keycloakService.getToken(); const decoded = jwt_decode(token) as any; const userId = decoded.sub; - this._currentUser = new UserWrapper( - await this._keycloakService.loadUserProfile(true), - this._keycloakService.getUserRoles(true), - userId - ); + this._currentUser = new User(await this._keycloakService.loadUserProfile(true), this._keycloakService.getUserRoles(true), userId); } getRedUserById(id: string) { @@ -109,11 +86,7 @@ export class UserService { return this.getUserById(userId)?.name; } - isManager(user: UserWrapper = this._currentUser): boolean { - return user.roles.indexOf('RED_MANAGER') >= 0; - } - - hasAnyRole(requiredRoles: string[], user: UserWrapper = this._currentUser) { + hasAnyRole(requiredRoles: string[], user = this._currentUser): boolean { if (requiredRoles?.length > 0) { for (const role of requiredRoles) { if (user.roles.indexOf(role) >= 0) { diff --git a/libs/red-ui-http/src/lib/api/userController.service.ts b/libs/red-ui-http/src/lib/api/userController.service.ts index f7be77a31..1fbce4576 100644 --- a/libs/red-ui-http/src/lib/api/userController.service.ts +++ b/libs/red-ui-http/src/lib/api/userController.service.ts @@ -10,20 +10,20 @@ * Do not edit the class manually. */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http'; -import { CustomHttpUrlEncodingCodec } from '../encoder'; +import { Inject, Injectable, Optional } from "@angular/core"; +import { HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpResponse } from "@angular/common/http"; +import { CustomHttpUrlEncodingCodec } from "../encoder"; -import { Observable } from 'rxjs'; +import { Observable } from "rxjs"; -import { CreateUserRequest } from '../model/createUserRequest'; -import { ResetPasswordRequest } from '../model/resetPasswordRequest'; -import { UpdateMyProfileRequest } from '../model/updateMyProfileRequest'; -import { UpdateProfileRequest } from '../model/updateProfileRequest'; -import { User } from '../model/user'; +import { CreateUserRequest } from "../model/createUserRequest"; +import { ResetPasswordRequest } from "../model/resetPasswordRequest"; +import { UpdateMyProfileRequest } from "../model/updateMyProfileRequest"; +import { UpdateProfileRequest } from "../model/updateProfileRequest"; +import { IUser } from "../model/user"; -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH } from "../variables"; +import { Configuration } from "../configuration"; @Injectable() export class UserControllerService { @@ -112,11 +112,11 @@ export class UserControllerService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: CreateUserRequest, observe?: 'body', reportProgress?: boolean): Observable; + public createUser(body: CreateUserRequest, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: CreateUserRequest, observe?: 'response', reportProgress?: boolean): Observable>; + public createUser(body: CreateUserRequest, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: CreateUserRequest, observe?: 'events', reportProgress?: boolean): Observable>; + public createUser(body: CreateUserRequest, observe?: 'events', reportProgress?: boolean): Observable>; public createUser(body: CreateUserRequest, observe: any = 'body', reportProgress: boolean = false): Observable { if (body === null || body === undefined) { @@ -146,7 +146,7 @@ export class UserControllerService { headers = headers.set('Content-Type', httpContentTypeSelected); } - return this.httpClient.request('post', `${this.basePath}/user`, { + return this.httpClient.request('post', `${this.basePath}/user`, { body: body, withCredentials: this.configuration.withCredentials, headers: headers, @@ -254,11 +254,11 @@ export class UserControllerService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAllUsers(refreshCache?: boolean, observe?: 'body', reportProgress?: boolean): Observable>; + public getAllUsers(refreshCache?: boolean, observe?: 'body', reportProgress?: boolean): Observable>; - public getAllUsers(refreshCache?: boolean, observe?: 'response', reportProgress?: boolean): Observable>>; + public getAllUsers(refreshCache?: boolean, observe?: 'response', reportProgress?: boolean): Observable>>; - public getAllUsers(refreshCache?: boolean, observe?: 'events', reportProgress?: boolean): Observable>>; + public getAllUsers(refreshCache?: boolean, observe?: 'events', reportProgress?: boolean): Observable>>; public getAllUsers(refreshCache?: boolean, observe: any = 'body', reportProgress: boolean = false): Observable { let queryParameters = new HttpParams({ encoder: new CustomHttpUrlEncodingCodec() }); @@ -282,7 +282,7 @@ export class UserControllerService { headers = headers.set('Accept', httpHeaderAcceptSelected); } - return this.httpClient.request>('get', `${this.basePath}/user`, { + return this.httpClient.request>('get', `${this.basePath}/user`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, @@ -298,11 +298,11 @@ export class UserControllerService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserById(userId: string, observe?: 'body', reportProgress?: boolean): Observable; + public getUserById(userId: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserById(userId: string, observe?: 'response', reportProgress?: boolean): Observable>; + public getUserById(userId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserById(userId: string, observe?: 'events', reportProgress?: boolean): Observable>; + public getUserById(userId: string, observe?: 'events', reportProgress?: boolean): Observable>; public getUserById(userId: string, observe: any = 'body', reportProgress: boolean = false): Observable { if (userId === null || userId === undefined) { @@ -325,7 +325,7 @@ export class UserControllerService { headers = headers.set('Accept', httpHeaderAcceptSelected); } - return this.httpClient.request('get', `${this.basePath}/user/${encodeURIComponent(String(userId))}`, { + return this.httpClient.request('get', `${this.basePath}/user/${encodeURIComponent(String(userId))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, @@ -340,11 +340,11 @@ export class UserControllerService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUsers(refreshCache?: boolean, observe?: 'body', reportProgress?: boolean): Observable>; + public getUsers(refreshCache?: boolean, observe?: 'body', reportProgress?: boolean): Observable>; - public getUsers(refreshCache?: boolean, observe?: 'response', reportProgress?: boolean): Observable>>; + public getUsers(refreshCache?: boolean, observe?: 'response', reportProgress?: boolean): Observable>>; - public getUsers(refreshCache?: boolean, observe?: 'events', reportProgress?: boolean): Observable>>; + public getUsers(refreshCache?: boolean, observe?: 'events', reportProgress?: boolean): Observable>>; public getUsers(refreshCache?: boolean, observe: any = 'body', reportProgress: boolean = false): Observable { let queryParameters = new HttpParams({ encoder: new CustomHttpUrlEncodingCodec() }); @@ -368,7 +368,7 @@ export class UserControllerService { headers = headers.set('Accept', httpHeaderAcceptSelected); } - return this.httpClient.request>('get', `${this.basePath}/user/red`, { + return this.httpClient.request>('get', `${this.basePath}/user/red`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, diff --git a/libs/red-ui-http/src/lib/model/user.ts b/libs/red-ui-http/src/lib/model/user.ts index 338f08774..12c831294 100644 --- a/libs/red-ui-http/src/lib/model/user.ts +++ b/libs/red-ui-http/src/lib/model/user.ts @@ -13,29 +13,29 @@ /** * Object containing information of user and roles. */ -export interface User { +export interface IUser { /** * Email of user. */ - email?: string; + readonly email?: string; /** * First name of user. */ - firstName?: string; + readonly firstName?: string; /** * Last name of user. */ - lastName?: string; + readonly lastName?: string; /** * The list of RED_* roles. */ - roles?: Array; + readonly roles?: readonly string[]; /** * Id of user. */ - userId?: string; + readonly userId?: string; /** * Username for login. */ - username?: string; + readonly username?: string; }