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 = localStorage;
21

    
22
  public activateFrontAuthorization: boolean = environment.production;
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', '/dashboard');
36
    }
37
    console.log('redirect location', sessionStorage.getItem('state.location'));
38
    window.location.href = this.loginUrl;
39
  }
40

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

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

    
51
    /*window.location.href = `${this.apiUrl}/openid_logout`;*/
52
    window.location.href = `https://aai.openaire.eu/proxy/saml2/idp/SingleLogoutService.php?ReturnTo=${this.apiUrl}/openid_logout`;
53
  }
54

    
55
  public tryLogin() {
56
    if ( getCookie('openAIREUser') && (getCookie('openAIREUser') !== '') ) {
57
      console.log(`I got the cookie!`);
58
      console.log(`in tryLogin -> document.cookie is: ${document.cookie.toString()}`);
59
      /* SETTING INTERVAL TO REFRESH SESSION TIMEOUT COUNTDOWN */
60
      setInterval(() => {
61
        this.http.get(this.apiUrl + '/user/login', { withCredentials: true }).subscribe(
62
          userInfo => {
63
            console.log('User is still logged in');
64
            console.log(userInfo);
65
            this.isLoggedIn = true;
66
          },
67
          () => {
68
            this.logout();
69
          },
70
          () => {
71
            if ( !getCookie('openAIREUser') || (getCookie('openAIREUser') === '') ) {
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
            localStorage.setItem('name', userInfo['name']);
86
            localStorage.setItem('email', userInfo['email'].trim());
87
            localStorage.setItem('role', userInfo['role']);
88
            this.isLoggedIn = true;
89
            console.log(`the current user is: ${localStorage.getItem('name')},
90
                         ${localStorage.getItem('email')}, ${localStorage.getItem('role')}`);
91
          },
92
          error => {
93
            localStorage.clear();
94
            sessionStorage.clear();
95
            console.log('Error!');
96
            console.log(error);
97
            deleteCookie('openAIREUser');
98
            deleteCookie('AccessToken');
99
            this.isLoggedIn = false;
100
            this.router.navigate(['/landing']);
101
          },
102
          () => {
103
            if ( sessionStorage.getItem('state.location') ) {
104
              const state = sessionStorage.getItem('state.location');
105
              sessionStorage.clear();
106
              console.log(`tried to login - returning to state: ${state}`);
107
              if ( !this.getIsUserLoggedIn() ) {
108
                console.log('user hasn\'t logged in yet -- going to landing');
109
                this.router.navigate(['/landing']);
110
              } else {
111
                this.router.navigate([state]);
112
              }
113
            }
114
          }
115
        );
116
      } else {
117
        this.isLoggedIn = true;
118
        console.log(`the current user is: ${localStorage.getItem('name')},
119
                     ${localStorage.getItem('email')}, ${localStorage.getItem('role')}`);
120
        if (this.redirectUrl) {
121
          const url = this.redirectUrl;
122
          this.redirectUrl = null;
123
          this.router.navigate([url]);
124
          console.log('route is', url);
125
        }
126
      }
127
    }
128
  }
129

    
130
  public getIsUserLoggedIn() {
131
    this.isLoggedIn = (getCookie('openAIREUser') && (getCookie('openAIREUser') !== '') && (this.getUserEmail() !== '' ) );
132
    return this.isLoggedIn;
133
  }
134

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

    
143
  public getUserEmail() {
144
    if (this.isLoggedIn) {
145
      return localStorage.getItem('email');
146
    } else {
147
      return '';
148
    }
149
  }
150

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

    
159
}
(3-3/11)