summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/api/auth.service.ts
blob: 8a291799235b398f24b14c990269627764df4c6b (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import * as _ from 'lodash';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

import { Credentials } from '../models/credentials';
import { LoginResponse } from '../models/login-response';
import { AuthStorageService } from '../services/auth-storage.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(
    private authStorageService: AuthStorageService,
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  check(token: string) {
    return this.http.post('api/auth/check', { token: token });
  }

  login(credentials: Credentials): Observable<LoginResponse> {
    return this.http.post('api/auth', credentials).pipe(
      tap((resp: LoginResponse) => {
        this.authStorageService.set(
          resp.username,
          resp.permissions,
          resp.sso,
          resp.pwdExpirationDate,
          resp.pwdUpdateRequired
        );
      })
    );
  }

  logout(callback: Function = null) {
    return this.http.post('api/auth/logout', null).subscribe((resp: any) => {
      this.authStorageService.remove();
      const url = _.get(this.route.snapshot.queryParams, 'returnUrl', '/login');
      this.router.navigate([url], { skipLocationChange: true });
      if (callback) {
        callback();
      }
      window.location.replace(resp.redirect_url);
    });
  }
}