Project

General

Profile

1
import { Injectable } from '@angular/core';
2
import { ActivatedRoute, Router } from '@angular/router';
3
import { HttpClient } from '@angular/common/http';
4
import { environment } from '../../environments/environment';
5
import { deleteCookie, getCookie } from '../domain/utils';
6

    
7
@Injectable()
8
export class AuthenticationService {
9

    
10
  constructor(private route: ActivatedRoute,
11
              private router: Router,
12
              private http: HttpClient) {}
13

    
14
  private apiUrl: string = environment.API_ENDPOINT;
15
  private loginUrl = environment.API_ENDPOINT + '/openid_connect_login';
16

    
17
  // store the URL so we can redirect after logging in
18
  public redirectUrl: string;
19

    
20
  private _storage: Storage = sessionStorage;
21

    
22
  private cookie: string = null;
23

    
24
  isLoggedIn: boolean = false;
25

    
26
  public loginWithState() {
27
    console.log(`logging in with state. Current url is: ${this.router.url}`);
28
    if (this.redirectUrl) {
29
      const url = this.redirectUrl;
30
      this.redirectUrl = null;
31
      console.log('stored location', url);
32
      sessionStorage.setItem('state.location', url);
33
    } else {
34
      /*sessionStorage.setItem("state.location", this.router.url);*/
35
      sessionStorage.setItem('state.location', '/join');
36
    }
37
    console.log('redirect location', sessionStorage.getItem('state.location'));
38
    window.location.href = this.loginUrl;
39
  }
40

    
41
  public logout() {
42
    deleteCookie('AccessToken');
43
    sessionStorage.clear();
44
    this.isLoggedIn = false;
45

    
46
    console.log('logging out, calling:');
47
    console.log(`${this.apiUrl}/openid_logout`);
48

    
49
    /*window.location.href = `${this.apiUrl}/openid_logout`;*/
50
    window.location.href = `${environment.AAI_LOGOUT + window.location.origin + this.apiUrl}/openid_logout`;
51
  }
52

    
53
  public tryLogin() {
54
    this.cookie = getCookie('AccessToken');
55
    if (this.cookie && this.cookie !== '') {
56
      // console.log(`I got the cookie!`);
57
      // console.log(`in tryLogin -> document.cookie is: ${document.cookie.toString()}`);
58
      /* SETTING INTERVAL TO REFRESH SESSION TIMEOUT COUNTDOWN */
59
      setInterval(() => {
60
        this.http.get(this.apiUrl + '/user/login', { withCredentials: true }).subscribe(
61
          userInfo => {
62
            // console.log('User is still logged in');
63
            // console.log(userInfo);
64
            this.isLoggedIn = true;
65
          },
66
          () => {
67
            this.logout();
68
          },
69
          () => {
70
            this.cookie = getCookie('AccessToken');
71
            if ( !this.cookie || this.cookie === '') {
72
              this.logout();
73
            }
74
          }
75
        );
76
        /*this.redirectUrl = window.location.pathname;
77
        this.loginWithState();*/
78

    
79
      }, 1000 * 60 * 5);
80
      if (!this.getIsUserLoggedIn()) {
81
        // console.log(`session.name wasn't found --> logging in via repo-service!`);
82
        this.http.get(this.apiUrl + '/user/login', { withCredentials: true }).subscribe(
83
          userInfo => {
84
            // console.log(userInfo);
85
            sessionStorage.setItem('name', userInfo['name']);
86
            sessionStorage.setItem('email', userInfo['email'].trim());
87
            sessionStorage.setItem('role', userInfo['role']);
88
            this.isLoggedIn = true;
89
            // console.log(`the current user is: ${sessionStorage.getItem('name')},
90
            //              ${sessionStorage.getItem('email')}, ${sessionStorage.getItem('role')}`);
91
          },
92
          error => {
93
            sessionStorage.clear();
94
            console.log('Error!');
95
            console.log(error);
96
            deleteCookie('AccessToken');
97
            deleteCookie('AccessToken');
98
            this.isLoggedIn = false;
99
            this.router.navigate(['/home']);
100
          },
101
          () => {
102
            if ( sessionStorage.getItem('state.location') ) {
103
              const state = sessionStorage.getItem('state.location');
104
              sessionStorage.removeItem('state.location');
105
              console.log(`tried to login - returning to state: ${state}`);
106
              if ( !this.getIsUserLoggedIn() ) {
107
                // console.log('user hasn\'t logged in yet -- going to home');
108
                this.router.navigate(['/home']);
109
              } else {
110
                this.router.navigate([state]);
111
              }
112
            }
113
          }
114
        );
115
      } else {
116
        this.isLoggedIn = true;
117
        // console.log(`the current user is: ${sessionStorage.getItem('name')},
118
        //              ${sessionStorage.getItem('email')}, ${sessionStorage.getItem('role')}`);
119
        if (this.redirectUrl) {
120
          const url = this.redirectUrl;
121
          this.redirectUrl = null;
122
          this.router.navigate([url]);
123
          // console.log('route is', url);
124
        }
125
      }
126
    }
127
  }
128

    
129
  public getIsUserLoggedIn() {
130
    // todo: probably not all of them are needed
131
    return this.isLoggedIn && this.cookie && this.cookie !== '' && sessionStorage.getItem('email') !== null;
132
  }
133

    
134
  public getUserName() {
135
    if (this.isLoggedIn) {
136
      return sessionStorage.getItem('name');
137
    } else {
138
      return '';
139
    }
140
  }
141

    
142
  public getUserEmail() {
143
    if (this.getIsUserLoggedIn()) {
144
      return sessionStorage.getItem('email');
145
    } else {
146
      return '';
147
    }
148
  }
149

    
150
  public getUserRole() {
151
    if (this.isLoggedIn) {
152
      return sessionStorage.getItem('role');
153
    } else {
154
      return '';
155
    }
156
  }
157

    
158
}
(3-3/13)