Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.18 KB | None | 0 0
  1. import {Injectable, Inject} from '@angular/core';
  2. import {Http, Headers, RequestOptions} from '@angular/http';
  3.  
  4. import { Storage } from '@ionic/storage';
  5.  
  6. import {Observable} from 'rxjs/Observable';
  7. import {BehaviorSubject} from 'rxjs/BehaviorSubject';
  8. import 'rxjs/add/observable/throw';
  9. import 'rxjs/add/observable/fromPromise';
  10. import 'rxjs/add/operator/map';
  11. import 'rxjs/add/operator/mergeMap';
  12. import 'rxjs/add/operator/toPromise';
  13. import 'rxjs/add/operator/catch';
  14.  
  15. import {API_ENDPOINTS, IApiEndpoints} from "../config/API_ENDPOINTS.config";
  16. import {APPLICATION_SETTINGS, IApplicationSettings} from "../config/APPLICATION_SETTINGS.config";
  17.  
  18. import {User} from './user.model';
  19. import {Roles} from './role.model';
  20.  
  21. @Injectable()
  22. export class AuthenticationService {
  23.  
  24. private STORAGE_IDENTIFIER: string;
  25.  
  26. public TOKEN: any;
  27.  
  28. private _currentUser: BehaviorSubject<any>;
  29. public currentUser: Observable<any>;
  30.  
  31. private _currentRole: BehaviorSubject<number>;
  32. public currentRole: Observable<number>;
  33.  
  34. constructor(
  35. @Inject(API_ENDPOINTS) private endpoints: IApiEndpoints,
  36. @Inject(APPLICATION_SETTINGS) private appSettings: IApplicationSettings,
  37. private http: Http,
  38. private storage: Storage
  39. ) {
  40.  
  41. this.STORAGE_IDENTIFIER = appSettings.storageIdentifier + 'AUTH';
  42.  
  43. this._currentUser = new BehaviorSubject(null);
  44. this.currentUser = this._currentUser.asObservable();
  45.  
  46. this._currentRole = new BehaviorSubject(null);
  47. this.currentRole = this._currentRole.asObservable();
  48.  
  49. this.storage.get(this.STORAGE_IDENTIFIER).then(auth => {
  50. if(auth) {
  51. this.TOKEN = auth.access_token || undefined;
  52. this.me().subscribe();
  53. }
  54. });
  55.  
  56. }
  57.  
  58. /**
  59. * Login, currently only for "front-end" users.
  60. *
  61. * @param email {string}
  62. * @param password {string}
  63. * @returns {Observable<R>}
  64. */
  65. login(email: string, password: string): Observable<any> {
  66.  
  67. let url = [
  68. this.endpoints.root.production,
  69. this.endpoints.frontendUser.login
  70. ].join('/');
  71.  
  72. let payload = {
  73. email: email,
  74. password: password,
  75. mobile: true
  76. };
  77.  
  78. return this.http.post(url, payload)
  79. .map(response => {
  80. let body = response.json();
  81. return Observable.fromPromise(this._setUser(body.data));
  82. })
  83. .catch(this._handleError.bind(this));
  84.  
  85. }
  86.  
  87. /**
  88. * Logout
  89. */
  90. logout(): void {
  91. this._clearUser();
  92. }
  93.  
  94. resetPassword(email: string) {
  95.  
  96. let url = [
  97. this.endpoints.root.production,
  98. this.endpoints.frontendUser.resetPassword
  99. ].join('/');
  100.  
  101. let payload = {email: email};
  102.  
  103. return this.http.post(url, payload)
  104. .map(response => {
  105.  
  106. let body = response.json();
  107.  
  108. return body.data;
  109.  
  110. })
  111. .catch(this._handleError.bind(this));
  112.  
  113. }
  114.  
  115. /**
  116. * Get logged in "front-end" user information
  117. * @returns {Observable<R>}
  118. */
  119. me(): Observable<any> {
  120.  
  121. if(!this.TOKEN) {return}
  122.  
  123. let url = [
  124. this.endpoints.root.production,
  125. this.endpoints.frontendUser.me
  126. ].join('/');
  127.  
  128. return this.http.get(url)
  129. .map(response => {
  130.  
  131. let body = response.json();
  132.  
  133. return Observable.fromPromise(this._setUser(body.data));
  134. })
  135. .catch(this._handleError.bind(this));
  136.  
  137. }
  138.  
  139. updateMe(user: User) {
  140.  
  141. if(!this.TOKEN) {return}
  142.  
  143. let url = [
  144. this.endpoints.root.production,
  145. this.endpoints.frontendUser.editUser
  146. ].join('/');
  147.  
  148. let headers = new Headers({'X-Authorization': this.TOKEN});
  149. let options = new RequestOptions({headers: headers});
  150.  
  151. return this.http.post(url, user, options)
  152. .map(response => {
  153.  
  154. let body = response.json();
  155.  
  156. return Observable.fromPromise(this._setUser(body.data));
  157. })
  158. .catch(this._handleError.bind(this));
  159.  
  160. }
  161.  
  162. /**
  163. * Sets the current users role - must be a Role from the Roles Enum
  164. * @param role {Role}
  165. * @returns {any}
  166. */
  167. setRole(role): void {
  168. this.currentRole = role;
  169. return this._currentRole.next(role);
  170. }
  171.  
  172. /**
  173. * Check if the user is authenticated based on their auth token being present in Storage
  174. * @returns {Promise<boolean>|PromiseLike<boolean>}
  175. */
  176. isAuthenticated(): Promise<any> {
  177. return this.storage.get(this.STORAGE_IDENTIFIER)
  178. .then((auth) => {
  179. return !!auth;
  180. });
  181. }
  182.  
  183. /**
  184. * Helper method for updating user and authentication state
  185. * @param data
  186. * @returns {Observable<T>}
  187. * @private
  188. */
  189. private _setUser(data) {
  190. let user = Object.assign(new User(), data);
  191.  
  192. let role = user.is_buyer ? Roles.BUYER : Roles.SELLER;
  193.  
  194. let authStore = {
  195. access_token: user.access_token,
  196. access_token_expire: user.access_token_expire
  197. };
  198.  
  199. this.TOKEN = authStore.access_token;
  200.  
  201.  
  202. this._currentRole.next(role);
  203. this._currentUser.next(user);
  204.  
  205. return this.storage.set(this.STORAGE_IDENTIFIER, authStore);
  206.  
  207. }
  208.  
  209. /**
  210. * Helper method for clearing user and authentication state
  211. * @private
  212. */
  213. private _clearUser() {
  214.  
  215. this.TOKEN = undefined;
  216. this.storage.remove(this.STORAGE_IDENTIFIER);
  217. this._currentUser.next(null);
  218.  
  219. }
  220.  
  221. /**
  222. * Helper method for handling error responses
  223. * @param error
  224. * @returns {ErrorObservable}
  225. * @private
  226. */
  227. private _handleError(error) {
  228.  
  229. let body = error.json();
  230.  
  231. let response = body.data.errors || {};
  232.  
  233. console.error(response);
  234.  
  235. return Observable.throw(response);
  236.  
  237. }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement