Joaquín Reñé
2026-03-27 4ee50e257b32f6ec0f72907305d1f2b1212808a4
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
import { LocaleService } from './common/i18n';
import { BasicService } from './common/utils';
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 { Locker } from 'angular-safeguard';
const SECURIS_TOKEN = "X-SECURIS-TOKEN";
@Injectable()
export class UserService extends BasicService {
  count : number = 0;
  constructor($L: LocaleService,
              private router: Router,
              private store: Locker, 
              private http: Http) {
    super($L);
  }
  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((resp) => this.mapLogin(resp))
                    .catch((err) => super.processErrorResponse(err));
  }
  private mapLogin(res : Response) : string {
    let data = res.json();
    this.store.set('user_full_name', data.full_name);
    this.store.set('username', data.username);
       this.store.set('token', data.token);
    console.log('New login token: ' + data.token);
    return <string>data.token;
  }    
  isLoggedIn() : Observable<Boolean> {
    if (!this.existsToken()) {
      return Observable.of(false);
    }
    var token = this.store.get("token");
    let option = new RequestOptions({ headers: new Headers({ 'X-SECURIS-TOKEN': token }) });
    return this.http.get('check', option)
                    .map((resp) => this.mapCheck(resp))
                    .catch((err) => super.processErrorResponse(err));
  }
  private mapCheck(res : Response) : boolean {
    let data = res.json();
    if (data.valid) {
      this.store.set('user', data.user);
    }
    return data.valid;
  }  
  existsToken() : Boolean {
    return this.store.get("token") !== null;
  }
  logout() : void {
    this.store.remove('user');
    this.store.remove('token');    
    this.router.navigate(['public/login']);
  }
}