File

src/lib/service/auth/auth.service.ts

Description

AuthService handles authentication against an yuuvis® RAD backend.

Index

Properties
Methods

Methods

Public isLoggedIn
isLoggedIn()

Get the current state of a user being logged in. This is kind of the synchronous version of subscribing to authenticated$.

Returns : boolean

True if there is a logged in user, false otherwise

Public login
login(host: string, username: string, password: string)

Login a user using form based login.

Parameters :
Name Type Optional Description
host string no

The target host (could be null if you are running in web environment)

username string no

The username

password string no

The password

Returns : Observable<EoUser>

Resolves with the logged in user

Public logout
logout(gatewayLogout?: boolean)

Logs out the current user.

Parameters :
Name Type Optional Description
gatewayLogout boolean yes

Flag indicating whether or not to perform a gateway logout as well

Returns : void

Properties

Public authenticated$
authenticated$: Observable<boolean>
Type : Observable<boolean>
Default value : this.authSource.asObservable()

Observable to subscribe to for getting the state of being authenticated. Will emit true when a user logged in, false when the user logged out or the gateways session timed out.

Public gatewayInfo
gatewayInfo: GatewayInfo
Type : GatewayInfo

AuthService

AuthService handles authentication against an yuuvis® RAD backend.

import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Inject, Injectable} from '@angular/core';
import {
  BehaviorSubject, Observable,
  forkJoin as observableForkJoin,
} from 'rxjs';
import {map, switchMap, tap} from 'rxjs/operators';
import {CoreConfig} from '../../config/core-config';
import {CORE_CONFIG} from '../../config/core-init.tokens';
import {EoUser} from '../../model/eo-user.model';
import {BackendService} from '../backend/backend.service';
import {BpmService} from '../bpm/bpm.service';
import {CapabilitiesService} from '../capabilities/capabilities.service';
import {Config} from '../config/config.service';
import {EventService} from '../events/event.service';
import {EnaioEvent} from '../events/events';
import {InboxService} from '../inbox/inbox.service';
import {PrepareService} from '../prepare/prepare.service';
import {LocalStorageService} from '../storage/local-storage.service';
import {SystemStatusService} from '../system-status/system-status.service';
import {SystemService} from '../system/system.service';
import {UserService} from '../user/user.service';
import {AuthProfile} from './auth-profile.interface';
import {GatewayInfo} from './gateway-info.interface';
import {Utils} from '../../util/utils';
import {EnvironmentEnaio} from '../../environment.enaio';

/**
 * `AuthService` handles authentication against an yuuvis<sup>&reg;</sup> RAD backend.
 */
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private userProfileUri = this.userService.USER_FETCH_URI;
  private authSource = new BehaviorSubject<boolean>(false);
  private loggedInCacheKey = 'eo.user.loggedIn';

  /**
   * Observable to subscribe to for getting the state of being authenticated. Will emit true when a user logged in,
   * false when the user logged out or the gateways session timed out.
   */
  public authenticated$: Observable<boolean> = this.authSource.asObservable();

  /**
   * @ignore
   */
  public hosts: string[] = [];
  public gatewayInfo: GatewayInfo;

  /**
   * @ignore
   */
  public profile: AuthProfile = {
    host: '',
    user: null,
    auth: null,
    active: false
  };

  /**
   * @ignore
   */
  constructor(private config: Config,
    @Inject(CORE_CONFIG) public coreConfig: CoreConfig,
    private http: HttpClient,
    private bpmService: BpmService,
    private capabilitiesService: CapabilitiesService,
    private inboxService: InboxService,
    private prepareService: PrepareService,
    private backend: BackendService,
    private systemService: SystemService,
    private userService: UserService,
    private eventService: EventService,
    private systemStatusService: SystemStatusService,
    protected local: LocalStorageService) {
    window.addEventListener('storage', evt => {
      if (evt.key === this.loggedInCacheKey) {
        const host = JSON.parse(evt.newValue).host;
        this.initUser(host).subscribe();
      }
    });
  }

  /**
   * Login a user using form based login.
   * @param host The target host (could be null if you are running in web environment)
   * @param username The username
   * @param password The password
   * @returns Resolves with the logged in user
   */
  public login(host: string, username: string, password: string): Observable<EoUser> {

    host = host || '';
    const fd = new FormData();
    fd.append('username', encodeURIComponent(username));
    fd.append('password', encodeURIComponent(password));

    const loginHeader = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded'
    });
    return this.http.post(host + this.config.getContextPath() + '/login',
      `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`, {
      headers: loginHeader,
      responseType: 'text',
      withCredentials: this.coreConfig.withCredentials
    }).pipe(
      switchMap(() => this.initUser(host))
    );
  }

  /**
   * Gets called while app init
   * @ignore
   */
  initUser(host?: string) {

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    return this.http
      .get(`${host || ''}${this.config.getContextPath()}/auth/info`, {headers, withCredentials: this.coreConfig.withCredentials})
      .pipe(switchMap((info: GatewayInfo) => {
        this.gatewayInfo = info;
        return this.fetchUser(info, host)
      }));
  }

  /**
   *
   * @param gatewayInfo
   * @param host
   * @returns Observable<EoUser>
   */
  private fetchUser(gatewayInfo: any, host?: string): Observable<EoUser> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    this.backend.setAuthProfile({host: host || ''});
    return this.backend
      .get(this.userProfileUri, '', {headers, withCredentials: this.coreConfig.withCredentials})
      .pipe(
        switchMap((user: any) => {
          this.profile = {
            host: host || '',
            user: user.user.name,
            auth: null,
            active: true
          };
          if (host) {
            this.addHostConfig(host);
          }
          if (this.local.isEmpty()) {
            this.userService.loadLocalSettings().subscribe(settings => {
              this.local.setStorage(settings.localSettings);
            });
          }
          window.localStorage.setItem(this.loggedInCacheKey, JSON.stringify({userId: user.user.id, host: host}));
          return this.initApp(user, gatewayInfo.ntlm);
        }),
        tap(() => this.authSource.next(this.isLoggedIn()))
      );
  }

  /**
   * Logs out the current user.
   * @param gatewayLogout Flag indicating whether or not to perform a gateway logout as well
   */
  public logout(gatewayLogout?: boolean) {

    this.authSource.next(false);
    this.systemStatusService.stop();

    this.profile = {
      host: '',
      user: null,
      auth: null,
      active: false
    };

    if (this.gatewayInfo && this.gatewayInfo.external) {
      (window as any).location.href = this.config.getContextPath() + '/logout';
      return;
    }

    if (gatewayLogout) {
      (window as any).location.href = this.config.getContextPath() + '/logout?fallbackredir=' + Utils.getBaseHref();
    }

    this.backend.setAuthProfile(this.profile);
    this.eventService.trigger(EnaioEvent.LOGOUT);
  }

  /**
   * for desktop and mobile devices we provide a list of hosts for the login
   *
   * @param string host
   */
  private addHostConfig(host: string) {
    const existingHost = this.hosts.find(h => h === host);
    if (!existingHost) {
      this.hosts.push(host);
    }
  }

  /**
   * Get the current state of a user being logged in. This is kind of the synchronous version of subscribing to `authenticated$`.
   * @returns True if there is a logged in user, false otherwise
   */
  public isLoggedIn(): boolean {
    return this.profile.user !== null;
  }

  /**
   *
   * @param user
   * @param boolean sso
   * @returns Observable<EoUser>
   */
  private initApp(user: any, sso?: boolean): Observable<EoUser> {

    const currUser = new EoUser(user);
    this.backend.setAuthProfile(this.profile);
    this.userService.setCurrentUser(user);
    const capabilities = this.capabilitiesService.setCapabilities(
      user.capabilities, sso);

    this.systemStatusService.init(this.config.getRaw('systemStatusUpdateInterval'));

    // update states
    if (capabilities.inbox) {
      this.inboxService.refreshInboxState();
    }
    if (capabilities.intray) {
      this.prepareService.refreshPreparedItemsCount();
    }

    const todo = [
      this.bpmService.initExecutableProcesses(),
      this.systemService.getSystemDefinition(currUser)
    ];

    return observableForkJoin(todo).pipe(
      map(() => currUser)
    );
  }
}

results matching ""

    No results matching ""