Matteo Scandolo | 035c593 | 2016-12-14 09:55:15 -0800 | [diff] [blame] | 1 | import {AppConfig} from '../../config/app.config'; |
Matteo Scandolo | f6acdbe | 2016-12-13 10:29:37 -0800 | [diff] [blame] | 2 | import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg; |
| 3 | export interface IAuthRequestData { |
| 4 | username: string; |
| 5 | password: string; |
| 6 | } |
| 7 | |
| 8 | export interface IAuthResponseData extends IHttpPromiseCallbackArg<any> { |
| 9 | data: { |
| 10 | user: string; |
| 11 | xoscsrftoken: string; |
| 12 | xossessionid: string; |
| 13 | }; |
| 14 | } |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame] | 15 | |
| 16 | export interface IXosAuthService { |
| 17 | login(data: IAuthRequestData): Promise<any>; |
| 18 | logout(): Promise<any>; |
| 19 | } |
Matteo Scandolo | f6acdbe | 2016-12-13 10:29:37 -0800 | [diff] [blame] | 20 | export class AuthService { |
| 21 | |
| 22 | |
| 23 | /** @ngInject */ |
| 24 | constructor( |
| 25 | private $http: angular.IHttpService, |
| 26 | private $q: angular.IQService, |
| 27 | private $cookies: angular.cookies.ICookiesService |
| 28 | ) { |
| 29 | } |
| 30 | |
| 31 | public login(data: IAuthRequestData): Promise<any> { |
| 32 | const d = this.$q.defer(); |
| 33 | this.$http.post(`${AppConfig.apiEndpoint}/utility/login/`, data) |
| 34 | .then((res: IAuthResponseData) => { |
| 35 | this.$cookies.put('xoscsrftoken', res.data.xoscsrftoken); |
| 36 | this.$cookies.put('xossessionid', res.data.xossessionid); |
| 37 | this.$cookies.put('xosuser', res.data.user); |
| 38 | res.data.user = JSON.parse(res.data.user); |
| 39 | d.resolve(res.data); |
| 40 | }) |
| 41 | .catch(e => { |
| 42 | d.reject(e); |
| 43 | }); |
| 44 | return d.promise; |
| 45 | } |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame] | 46 | |
| 47 | public logout(): Promise<any> { |
| 48 | const d = this.$q.defer(); |
| 49 | this.$http.post(`${AppConfig.apiEndpoint}/utility/login/`, { |
| 50 | xoscsrftoken: this.$cookies.get('xoscsrftoken'), |
| 51 | xossessionid: this.$cookies.get('xossessionid') |
| 52 | }) |
| 53 | .then(() => { |
| 54 | this.$cookies.remove('xoscsrftoken'); |
| 55 | this.$cookies.remove('xossessionid'); |
| 56 | this.$cookies.remove('xosuser'); |
| 57 | d.resolve(); |
| 58 | }) |
| 59 | .catch(e => { |
| 60 | d.reject(e); |
| 61 | }); |
| 62 | return d.promise; |
| 63 | } |
Matteo Scandolo | f6acdbe | 2016-12-13 10:29:37 -0800 | [diff] [blame] | 64 | } |