blob: 7c73c2819a66df19fa76568e5d6ca790ecdcddb0 [file] [log] [blame]
Matteo Scandolo43ffb672016-12-02 14:49:58 -08001/// <reference path="../../../../typings/index.d.ts"/>
2
3// Imports
4import {AppConfig} from '../../config/app.config';
5import {Injectable} from '@angular/core';
6import {Http, Response} from '@angular/http';
7import {Observable} from 'rxjs/Rx';
8import {IAuthRequest, IAuthResponse} from '../../interfaces/auth.interface';
9import {CookieService} from 'angular2-cookie/core';
10
11// Import RxJs required methods
12import 'rxjs/add/operator/map';
13import 'rxjs/add/operator/catch';
14
15@Injectable()
16export class AuthService {
17 private xosToken:string;
18 private xosSessionId:string;
19 // Resolve HTTP using the constructor
20 constructor (private http: Http, private cookieService:CookieService) {
21 }
22
23 // check if the user is authenticated
24 isAuthenticated(){
25 this.xosToken = this.cookieService.get('xoscsrftoken');
26 this.xosSessionId = this.cookieService.get('xossessionid');
27 return this.xosToken;
28 }
29
30 // save cookies
31 storeAuth(auth:IAuthResponse){
32 this.cookieService.put('xoscsrftoken', auth.xoscsrftoken);
33 this.cookieService.put('xossessionid', auth.xossessionid);
34 }
35
36 // Log the user in
37 login(auth: IAuthRequest) : Observable<IAuthResponse> {
38 return this.http.post(`${AppConfig.apiEndpoint}/utility/login/`, auth)
39 .map((res:Response) => res.json())
40 .map((auth:IAuthResponse) => {
41 this.storeAuth(auth);
42 auth.user = JSON.parse(auth.user);
43 return auth;
44 })
45 .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
46 }
47}
48