File

src/lib/service/user/user.service.ts

Description

Applications user service. To get the current user you have to subscribe to the services user$ observable.

userService.user$.subscribe((user) => this.user = user);

This way your component will be provided with an up-to-date user object no matter which component changes on of the users properties.

Index

Properties
Methods

Methods

Public changeClientLocale
changeClientLocale(iso: string)

Change the users client locale

Parameters :
Name Type Optional Description
iso string no

ISO locale string to be set as new client locale

Returns : void
Public changeLockSetting
changeLockSetting(lock: string)

Changes the users preferred lock mode and persists it on the server

Parameters :
Name Type Optional Description
lock string no

The value to set the lock settings to

Returns : any
changePassword
changePassword(payload: ChangePasswordInterface)

Changes the users password and persists it on the server

Parameters :
Name Type Optional
payload ChangePasswordInterface no
Returns : Observable<any>
Public changeSavedInboxFilters
changeSavedInboxFilters(filterTerms: string[])

Changes the users saved inbox filter terms

Parameters :
Name Type Optional Description
filterTerms string[] no

The value to set the saved inbox filters list to

Returns : any
Public changeSchemaLocale
changeSchemaLocale(iso: string)

Change the users schema locale

Parameters :
Name Type Optional Description
iso string no

ISO locale string to be set as new schema locale

Returns : any
Public createFavorite
createFavorite(id: string, type: string, title: string)

Create a new favorite item for the current user

Parameters :
Name Type Optional Description
id string no

ID of the dms object to be set up as favorite

type string no

The object type of the dms object

title string no

The favorites title

Returns : any
Public delUserImage
delUserImage(uri: string)
Parameters :
Name Type Optional
uri string no
Returns : Observable<any>
Public getCurrentUser
getCurrentUser()

Gets the current user.

Returns : EoUser

The current user or NULL if no user is logged in

Public getFavorites
getFavorites()

Fetches the current users favorites

Returns : Observable<any>
Public getFieldDefinition
getFieldDefinition(type: string, contextType?: string)

Get all the field definitions of an object type

Parameters :
Name Type Optional Description
type string no

The object type

contextType string yes

The context type

Returns : any
Public getNotifications
getNotifications()

Gets the users notifications (resubmissions and subscriptions)

Returns : Observable<any>

Resolved by list of the users notifications

getRecycleBin
getRecycleBin()

Gets the users recyclebin

Returns : Observable<any>
Public getResubmission
getResubmission()

Gets the users resubmissions

Returns : Observable<any>

Collection of users resubmissions

Public getSubscription
getSubscription()

Gets the users subscriptions

Returns : Observable<any>

Collection of users subscriptions

Public getUserImageUri
getUserImageUri(userId: string)

Gets the URI to a users avatar image

Parameters :
Name Type Optional Description
userId string no

The users ID

Returns : string

URI to the user image

Public hasPrivilege
hasPrivilege(privilege: string)
Parameters :
Name Type Optional
privilege string no
Returns : boolean
Public loadLocalSettings
loadLocalSettings()

Loads the local storage settings

Returns : Observable<any>

The saved settings

Public removeFavorite
removeFavorite(favoriteId: string)

Removes a favorite item

Parameters :
Name Type Optional Description
favoriteId string no

ID of the favorite item to be removed

Returns : any
Public removeNotifications
removeNotifications(id: string, type: string)

Removes a notification

Parameters :
Name Type Optional Description
id string no

ID of the notification to be removed

type string no

The notifications type ('SUBSCRIPTION', 'RESUBMISSION')

Returns : any
Public saveChangeWorkspace
saveChangeWorkspace(workspaceConfig: any)

Save or change the workspace of the current user

Parameters :
Name Type Optional Description
workspaceConfig any no

The value to set the saved workspace or create a new workspace

Returns : any
Public saveLocalSettings
saveLocalSettings(localSettings: any, cacheSettings: any)

Save the local storage settings

Parameters :
Name Type Optional Description
localSettings any no

The local settings to be saved from the localstorage

cacheSettings any no

The local settings to be saved from the app cache

Returns : any
Public saveTodoWidget
saveTodoWidget(task: TodoWidgetConfig[])

Save or change the task list of the current user

Parameters :
Name Type Optional
task TodoWidgetConfig[] no
Returns : any
Public saveToolbarState
saveToolbarState(toolbarVisibility: boolean)

Save or change the visibility state of dashboard toolbar for the current user

Parameters :
Name Type Optional Description
toolbarVisibility boolean no

The visibility state

Returns : any
Public setCurrentUser
setCurrentUser(res: any)

Set a new current user

Parameters :
Name Type Optional Description
res any no

The user to be set as current user

Returns : void
Public setDeputies
setDeputies(deputiesNames: string[])

Sets the deputies for the current user

Parameters :
Name Type Optional Description
deputiesNames string[] no

Names of the users to be set as deputies

Returns : Observable<any>
Public setPresence
setPresence(present: boolean)

Set presence of the current user

Parameters :
Name Type Optional Description
present boolean no

Value to set the users presence to

Returns : Observable<any>
Public setUserImage
setUserImage(file: File)
Parameters :
Name Type Optional
file File no
Returns : Observable<any>
Public updateFavorites
updateFavorites(id?: string, item?: any, multi?: any[])

Soft update for the users favorites

Parameters :
Name Type Optional Description
id string yes

ID of the favorite to be updated

item any yes

The new favorite item

multi any[] yes

Whether or not to update multiple items

Returns : void
Public updateNotifications
updateNotifications(id?: string, item?: any, multi?: any[])

Soft update for users notifications

Parameters :
Name Type Optional
id string yes
item any yes
multi any[] yes
Returns : void
Public validatePassword
validatePassword(password: string)
Parameters :
Name Type Optional
password string no
Returns : literal type

Properties

Public favorites$
favorites$: Observable<any>
Type : Observable<any>
Default value : this.favoritesGridData$.pipe(this.backend.gridDataFilter)
Public favoritesGridData$
favoritesGridData$: Observable<any>
Type : Observable<any>
Default value : this.favoritesSource.asObservable().pipe(debounceTime(100), filter(v => v))

Observable emitting current users favorites

Public notifications$
notifications$: Observable<any>
Type : Observable<any>
Default value : this.notificationsGridData$.pipe(this.backend.gridDataFilter)
Public notificationsGridData$
notificationsGridData$: Observable<any>
Type : Observable<any>
Default value : this.notificationsSource.asObservable().pipe(debounceTime(100), filter(v => v))

Observable emitting current users notifications

Public passwordValidationSettings
passwordValidationSettings: any
Type : any
Public recycles$
recycles$: Observable<any>
Type : Observable<any>
Default value : this.recyclesGridData$.pipe(this.backend.gridDataFilter)
Public recyclesGridData$
recyclesGridData$: Observable<any>
Type : Observable<any>
Default value : this.recyclesSource.asObservable().pipe(debounceTime(100), filter(v => v))
USER_FETCH_URI
USER_FETCH_URI: string
Type : string
Default value : '/user?favorites=true&privileges=true&roles=true&deputies=true&substitutesOf=true'
Public user$
user$: Observable<any>
Type : Observable<any>
Default value : this.userSource.asObservable()

Observable emitting the current user

import {Injectable} from '@angular/core';
import {Observable, BehaviorSubject, forkJoin, of, EMPTY} from 'rxjs';
import {map, tap, debounceTime, filter, catchError} from 'rxjs/operators';
import {TranslateService} from '@ngx-translate/core';
import {ChangePasswordInterface} from '../../interface/change-password.interface';
import {BackendService} from '../backend/backend.service';
import {EoUser} from '../../model/eo-user.model';
import {Config} from '../config/config.service';
import {Logger} from '../logger/logger';
import {SystemService} from '../system/system.service';
import {Utils} from '../../util/utils';
import {EnaioEvent} from '../events/events';
import {EventService} from '../events/event.service';
import {Direction} from '../config/config.enum';
import { HttpClient } from '@angular/common/http';
import {TodoWidgetConfig} from '../../interface/todo.interface';

/**
 * Applications user service.
 * To get the current user you have to subscribe to the services `user$` observable.
 *
 * ```javascript
 * userService.user$.subscribe((user) => this.user = user);
 * ```
 *
 * This way your component will be provided with an up-to-date user object no matter
 * which component changes on of the users properties.
 */
@Injectable({
  providedIn: 'root'
})
export class UserService {

  USER_FETCH_URI = '/user?favorites=true&privileges=true&roles=true&deputies=true&substitutesOf=true';

  private user: EoUser = null;
  private userSource = new BehaviorSubject<EoUser>(this.user);
  /**
   * Observable emitting the current user
   */
  public user$: Observable<any> = this.userSource.asObservable();

  private favorites = null;
  private favoritesSource = new BehaviorSubject<any>(this.favorites);
  /**
   * Observable emitting current users favorites
   */
  public favoritesGridData$: Observable<any> = this.favoritesSource.asObservable().pipe(debounceTime(100), filter(v => v));
  public favorites$: Observable<any> = this.favoritesGridData$.pipe(this.backend.gridDataFilter);

  private notifications = null;
  private notificationsSource = new BehaviorSubject<any>(this.notifications);

  /**
   * Observable emitting current users recyclebin
   */

  private recycles = null;
  private recyclesSource = new BehaviorSubject<any>(this.recycles);

  public recyclesGridData$: Observable<any> = this.recyclesSource.asObservable().pipe(debounceTime(100), filter(v => v));
  public recycles$: Observable<any> = this.recyclesGridData$.pipe(this.backend.gridDataFilter);


  /**
   * Observable emitting current users notifications
   */
  public notificationsGridData$: Observable<any> = this.notificationsSource.asObservable().pipe(debounceTime(100), filter(v => v));
  public notifications$: Observable<any> = this.notificationsGridData$.pipe(this.backend.gridDataFilter);

  public passwordValidationSettings: any;

  /**
   * @ignore
   */
  constructor(private backend: BackendService,
    private translate: TranslateService,
    private logger: Logger,
    private eventService: EventService,
    private system: SystemService,
    private http: HttpClient,
    private config: Config) {
  }

  /**
   * Gets the current user.
   * @returns The current user or NULL if no user is logged in
   */
  public getCurrentUser(): EoUser {
    return this.user;
  }


  /**
   * Set presence of the current user
   * @param present Value to set the users presence to
   */
  public setPresence(present: boolean): Observable<any> {

    if (present !== this.user.present) {
      return this.backend.put('/user?presence=' + present)
        .pipe(
          tap(_ => {
            this.user.present = present;
            this.userSource.next(this.user);
          })
        )
    } else {
      return of(null);
    }
  }

  /**
   *
   * @param uri
   * @returns
   */

  public delUserImage(uri: string): Observable<any> {
    return this.http.put(uri, null);
  }

  public setUserImage(file: File): Observable<any> {
    return this.backend.put(`/user/image`, file);
  }

  /**
   * Sets the deputies for the current user
   * @param deputiesNames Names of the users to be set as deputies
   */
  public setDeputies(deputiesNames: string[]): Observable<any> {
    return this.backend.put(`/user/deputy?user=${deputiesNames.join('&user=')}`).pipe(
      tap(() => this.refreshCurrentUser().subscribe())
    );
  }

  /**
   * Change the users client locale
   * @param iso ISO locale string to be set as new client locale
   */
  public changeClientLocale(iso: string) {
    this.user.userSettings['clientlocale'] = iso;
    this.backend
      .put('/user/config/web', this.user.userSettings)
      .subscribe(() => {
        this.logger.debug('Changed client locale to \'' + iso + '\'');
        this.translate.use(iso);
        this.user.uiDirection = (this.config.getClientLocales().find(l => l.iso === iso) || {}).dir || Direction.LTR;
        this.userSource.next(this.user);
        this.eventService.trigger(EnaioEvent.CLIENT_LOCALE_CHANGED, iso);
      });
  }

  /**
   * Change the users schema locale
   * @param iso ISO locale string to be set as new schema locale
   */
  public changeSchemaLocale(iso: string) {
    this.user.schemaLocale = iso;
    return this.backend
      .put('/user/locale/' + this.user.schemaLocale)
      .pipe(
        tap(() => {
          this.logger.debug('Changed schema locale to \'' + iso + '\'');
          this.userSource.next(this.user);
          this.backend.setHeader('Accept-Language', this.user.getSchemaLocale());
          this.logger.debug('Loading system definition for new locale.');
          this.system.getSystemDefinition(this.user).subscribe();
          this.eventService.trigger(EnaioEvent.SCHEMA_LOCALE_CHANGED, iso);
        }));
  }

  /**
   * Set a new current user
   * @param res The user to be set as current user
   */
  public setCurrentUser(res: any): void {
    const languages = this.config.getClientLocales().map(lang => lang.iso);
    const browserLang = this.translate.getBrowserLang();
    const schemaLocale = res.schema.supportedlocales.sort(Utils.sortValues('displayname')).map(locale => locale.code);
    const defaultClientLocale = languages.includes(browserLang) ? browserLang : this.config.getDefaultClientLocale();
    const defaultSchemaLocale = schemaLocale.includes(browserLang)
      ? browserLang
      : schemaLocale.includes(this.config.getDefaultClientLocale()) ? this.config.getDefaultClientLocale() : schemaLocale[0];
    this.user = new EoUser(res);
    this.user.schemaLocale =  this.user.schemaLocale ? this.user.schemaLocale : defaultSchemaLocale;
    this.user.userSettings.clientlocale = this.user.userSettings.clientlocale ? this.user.userSettings.clientlocale : defaultClientLocale;
    this.passwordValidationSettings = res.passwortvalidation;
    this.user.setImageBase(this.backend.getServiceBase());
    this.backend.setHeader('Accept-Language', this.user.getSchemaLocale());
    this.logger.debug('Setting client locale to \'' + defaultClientLocale + '\'');
    this.translate.use(this.user.userSettings.clientlocale);
    this.user.uiDirection = (this.config.getClientLocales().find(l => l.iso === defaultClientLocale) || {}).dir || Direction.LTR;

    this.userSource.next(this.user);

    this.favorites = null;
    this.favoritesSource.next(this.favorites);

    this.notifications = null;
    this.notificationsSource.next(this.notifications);
  }

  /**
   * Fetches the current users favorites
   */
  public getFavorites(): Observable<any> {

    // only favorite objects of type 'DMS_OBJECT', are accepted
    // read more: http://jira.optimal-systems.de/browse/COOL-2316
    return this.backend
      .getJson('/user/favorites')
      .pipe(
        map(res => res && res.filter(r => r.favoritetype === 'DMS_OBJECT')),
        tap(res => {
          this.favorites = res;
          this.favoritesSource.next(this.favorites);
        }));

    // .map(res => {
    //   let dmsObject = this.resolveObjectTypes(new DmsObject(res));
    //   return dmsObject;
    // });
  }

  /**
   * Soft update for the users favorites
   * @param id ID of the favorite to be updated
   * @param item The new favorite item
   * @param multi Whether or not to update multiple items
   */
  public updateFavorites(id?: string, item?: any, multi?: any[]) {
    if (this.backend.update(this.favorites, multi || [{id, item}])) {
      this.favoritesSource.next(this.favorites);
    }
  }

  /**
   * Gets the users notifications (resubmissions and subscriptions)
   * @returns Resolved by list of the users notifications
   */
  public getNotifications(): Observable<any> {
    const notificationData = [
      this.getSubscription(),
      this.getResubmission()
    ];
    return forkJoin(notificationData);
  }

  /**
   * Gets the users resubmissions
   * @returns Collection of users resubmissions
   */
  public getResubmission(): Observable<any> {
    return this.backend.getJson('/messageprovider/resubmission/list').pipe(
      tap(response => {
        this.notifications = response;
        this.notificationsSource.next(this.notifications);
      }));
  }

  /**
   * Gets the users subscriptions
   * @returns Collection of users subscriptions
   */
  public getSubscription(): Observable<any> {
    return this.backend
      .getJson('/messageprovider/subscription/list').pipe(
        tap(response => {
          this.notifications = response;
          this.notificationsSource.next(this.notifications);
        }));
  }

  /**
   * Removes a notification
   * @param id ID of the notification to be removed
   * @param type The notifications type ('SUBSCRIPTION', 'RESUBMISSION')
   */
  public removeNotifications(id: string, type: string) {
    let messagetype: string;
    switch (type) {
      case 'SUBSCRIPTION':
        messagetype = 'subscription';
        break;
      case 'RESUBMISSION':
        messagetype = 'resubmission';
        break;
      default:
        return;
    }
    return this.backend.del(`/messageprovider/${messagetype}/` + id).pipe(tap(res => this.updateNotifications('')));
  }

  /**
   * Soft update for users notifications
   */
  public updateNotifications(id?: string, item?: any, multi?: any[]) {
    if (this.backend.update(this.notifications, multi || [{id, item}])) {
      this.notificationsSource.next(this.notifications);
    }
  }

  /**
   * Gets the URI to a users avatar image
   * @param userId The users ID
   * @returns URI to the user image
   */
  public getUserImageUri(userId: string) {
    return `${this.backend.getBaseWithContext(this.backend.getServiceBase())}/organization/image/${userId}?usedefault=true`;
  }

  /**
   * Removes a favorite item
   * @param favoriteId ID of the favorite item to be removed
   */
  public removeFavorite(favoriteId: string) {
    return this.backend.del('/user/favorite/' + favoriteId).pipe(tap(res => this.updateFavorites(favoriteId)));
  }

  /**
   * Create a new favorite item for the current user
   * @param id ID of the dms object to be set up as favorite
   * @param type The object type of the dms object
   * @param title The favorites title
   */
  public createFavorite(id: string, type: string, title: string) {
    const uri = Utils.buildUri('/dms/favorite/' + id, {type, title});
    return this.backend.post(uri, {}).pipe(tap(res => this.getFavorites().subscribe()));
  }

  /**
   * @ignore
   */
  public removeFavoritesForTarget(id: string) {
    return this.backend.del('/dms/favorite/' + id).pipe(tap(
      res => {
        const toRemove = this.favorites.filter(i => i.target.id === id).map(i => Object.assign({
          id: i.id
        }));
        this.updateFavorites(null, null, toRemove);
      }));
  }

  /**
   * Gets the users recyclebin
  */
  getRecycleBin(): Observable<any> {
    return this.backend.getJson(`/user/recyclebin`).pipe(
      tap(response => {
        this.recycles = response;
        this.recyclesSource.next(this.recycles);
      }));
  }

  /**
   * Changes the users preferred lock mode and persists it on the server
   * @param lock The value to set the lock settings to
   */
  public changeLockSetting(lock: string) {
    this.user.userSettings.alwayslock = lock;
    return this.backend.put('/user/config/web', this.user.userSettings).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }

  public hasPrivilege(privilege: string): boolean {
    return !!this.user.privileges.find(priv => priv.name === privilege);
  }


  /**
   * Changes the users password and persists it on the server
   */
  changePassword(payload: ChangePasswordInterface): Observable<any> {
    return this.backend.put(`/user/password`, payload);
  }

  /**
   * Fetches the settings for the current user and stores the new User object on the session
   */
  private refreshCurrentUser() {
    return this.backend.get(this.USER_FETCH_URI).pipe(map(res => this.setCurrentUser(res)));
  }

  public validatePassword(password: string): {type: string, amount: number} {
    if (password.length < this.passwordValidationSettings.minlength) {
      return {type: 'short', amount: this.passwordValidationSettings.minlength};
    }

    if (password.replace(/[^0-9]/g, '').length < this.passwordValidationSettings.minnumber) {
      return {type: 'number', amount: this.passwordValidationSettings.minnumber};
    }

    if (password.replace(/[a-zA-Z0-9ß ]/g, '').length < this.passwordValidationSettings.minspecialchars) {
      return {type: 'specialchars', amount: this.passwordValidationSettings.minspecialchars};
    }

    return {type: 'valid', amount: null};
  }

  /**
   * Changes the users saved inbox filter terms
   * @param filterTerms The value to set the saved inbox filters list to
   */
  public changeSavedInboxFilters(filterTerms: string[]) {
    this.user.userSettings.savedInboxFilter = filterTerms;
    return this.backend.put('/user/config/web', this.user.userSettings).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }

  /**
   * Save or change the workspace of the current user
   * @param workspaceConfig The value to set the saved workspace or create a new workspace
   */
  public saveChangeWorkspace(workspaceConfig: any) {
    this.user.userSettings.workspaceOptions = workspaceConfig;
    return this.backend.put('/user/config/web', this.user.userSettings).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }

  /**
   * Get all the field definitions of an object type
   * @param type The object type
   * @param contextType The context type
   */

  public getFieldDefinition(type: string, contextType?: string) {
    const contextTypeDefault = 'sysfolder';
    let mode = 'ALL';
    return this.backend.get(`/user/config/result/${type}?contexttype=${contextType ? contextType : contextTypeDefault}&mode=${mode}`).pipe(map(definition => {
      definition.elements.forEach(el => {
        if (el.system) {
          el.label = this.translate.instant('eo.global.baseparam.' + el.name);
        }
      });
      return definition;
    }));
  }

  /**
   * Save or change the visibility state of dashboard toolbar for the current user
   * @param toolbarVisibility The visibility state
   */
  public saveToolbarState(toolbarVisibility: boolean) {
    this.user.userSettings.toolbarVisibility = toolbarVisibility;
    return this.backend.put('/user/config/web', this.user.userSettings).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }

  /**
 * Save or change the task list of the current user
 * @param Tasks state
 */
  public saveTodoWidget(task: TodoWidgetConfig[]) {
    this.user.userSettings.tasks = task;
    return this.backend.put('/user/config/web', this.user.userSettings).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }


  /**
   * Save the local storage settings
   * @param localSettings The local settings to be saved from the localstorage
   * @param cacheSettings The local settings to be saved from the app cache
   */
  public saveLocalSettings(localSettings: any, cacheSettings: any) {
    return this.backend.put('/user/config/localSettings', {localSettings: localSettings, cacheSettings: cacheSettings}).pipe(map(() => {
      this.refreshCurrentUser().subscribe();
    }));
  }

  /**
   * Loads the local storage settings
   * @returns The saved settings
   */
  public loadLocalSettings(): Observable<any> {
    return this.backend.get('/user/config/localSettings').pipe(catchError(() => EMPTY));
  }
}

results matching ""

    No results matching ""