idp.service.ts 2.16 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { CookieService } from 'ngx-cookie-service';
import {environment} from '../environments/environment';

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();
  }

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

40
  private apiCall(): void {
Lukas Burgey's avatar
Lukas Burgey committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
      // 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);
        }
      );

  }

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

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

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

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