Guest User

my old athentication

a guest
Jan 17th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.30 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. let headers = new Headers({'Authorization': 'Bearer '+ this.TOKEN,'N-Meta' : 'web;development'});
  129. let options = new RequestOptions({headers: headers});
  130.  
  131. return this.http.get(url, options)
  132. .map(response => {
  133.  
  134. let body = response.json();
  135.  
  136. return Observable.fromPromise(this._setUser(body.data));
  137. })
  138. .catch(this._handleError.bind(this));
  139.  
  140. }
  141.  
  142. updateMe(user: User) {
  143.  
  144. if(!this.TOKEN) {return}
  145.  
  146. let url = [
  147. this.endpoints.root.production,
  148. this.endpoints.frontendUser.editUser
  149. ].join('/');
  150.  
  151. let headers = new Headers({'X-Authorization': this.TOKEN});
  152. let options = new RequestOptions({headers: headers});
  153.  
  154. return this.http.post(url, user, options)
  155. .map(response => {
  156.  
  157. let body = response.json();
  158.  
  159. return Observable.fromPromise(this._setUser(body.data));
  160. })
  161. .catch(this._handleError.bind(this));
  162.  
  163. }
  164.  
  165. /**
  166. * Sets the current users role - must be a Role from the Roles Enum
  167. * @param role {Role}
  168. * @returns {any}
  169. */
  170. setRole(role): void {
  171. this.currentRole = role;
  172. return this._currentRole.next(role);
  173. }
  174.  
  175. /**
  176. * Check if the user is authenticated based on their auth token being present in Storage
  177. * @returns {Promise<boolean>|PromiseLike<boolean>}
  178. */
  179. isAuthenticated(): Promise<any> {
  180. return this.storage.get(this.STORAGE_IDENTIFIER)
  181. .then((auth) => {
  182. return !!auth;
  183. });
  184. }
  185.  
  186. /**
  187. * Helper method for updating user and authentication state
  188. * @param data
  189. * @returns {Observable<T>}
  190. * @private
  191. */
  192. private _setUser(data) {
  193. let user = Object.assign(new User(), data);
  194.  
  195. let role = user.is_buyer ? Roles.BUYER : Roles.SELLER;
  196.  
  197. let authStore = {
  198. access_token: user.access_token,
  199. access_token_expire: user.access_token_expire
  200. };
  201.  
  202. this.TOKEN = authStore.access_token;
  203.  
  204.  
  205. this._currentRole.next(role);
  206. this._currentUser.next(user);
  207.  
  208. return this.storage.set(this.STORAGE_IDENTIFIER, authStore);
  209.  
  210. }
  211.  
  212. /**
  213. * Helper method for clearing user and authentication state
  214. * @private
  215. */
  216. private _clearUser() {
  217.  
  218. this.TOKEN = undefined;
  219. this.storage.remove(this.STORAGE_IDENTIFIER);
  220. this._currentUser.next(null);
  221.  
  222. }
  223.  
  224. /**
  225. * Helper method for handling error responses
  226. * @param error
  227. * @returns {ErrorObservable}
  228. * @private
  229. */
  230. private _handleError(error) {
  231.  
  232. let body = error.json();
  233.  
  234. let response = body.data.errors || {};
  235.  
  236. console.error(response);
  237.  
  238. return Observable.throw(response);
  239.  
  240. }
  241. }
Add Comment
Please, Sign In to add comment