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
  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
    sessionStorage.clear();
45
    this.isLoggedIn = false;
46

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

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

    
54
  public tryLogin() {
55
    if ( getCookie('openAIREUser') && (getCookie('openAIREUser') !== '') ) {
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
            if ( !getCookie('openAIREUser') || (getCookie('openAIREUser') === '') ) {
71
              this.logout();
72
            }
73
          }
74
        );
75
        /*this.redirectUrl = window.location.pathname;
76
        this.loginWithState();*/
77

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

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

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

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

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

    
157
}
(3-3/11)