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

8
9
import {CookieService } from 'ngx-cookie-service';
import {MatTableDataSource } from '@angular/material';
Lukas Burgey's avatar
Lukas Burgey committed
10

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

15
16
import {environment } from '../environments/environment';
import {IdP, User, Service, AuthInfo, AllAuthInfo, UserState, SSHKey, NewSSHKey } from './types/types.module';
Lukas Burgey's avatar
Lukas Burgey committed
17

Lukas Burgey's avatar
Lukas Burgey committed
18
19
20
21
22
23
24

@Injectable()
export class UserService {
  public loggedIn = false;
  public user: User;
  public sshKeyData: MatTableDataSource<any>;
  public userInfoData: MatTableDataSource<any>;
25
  public services: Service[];
Lukas Burgey's avatar
Lukas Burgey committed
26
27
28
29
30
31


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

37
38
  public setIdPPreference(idp: IdP) {
    this.cookieService.set(environment.idpCookieName, String(idp.id));
Lukas Burgey's avatar
Lukas Burgey committed
39
40
  }

41
42
43
44
45
46
  public errorHandler(error: any): void {
    if (error.status === 500) {
      this.snackBar.open('Server Error');
    }
  }

47
48
  public getIdPPreference(): Observable<AllAuthInfo> {
    let idpID = Number(this.cookieService.get(environment.idpCookieName));
Lukas Burgey's avatar
Lukas Burgey committed
49

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    return this.http.get('/backend/auth/v1/info/').map(
      (authInfo: 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,
        };
      }
67
68
69
70
71
    ).catch(
      (error: any) => {
        this.errorHandler(error);
        return Observable.of(null);
      }
72
    );
Lukas Burgey's avatar
Lukas Burgey committed
73
74
  }

75
  public updateData(data: any) {
76
77
78
79
    if (data['error']) {
      this.snackBar.open(data['error']);
    }

Lukas Burgey's avatar
Lukas Burgey committed
80
81
    if (!this.services) {
      this.services = data.services;
82
83
84
85
86
87
88
89
90
91
92
93
94
    }
    this.user = data.user;

    if (this.user) {
      // build sshKeyData
      if ('ssh_keys' in this.user) {
        this.sshKeyData = new MatTableDataSource(this.user.ssh_keys);
      } else {
        this.sshKeyData = null;
      }

      // build userInfoData
      const userInfoList = [];
Lukas Burgey's avatar
Lukas Burgey committed
95
96
97
      for (const key in this.user.userinfo) {
        if (this.user.userinfo.hasOwnProperty(key)) {
          userInfoList.push({name: key, info: this.user.userinfo[key]});
Lukas Burgey's avatar
Lukas Burgey committed
98
        }
99
100
101
102
103
104
105
      }
      this.userInfoData = new MatTableDataSource(userInfoList);

    } else {
      this.sshKeyData = null;
      this.userInfoData = null;
    }
106
107
108
109
110
111
112

    if (!this.loggedIn && data.logged_in) {
      this.snackBar.open('Logged in');
      // TODO dirty
      this.connectLiveUpdates()
    }
    this.loggedIn = data.logged_in;
Lukas Burgey's avatar
Lukas Burgey committed
113
114
115
  }

  public updateState() {
Lukas Burgey's avatar
Lukas Burgey committed
116
117
118
    this.http
      .get('/backend/api/state/')
      .subscribe(
119
        (data: UserState) => {
120
          this.updateData(data);
Lukas Burgey's avatar
Lukas Burgey committed
121
122
123
124
125
126
127
128
        },
        (err: HttpErrorResponse) => {
          console.log('Error', err);
          this.snackBar.open('Error receiving data from the server');
        }
      );
  }

Lukas Burgey's avatar
Lukas Burgey committed
129
130
131
132
  public update() {
    this.updateState();
  }

133
134
  public login(idp: IdP) {
    this.setIdPPreference(idp);
Lukas Burgey's avatar
Lukas Burgey committed
135
    window.location.href = 'https://hdf-portal.data.kit.edu/backend/auth/v1/request/';
136
137
  }

Lukas Burgey's avatar
Lukas Burgey committed
138
  public logout() {
Lukas Burgey's avatar
Lukas Burgey committed
139
    this.http.post('/backend/auth/v1/logout/', {}).subscribe(
Lukas Burgey's avatar
Lukas Burgey committed
140
      data => {
Lukas Burgey's avatar
Lukas Burgey committed
141
        this.updateData(data);
Lukas Burgey's avatar
Lukas Burgey committed
142
143
144
145
      }
    );
  }

146
  public addSshKey(key: NewSSHKey) {
Lukas Burgey's avatar
Lukas Burgey committed
147
148
149
150
151
152
    const body = {
      'type': 'add',
      'key': key,
    };
    return this.http.post('/backend/api/sshkey/', body).subscribe(
      data => {
153
        this.updateData(data);
Lukas Burgey's avatar
Lukas Burgey committed
154
155
156
157
      },
      (err) => {
        this.snackBar.open('Error uploading key');
        console.log(err);
158
        this.update();
Lukas Burgey's avatar
Lukas Burgey committed
159
160
161
162
      }
    );
  }

163
  public removeSshKey(key: SSHKey) {
Lukas Burgey's avatar
Lukas Burgey committed
164
165
    const body = {
      'type': 'remove',
166
      'id': key.id,
Lukas Burgey's avatar
Lukas Burgey committed
167
168
169
    };
    return this.http.post('/backend/api/sshkey/', body).subscribe(
      (data) => {
170
        this.updateData(data);
Lukas Burgey's avatar
Lukas Burgey committed
171
172
173
174
      },
      (err) => {
        this.snackBar.open('Error deleting key');
        console.log(err);
175
176
177
178
179
        this.update();
      }
    );
  }

180
  public addDeployment(service: Service, key: SSHKey) {
181
182
    const body = {
      'type': 'add',
183
184
      'key': key.id,
      'service': service.id,
185
186
187
    };
    return this.http.post('/backend/api/deployments/', body).subscribe(
      (data) => {
188
        this.snackBar.open('Deployed key ' + key.name);
189
190
191
        this.updateData(data);
      },
      (err) => {
192
        this.snackBar.open('Error deploying key ' + key.name);
193
194
195
196
197
198
        console.log(err);
        this.update();
      }
    );
  }

199
  public removeDeployment(service: Service, key: SSHKey) {
200
201
    const body = {
      'type': 'remove',
202
203
      'key': key.id,
      'service':  service.id,
204
    };
205

206
207
    return this.http.post('/backend/api/deployments/', body).subscribe(
      (data) => {
208
        this.snackBar.open('Withdrew key ' + key.name);
209
210
211
        this.updateData(data);
      },
      (err) => {
212
        this.snackBar.open('Error withdrawing key ' + key.name);
213
214
        console.log(err);
        this.update();
Lukas Burgey's avatar
Lukas Burgey committed
215
216
217
      }
    );
  }
Lukas Burgey's avatar
Lukas Burgey committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231

  public deleteUser() {
    return this.http.delete('/backend/api/delete_user/').subscribe(
      (data) => {
        this.snackBar.open('Deleted user from server');
        this.updateData(data);
      },
      (err) => {
        this.snackBar.open('Error deleting user from server');
        console.log(err);
        this.update();
      }
    );
  }
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

  public initStomp() {
    // handle with care
    let login = this.user.id
    let passcode = this.cookieService.get('sessionid');

    const stompConfig: StompConfig = {
      // Which server?
      url: 'wss://hdf-portal.data.kit.edu:15671/ws',

      // Headers
      // Typical keys: login, passcode, host
      headers: {
        login: 'webpage-client:' + login,
        passcode: passcode,
      },

      // 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,

      // Will log diagnostics on console
      debug: true
    };
    this._stompService.config = stompConfig;
    this._stompService.initAndConnect();
  }

  public connectLiveUpdates() {
    this.initStomp();
    let subscription = this._stompService.subscribe(
      '/exchange/update/' + this.user.id.toString()
    );

    subscription.map((message: Message) => {
      return message.body;
    }).subscribe((msg_body: string) => {
      this.snackBar.open(
        'Backend: ' + msg_body
      );
      console.log(`Received: ${msg_body}`);
    });
  }


Lukas Burgey's avatar
Lukas Burgey committed
282
}