user.service.ts 6.98 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
Lukas Burgey's avatar
Lukas Burgey committed
3
4
5
6
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
Lukas Burgey's avatar
Lukas Burgey committed
7
8
9
10
11

import {CookieService} from 'ngx-cookie-service';
import {MatTableDataSource} from '@angular/material';

import {SnackBarService} from './snackbar.service';
12
13
import {StompConfig, StompRService} from '@stomp/ng2-stompjs';
import {Message} from '@stomp/stompjs';
Lukas Burgey's avatar
Lukas Burgey committed
14

Lukas Burgey's avatar
Lukas Burgey committed
15
import {environment} from '../environments/environment';
Lukas Burgey's avatar
Lukas Burgey committed
16
import * as t from './types/types.module';
Lukas Burgey's avatar
Lukas Burgey committed
17

Lukas Burgey's avatar
Lukas Burgey committed
18
19
20

@Injectable()
export class UserService {
Lukas Burgey's avatar
Lukas Burgey committed
21
22
23
24
  private _loggedIn: boolean = false;

  public user: t.User;
  public userState: t.UserState;
Lukas Burgey's avatar
Lukas Burgey committed
25

26
  public messages: string[] = [];
27
28
  // local copy of services
  public services: t.Service[] = [];
Lukas Burgey's avatar
Lukas Burgey committed
29
30
31
32
33
34


  constructor(
    public cookieService: CookieService,
    public http: HttpClient,
    public snackBar: SnackBarService,
35
    private _stompService: StompRService,
Lukas Burgey's avatar
Lukas Burgey committed
36
  ) {
Lukas Burgey's avatar
Lukas Burgey committed
37
    this.update();
Lukas Burgey's avatar
Lukas Burgey committed
38
39
  }

Lukas Burgey's avatar
Lukas Burgey committed
40
41
42
43
44
  // PRIVATE API
  private initStomp() {
    // handle with care
    let login = this.user.id
    let passcode = this.cookieService.get('sessionid');
Lukas Burgey's avatar
Lukas Burgey committed
45

Lukas Burgey's avatar
Lukas Burgey committed
46
47
48
    const stompConfig: StompConfig = {
      // Which server?
      url: 'wss://hdf-portal.data.kit.edu/ws',
49

Lukas Burgey's avatar
Lukas Burgey committed
50
51
52
53
54
55
      // Headers
      // Typical keys: login, passcode, host
      headers: {
        login: 'webpage-client:' + login,
        passcode: passcode,
      },
Lukas Burgey's avatar
Lukas Burgey committed
56

Lukas Burgey's avatar
Lukas Burgey committed
57
58
59
60
61
62
63
64
      // How often to heartbeat?
      // Interval in milliseconds, set to 0 to disable
      heartbeat_in: 0, // Typical value 0 - disabled
      heartbeat_out: 20000, // Typical value 20000 - every 20 seconds
      // Wait in milliseconds before attempting auto reconnect
      // Set to 0 to disable
      // Typical value 5000 (5 seconds)
      reconnect_delay: 5000,
65

Lukas Burgey's avatar
Lukas Burgey committed
66
67
68
69
70
      // Will log diagnostics on console
      debug: false,
    };
    this._stompService.config = stompConfig;
    this._stompService.initAndConnect();
Lukas Burgey's avatar
Lukas Burgey committed
71
72
  }

Lukas Burgey's avatar
Lukas Burgey committed
73
74
75
76
77
  private connectLiveUpdates() {
    this.initStomp();
    let subscription = this._stompService.subscribe(
      '/exchange/update/' + this.user.id.toString()
    );
78

Lukas Burgey's avatar
Lukas Burgey committed
79
80
81
82
83
84
85
    subscription.map((message: Message) => {
      return message.body;
    }).subscribe((body: any) => {
      let json = JSON.parse(body);
      if (json.message && json.message != '') {
        this.snackBar.open(json.message);
        this.messages.push(json.message);
86
      }
Lukas Burgey's avatar
Lukas Burgey committed
87
88
      if (json.user_state) {
        this.updateUserState(json.user_state);
89
      }
Lukas Burgey's avatar
Lukas Burgey committed
90
91
    });
  }
92

Lukas Burgey's avatar
Lukas Burgey committed
93
94
  private updateUser(newUser: t.User) {
    this.user = newUser;
Lukas Burgey's avatar
Lukas Burgey committed
95
96
  }

97
98
99
100
101
  private updateServices(newServices: t.Service[]){
    if (this.services.length !== newServices.length) {
      this.services = [];
      for (let service of newServices) {
        this.services.push(service);
Lukas Burgey's avatar
Lukas Burgey committed
102
103
104
105
      }
    }
  }

106
107
108
109
110
111
112
113
114
  private _logout() {
    this._loggedIn = false;
    this.snackBar.open('Logged out');
    this._stompService.disconnect();
    this.services = [];
    this.user = null;
    this.userState = null;
  }

Lukas Burgey's avatar
Lukas Burgey committed
115
116
117
  private updateUserState(newState: t.UserState) {
      // did a login occur?
    let login = (!this._loggedIn && newState);
Lukas Burgey's avatar
Lukas Burgey committed
118
    // did a logout occur?
Lukas Burgey's avatar
Lukas Burgey committed
119
    let logout = (this._loggedIn && !newState);
Lukas Burgey's avatar
Lukas Burgey committed
120
121
122

    // -- Value updating --
    if (login) {
Lukas Burgey's avatar
Lukas Burgey committed
123
      this._loggedIn = true;
124
      this.snackBar.open('Logged in');
125
126


127
128
      this.connectLiveUpdates()
    }
Lukas Burgey's avatar
Lukas Burgey committed
129
    if (logout) {
130
131
      this._logout()
      return
Lukas Burgey's avatar
Lukas Burgey committed
132
133
134
135
136
137
    }

    this.userState = newState;
  }

  private stateAPIUpdate(update: t.StateAPIResult) {
138
139
140
141
142
143
144
145
146
147
148
    if (update) {
      this.updateUser(update.user)
      this.updateUserState(update.user_state);
      this.updateServices(update.services);

      // report an occured error
      if (update.error) {
        this.snackBar.open(update.error);
      }
    } else {
      console.log("Got null update");
Lukas Burgey's avatar
Lukas Burgey committed
149
    }
Lukas Burgey's avatar
Lukas Burgey committed
150
151
  }

Lukas Burgey's avatar
Lukas Burgey committed
152
153
154
155
156
  private setIdPPreference(idp: t.IdP) {
    this.cookieService.set(environment.idpCookieName, String(idp.id));
  }

  // PUBLIC API
157
  public getDeployment(service: t.Service): t.Deployment {
Lukas Burgey's avatar
Lukas Burgey committed
158
159
    return this.userState.deployments.find(
      dep => {
160
        return dep.service.id === service.id;
Lukas Burgey's avatar
Lukas Burgey committed
161
162
163
      }
    );
  }
Lukas Burgey's avatar
Lukas Burgey committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
  public userInfo(): MatTableDataSource<any> {
      const userInfoList = [];
      for (const key in this.user.userinfo) {
        if (this.user.userinfo.hasOwnProperty(key)) {
          userInfoList.push({name: key, info: this.user.userinfo[key]});
        }
      }
      return new MatTableDataSource(userInfoList);
  }

  public sshKeyTable(): MatTableDataSource<any> {
      return new MatTableDataSource(this.user.ssh_keys);
  }

  public loggedIn():boolean {
    if (this.userState) {
      return true;
    }
    return false;
  }

  public update() {
Lukas Burgey's avatar
Lukas Burgey committed
186
    this.http
187
      .get('/backend/api/state')
Lukas Burgey's avatar
Lukas Burgey committed
188
      .subscribe(
Lukas Burgey's avatar
Lukas Burgey committed
189
190
        (data: t.StateAPIResult) => {
          this.stateAPIUpdate(data);
Lukas Burgey's avatar
Lukas Burgey committed
191
192
193
194
195
196
197
198
        },
        (err: HttpErrorResponse) => {
          console.log('Error', err);
          this.snackBar.open('Error receiving data from the server');
        }
      );
  }

Lukas Burgey's avatar
Lukas Burgey committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
  public errorHandler(error: any): void {
    if (error.status === 500) {
      this.snackBar.open('Server Error');
    }
  }

  public getIdPPreference(): Observable<t.AllAuthInfo> {
    let idpID = Number(this.cookieService.get(environment.idpCookieName));

    return this.http.get('/backend/auth/v1/info').map(
      (authInfo: t.AuthInfo) => {
        let selected = authInfo.idps[1];

        if (!idpID) {
          idpID = authInfo.default;
        }
        for (const idp of authInfo.idps) {
          if (idp.id === idpID) {
            selected = idp;
          }
        }
        return {
          idps: authInfo.idps,
          selected: selected,
        };
      }
    ).catch(
      (error: any) => {
        this.errorHandler(error);
        return Observable.of(null);
      }
    );
  }
Lukas Burgey's avatar
Lukas Burgey committed
232

Lukas Burgey's avatar
Lukas Burgey committed
233
  public login(idp: t.IdP) {
234
    this.setIdPPreference(idp);
235
    window.location.href = 'https://hdf-portal.data.kit.edu/backend/auth/v1/request';
236
237
  }

Lukas Burgey's avatar
Lukas Burgey committed
238
  public logout() {
239
    this.http.post('/backend/auth/v1/logout', {}).subscribe(
Lukas Burgey's avatar
Lukas Burgey committed
240
241
      (data: t.StateAPIResult) => {
        this.stateAPIUpdate(data);
Lukas Burgey's avatar
Lukas Burgey committed
242
243
244
      },
      (err) => {
        console.log(err);
245
        this._logout();
246
247
248
249
      }
    );
  }

250
251
  public sentQuestionnaire(stateItemID: number, answers: any) {
    return this.http.post('/backend/api/questionnaire?id='+String(stateItemID), answers).subscribe(
Lukas Burgey's avatar
Lukas Burgey committed
252
      (data: t.UserState) => {
Lukas Burgey's avatar
Lukas Burgey committed
253
254
        this.snackBar.open('Uploaded questionnaire');
        //this.snackBar.open('Deployed key ' + key.name);
Lukas Burgey's avatar
Lukas Burgey committed
255
        this.updateUserState(data);
Lukas Burgey's avatar
Lukas Burgey committed
256
257
258
259
      },
      (err) => {
        this.snackBar.open('Error uploading questionnaire');
        console.log(err);
Lukas Burgey's avatar
Lukas Burgey committed
260
        this.update();
Lukas Burgey's avatar
Lukas Burgey committed
261
262
263
264
      }
    );
  }

Lukas Burgey's avatar
Lukas Burgey committed
265
266
  public deleteUser() {
    return this.http.delete('/backend/api/delete_user/').subscribe(
Lukas Burgey's avatar
Lukas Burgey committed
267
      (data: t.UserState) => {
Lukas Burgey's avatar
Lukas Burgey committed
268
        this.snackBar.open('Deleted user from server');
Lukas Burgey's avatar
Lukas Burgey committed
269
        this.updateUserState(data);
Lukas Burgey's avatar
Lukas Burgey committed
270
271
272
273
      },
      (err) => {
        this.snackBar.open('Error deleting user from server');
        console.log(err);
Lukas Burgey's avatar
Lukas Burgey committed
274
        this.update();
Lukas Burgey's avatar
Lukas Burgey committed
275
276
277
      }
    );
  }
Lukas Burgey's avatar
Lukas Burgey committed
278
}