Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable, Inject} from '@angular/core';
- import {Http, Headers, RequestOptions} from '@angular/http';
- import { Storage } from '@ionic/storage';
- import {Observable} from 'rxjs/Observable';
- import {BehaviorSubject} from 'rxjs/BehaviorSubject';
- import 'rxjs/add/observable/throw';
- import 'rxjs/add/observable/fromPromise';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/mergeMap';
- import 'rxjs/add/operator/toPromise';
- import 'rxjs/add/operator/catch';
- import {API_ENDPOINTS, IApiEndpoints} from "../config/API_ENDPOINTS.config";
- import {APPLICATION_SETTINGS, IApplicationSettings} from "../config/APPLICATION_SETTINGS.config";
- import {User} from './user.model';
- import {Roles} from './role.model';
- @Injectable()
- export class AuthenticationService {
- private STORAGE_IDENTIFIER: string;
- public TOKEN: any;
- private _currentUser: BehaviorSubject<any>;
- public currentUser: Observable<any>;
- private _currentRole: BehaviorSubject<number>;
- public currentRole: Observable<number>;
- constructor(
- @Inject(API_ENDPOINTS) private endpoints: IApiEndpoints,
- @Inject(APPLICATION_SETTINGS) private appSettings: IApplicationSettings,
- private http: Http,
- private storage: Storage
- ) {
- this.STORAGE_IDENTIFIER = appSettings.storageIdentifier + 'AUTH';
- this._currentUser = new BehaviorSubject(null);
- this.currentUser = this._currentUser.asObservable();
- this._currentRole = new BehaviorSubject(null);
- this.currentRole = this._currentRole.asObservable();
- this.storage.get(this.STORAGE_IDENTIFIER).then(auth => {
- if(auth) {
- this.TOKEN = auth.access_token || undefined;
- this.me().subscribe();
- }
- });
- }
- /**
- * Login, currently only for "front-end" users.
- *
- * @param email {string}
- * @param password {string}
- * @returns {Observable<R>}
- */
- login(email: string, password: string): Observable<any> {
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.login
- ].join('/');
- let payload = {
- email: email,
- password: password,
- mobile: true
- };
- return this.http.post(url, payload)
- .map(response => {
- let body = response.json();
- return Observable.fromPromise(this._setUser(body.data));
- })
- .catch(this._handleError.bind(this));
- }
- /**
- * Logout
- */
- logout(): void {
- this._clearUser();
- }
- resetPassword(email: string) {
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.resetPassword
- ].join('/');
- let payload = {email: email};
- return this.http.post(url, payload)
- .map(response => {
- let body = response.json();
- return body.data;
- })
- .catch(this._handleError.bind(this));
- }
- /**
- * Get logged in "front-end" user information
- * @returns {Observable<R>}
- */
- me(): Observable<any> {
- if(!this.TOKEN) {return}
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.me
- ].join('/');
- let headers = new Headers({'Authorization': 'Bearer '+ this.TOKEN,'N-Meta' : 'web;development'});
- let options = new RequestOptions({headers: headers});
- return this.http.get(url, options)
- .map(response => {
- let body = response.json();
- return Observable.fromPromise(this._setUser(body.data));
- })
- .catch(this._handleError.bind(this));
- }
- updateMe(user: User) {
- if(!this.TOKEN) {return}
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.editUser
- ].join('/');
- let headers = new Headers({'X-Authorization': this.TOKEN});
- let options = new RequestOptions({headers: headers});
- return this.http.post(url, user, options)
- .map(response => {
- let body = response.json();
- return Observable.fromPromise(this._setUser(body.data));
- })
- .catch(this._handleError.bind(this));
- }
- /**
- * Sets the current users role - must be a Role from the Roles Enum
- * @param role {Role}
- * @returns {any}
- */
- setRole(role): void {
- this.currentRole = role;
- return this._currentRole.next(role);
- }
- /**
- * Check if the user is authenticated based on their auth token being present in Storage
- * @returns {Promise<boolean>|PromiseLike<boolean>}
- */
- isAuthenticated(): Promise<any> {
- return this.storage.get(this.STORAGE_IDENTIFIER)
- .then((auth) => {
- return !!auth;
- });
- }
- /**
- * Helper method for updating user and authentication state
- * @param data
- * @returns {Observable<T>}
- * @private
- */
- private _setUser(data) {
- let user = Object.assign(new User(), data);
- let role = user.is_buyer ? Roles.BUYER : Roles.SELLER;
- let authStore = {
- access_token: user.access_token,
- access_token_expire: user.access_token_expire
- };
- this.TOKEN = authStore.access_token;
- this._currentRole.next(role);
- this._currentUser.next(user);
- return this.storage.set(this.STORAGE_IDENTIFIER, authStore);
- }
- /**
- * Helper method for clearing user and authentication state
- * @private
- */
- private _clearUser() {
- this.TOKEN = undefined;
- this.storage.remove(this.STORAGE_IDENTIFIER);
- this._currentUser.next(null);
- }
- /**
- * Helper method for handling error responses
- * @param error
- * @returns {ErrorObservable}
- * @private
- */
- private _handleError(error) {
- let body = error.json();
- let response = body.data.errors || {};
- console.error(response);
- return Observable.throw(response);
- }
- }
Add Comment
Please, Sign In to add comment