rsanchez
2017-03-02 3a29297e886c8f4cc247e065df9a60d6177514a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { Http, RequestOptions, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { LocalStorageService } from 'angular-2-local-storage';
const SECURIS_TOKEN = "X-SECURIS-TOKEN";
@Injectable()
export class UserService {
  constructor(private router: Router,
              private store: LocalStorageService, 
              private http: Http) {
    
  }
  public login(username: string, password: string) : Observable<string> {
    let params = new URLSearchParams();
    params.append('username', username);
    params.append('password', password);
    let options = new RequestOptions({ headers: new Headers({ "Content-Type": "application/x-www-form-urlencoded" })});
    return this.http.post('user/login', params, options)
                    .map((res: Response) => {
                        let data = res.json();
                        this.store.set('username', username);
                               this.store.set('token', data.token);
                        return <string>data.token;
                      })
                    .catch(this.handleError);
  }
  isLoggedIn() : Observable<Boolean> {
    if (!this.existsToken()) {
      return Observable.of(false);
    }
    var token = this.store.get(SECURIS_TOKEN);
    return this.http.get('check', new RequestOptions({ headers: new Headers({ 'X-SECURIS-TOKEN': token }) }))
                    .map((res: Response) => {
                        let body = res.json();
                        if (body.valid) {
                          this.store.set('user', body.user);
                        }
                        return body.valid;
                      })
                    .catch(this.handleError)
                    .catch(() => Observable.of(false));
  }
  existsToken() : Boolean {
    return this.store.get(SECURIS_TOKEN) !== null;
  }
  logout() : void {
    this.store.remove('user', 'token');
    this.router.navigate(['Login']);
  }
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}