Guest User

Untitled

a guest
Mar 3rd, 2017
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.80 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{AuthHttpService} from '../authHttp/authHttp.service'
  19.  
  20. import {User} from './user.model';
  21. import {UserUpdatePassword} from './user.model';
  22.  
  23. @Injectable()
  24. export class AuthenticationService {
  25.  
  26. private STORAGE_IDENTIFIER: string;
  27.  
  28. public TOKEN: any;
  29.  
  30. private _currentUser: BehaviorSubject<any>;
  31. public currentUser: Observable<any>;
  32.  
  33. constructor(
  34. @Inject(API_ENDPOINTS) private endpoints: IApiEndpoints,
  35. @Inject(APPLICATION_SETTINGS) private appSettings: IApplicationSettings,
  36. private http: Http,
  37. private storage: Storage,
  38. public authHttpService: AuthHttpService
  39. ) {
  40. this.STORAGE_IDENTIFIER = appSettings.storageIdentifier + 'AUTH';
  41.  
  42. this._currentUser = new BehaviorSubject(null);
  43. this.currentUser = this._currentUser.asObservable();
  44.  
  45. const token = localStorage.getItem(this.STORAGE_IDENTIFIER + '_TOKEN');
  46. if(token) {
  47. this.TOKEN = token;
  48. }
  49.  
  50. // this.storage.get(this.STORAGE_IDENTIFIER).then(auth => {
  51. // if(auth) {
  52. // this.TOKEN = auth.token;
  53. // console.log(auth, 'wru token');
  54. // }
  55. // });
  56.  
  57. }
  58.  
  59. /**
  60. * Login, currently only for "front-end" users.
  61. *
  62. * @param username {string}
  63. * @param password {string}
  64. * @returns {Observable<R>}
  65. */
  66. login(username: string, password: string): Observable<any> {
  67.  
  68. let url = [
  69. this.endpoints.root.production,
  70. this.endpoints.frontendUser.login
  71. ].join('/');
  72.  
  73. let payload = {
  74. username: username,
  75. password: password,
  76. };
  77.  
  78. let additionalHeaders = new Headers;
  79. additionalHeaders.append('Image-Dimension', '200x200');
  80. let requestOptions = new RequestOptions();
  81. requestOptions.headers = additionalHeaders;
  82.  
  83. return this.authHttpService.post(url, payload )
  84. .map(response => {
  85. let body = response.json();
  86.  
  87. console.log(body);
  88.  
  89. this._setUser(body);
  90.  
  91. return body;
  92. // return Observable.fromPromise(this._setUser(body));
  93. })
  94. .catch(this._handleError.bind(this));
  95.  
  96. }
  97.  
  98. /**
  99. * Logout
  100. */
  101. logout(): void {
  102. this._clearUser();
  103. }
  104.  
  105. resetPassword(email: string) {
  106.  
  107. let url = [
  108. this.endpoints.root.production,
  109. this.endpoints.frontendUser.resetPassword
  110. ].join('/');
  111.  
  112. let payload = {email: email};
  113.  
  114. return this.authHttpService.post(url, payload)
  115. .map(response => {
  116.  
  117. let body = response.json();
  118.  
  119. return body;
  120.  
  121. })
  122. .catch(this._handleError.bind(this));
  123.  
  124. }
  125.  
  126. /**
  127. * Get logged in "front-end" user information
  128. * @returns {Observable<R>}
  129. */
  130. me(): Observable<any> {
  131.  
  132. if(!this.TOKEN) {
  133. return Observable.throw(new Error('MISSING_TOKEN'));
  134. }
  135.  
  136. let url = [
  137. this.endpoints.root.production,
  138. this.endpoints.frontendUser.me
  139. ].join('/');
  140.  
  141.  
  142. let additionalHeaders = new Headers;
  143. additionalHeaders.append('Image-Dimension', '200x200');
  144. let requestOptions = new RequestOptions();
  145. requestOptions.headers = additionalHeaders;
  146.  
  147. return this.authHttpService.get(url, this.TOKEN, additionalHeaders)
  148. .map(response => {
  149.  
  150. let body = response.json();
  151.  
  152. this._setUser(body);
  153.  
  154. return body;
  155.  
  156. })
  157. .catch(this._handleError.bind(this));
  158.  
  159. }
  160.  
  161. updateMe(user: User) {
  162.  
  163. if(!this.TOKEN) {return}
  164.  
  165. let url = [
  166. this.endpoints.root.production,
  167. this.endpoints.frontendUser.editUser
  168. ].join('/');
  169.  
  170. return this.authHttpService.patch(url, user, this.TOKEN)
  171. .map(response => {
  172.  
  173. let body = response.json();
  174.  
  175. this._setUser(body);
  176.  
  177. return body;
  178.  
  179. })
  180. .catch(this._handleError.bind(this));
  181.  
  182. }
  183.  
  184.  
  185.  
  186.  
  187. updatePassword(user: UserUpdatePassword){
  188. if(!this.TOKEN) {return}
  189.  
  190. let url = [
  191. this.endpoints.root.production,
  192. this.endpoints.frontendUser.editPassword
  193. ].join('/');
  194.  
  195.  
  196. return this.authHttpService.patch(url, user, this.TOKEN)
  197. .map(response => {
  198.  
  199. console.log('response', response);
  200.  
  201. let body = response.json();
  202.  
  203. this._setUser(body);
  204.  
  205. console.log("RETURN BODY", body);
  206. return body;
  207.  
  208. })
  209. .catch(this._handleError.bind(this));
  210.  
  211.  
  212.  
  213. }
  214.  
  215.  
  216.  
  217. /**
  218. * Check if the user is authenticated based on their auth token being present in Storage
  219. * @returns {Promise<boolean>|PromiseLike<boolean>}
  220. */
  221. isAuthenticated() {
  222. const token = localStorage.getItem(this.STORAGE_IDENTIFIER + '_TOKEN');
  223. return !!token;
  224. }
  225.  
  226. /**
  227. * Helper method for updating user and authentication state
  228. * @param data
  229. * @returns {Observable<T>}
  230. * @private
  231. */
  232. private _setUser(data) {
  233. let user = Object.assign(new User(), data);
  234.  
  235. this.TOKEN = user.token;
  236.  
  237. this._currentUser.next(user);
  238.  
  239. localStorage.setItem(this.STORAGE_IDENTIFIER + '_TOKEN', this.TOKEN);
  240.  
  241. }
  242.  
  243. /**
  244. * Helper method for clearing user and authentication state
  245. * @private
  246. */
  247. private _clearUser() {
  248.  
  249. this.TOKEN = undefined;
  250. localStorage.removeItem(this.STORAGE_IDENTIFIER + '_TOKEN');
  251. this._currentUser.next(null);
  252.  
  253. }
  254.  
  255. /**
  256. * Helper method for handling error responses
  257. * @param error
  258. * @returns {ErrorObservable}
  259. * @private
  260. */
  261. private _handleError(error) {
  262.  
  263. let body = error.json();
  264.  
  265. let response = body.errors || {};
  266.  
  267. console.error(response);
  268.  
  269. return Observable.throw(response);
  270.  
  271. }
  272. }
Add Comment
Please, Sign In to add comment