idp.service.ts 2.1 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1 2 3
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

4
import { Observable, BehaviorSubject  } from 'rxjs';
Lukas Burgey's avatar
Lukas Burgey committed
5 6 7

import { CookieService } from 'ngx-cookie-service';

8
import { environment } from '../environments/environment';
Lukas Burgey's avatar
Lukas Burgey committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import { IdP, AuthInfo } from './types/types.module';

@Injectable({
  providedIn: 'root'
})
export class IdpService {

  idps: IdP[];
  idps$: BehaviorSubject<IdP[]>;

  selectedIdp: IdP;
  selectedIdp$: BehaviorSubject<IdP>;

  constructor(
    public http: HttpClient,
    public cookieService: CookieService,
  ) {
    this.initializeDataService();
  }

29
  private initializeDataService() {
Lukas Burgey's avatar
Lukas Burgey committed
30
    if (!this.idps$) {
31
      this.idps$ = <BehaviorSubject<IdP[]>> new BehaviorSubject(undefined);
Lukas Burgey's avatar
Lukas Burgey committed
32 33
    }
    if (!this.selectedIdp$) {
34
      this.selectedIdp$ = <BehaviorSubject<IdP>> new BehaviorSubject(undefined);
Lukas Burgey's avatar
Lukas Burgey committed
35 36 37 38
    }
    this.apiCall();
  }

39
  private apiCall(): void {
Lukas Burgey's avatar
Lukas Burgey committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
      // initialize the subject with data
      this.http.get('/backend/auth/v1/info').subscribe(
        (info: AuthInfo) => {
          this.idps = info.idps;
          this.idps$.next(this.idps);

          let preferredIdP: IdP = this.idps.find((idp: IdP) => idp.id === this.getIdPPreference());
          let defaultIdP: IdP = this.idps.find((idp: IdP) => idp.id === info.default);

          if (preferredIdP) {
            this.selectedIdp = preferredIdP;
          } else if (defaultIdP) {
            this.selectedIdp = defaultIdP;
          } else if (this.idps.length > 0) {
            this.selectedIdp = this.idps[0];
          } else {
            console.log("No IdPs available. Unable to login");
          }

          this.selectedIdp$.next(this.selectedIdp);
        }
      );

  }

65 66
  private getIdPPreference(): number {
    return Number(this.cookieService.get(environment.idpCookieName));
Lukas Burgey's avatar
Lukas Burgey committed
67 68
  }

69
  public subscribeIdps(): Observable<IdP[]> {
Lukas Burgey's avatar
Lukas Burgey committed
70 71 72
    return this.idps$.asObservable();
  }

73
  public subscribeSelectedIdp(): Observable<IdP> {
Lukas Burgey's avatar
Lukas Burgey committed
74 75 76
    return this.selectedIdp$.asObservable();
  }

77
  public setIdPPreference(idp: IdP) {
Lukas Burgey's avatar
Lukas Burgey committed
78 79 80
    this.cookieService.set(environment.idpCookieName, String(idp.id));
  }
}