blob: e7a593c4dfcbdffdb02b4c46c64093530277163c [file] [log] [blame]
Matteo Scandolo035c5932016-12-14 09:55:15 -08001import {AppConfig} from '../../config/app.config';
Matteo Scandolof6acdbe2016-12-13 10:29:37 -08002import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg;
3export interface IAuthRequestData {
4 username: string;
5 password: string;
6}
7
8export interface IAuthResponseData extends IHttpPromiseCallbackArg<any> {
9 data: {
10 user: string;
11 xoscsrftoken: string;
12 xossessionid: string;
13 };
14}
Matteo Scandoloa4a47112016-12-16 10:06:13 -080015
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -080016export interface IXosUser {
17 id: number;
18 email: string;
19}
20
Matteo Scandoloa4a47112016-12-16 10:06:13 -080021export interface IXosAuthService {
22 login(data: IAuthRequestData): Promise<any>;
23 logout(): Promise<any>;
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -080024 getUser(): IXosUser;
Matteo Scandoloa4a47112016-12-16 10:06:13 -080025}
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080026export class AuthService {
27
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080028 constructor(
29 private $http: angular.IHttpService,
30 private $q: angular.IQService,
31 private $cookies: angular.cookies.ICookiesService
32 ) {
33 }
34
35 public login(data: IAuthRequestData): Promise<any> {
36 const d = this.$q.defer();
37 this.$http.post(`${AppConfig.apiEndpoint}/utility/login/`, data)
38 .then((res: IAuthResponseData) => {
39 this.$cookies.put('xoscsrftoken', res.data.xoscsrftoken);
40 this.$cookies.put('xossessionid', res.data.xossessionid);
41 this.$cookies.put('xosuser', res.data.user);
42 res.data.user = JSON.parse(res.data.user);
43 d.resolve(res.data);
44 })
45 .catch(e => {
46 d.reject(e);
47 });
48 return d.promise;
49 }
Matteo Scandoloa4a47112016-12-16 10:06:13 -080050
51 public logout(): Promise<any> {
52 const d = this.$q.defer();
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -080053 this.$http.post(`${AppConfig.apiEndpoint}/utility/logout/`, {
Matteo Scandoloa4a47112016-12-16 10:06:13 -080054 xoscsrftoken: this.$cookies.get('xoscsrftoken'),
55 xossessionid: this.$cookies.get('xossessionid')
56 })
57 .then(() => {
58 this.$cookies.remove('xoscsrftoken');
59 this.$cookies.remove('xossessionid');
60 this.$cookies.remove('xosuser');
61 d.resolve();
62 })
63 .catch(e => {
64 d.reject(e);
65 });
66 return d.promise;
67 }
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -080068
69 public getUser(): IXosUser {
70 return JSON.parse(this.$cookies.get('xosuser'));
71 }
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080072}