rsanchez
2017-03-14 ce9bc0c6ad58e4117d26a204ffc56bbcdb7fe916
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
76
77
78
79
80
81
82
83
84
85
86
import { LocaleService } from './common/i18n';
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 $L: LocaleService,
              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.toString(), options)
                    .map((res: Response) => {
                        let data = res.json();
                        this.store.set('username', username);
                               this.store.set('token', data.token);
                        return <string>data.token;
                      })
                    .catch((r) => this.handleError(r));
  }
  isLoggedIn() : Observable<Boolean> {
    if (!this.existsToken()) {
      return Observable.of(false);
    }
    var token = this.store.get("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((r) => this.handleError(r))
                    .catch(() => Observable.of(false));
  }
  existsToken() : Boolean {
    return this.store.get("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 err = JSON.stringify(error);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    if (error.status === 403 /* forbidden */ || error.status === 401 /* unauthorized */) {
      errMsg = this.$L.get('Invalid credentials');
    } else if (error.status === 418 /* Teapot */) {
      errMsg = this.$L.get(error.headers.get('X-SECURIS-ERROR-MSG'));
    } else {
      console.error(error);
      errMsg = this.$L.get(`Unexpected error HTTP (${error.status}) accessing to server. Contact with the administrator.`);
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}