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{AuthHttpService} from '../authHttp/authHttp.service'
- import {User} from './user.model';
- import {UserUpdatePassword} from './user.model';
- @Injectable()
- export class AuthenticationService {
- private STORAGE_IDENTIFIER: string;
- public TOKEN: any;
- private _currentUser: BehaviorSubject<any>;
- public currentUser: Observable<any>;
- constructor(
- @Inject(API_ENDPOINTS) private endpoints: IApiEndpoints,
- @Inject(APPLICATION_SETTINGS) private appSettings: IApplicationSettings,
- private http: Http,
- private storage: Storage,
- public authHttpService: AuthHttpService
- ) {
- this.STORAGE_IDENTIFIER = appSettings.storageIdentifier + 'AUTH';
- this._currentUser = new BehaviorSubject(null);
- this.currentUser = this._currentUser.asObservable();
- const token = localStorage.getItem(this.STORAGE_IDENTIFIER + '_TOKEN');
- if(token) {
- this.TOKEN = token;
- }
- // this.storage.get(this.STORAGE_IDENTIFIER).then(auth => {
- // if(auth) {
- // this.TOKEN = auth.token;
- // console.log(auth, 'wru token');
- // }
- // });
- }
- /**
- * Login, currently only for "front-end" users.
- *
- * @param username {string}
- * @param password {string}
- * @returns {Observable<R>}
- */
- login(username: string, password: string): Observable<any> {
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.login
- ].join('/');
- let payload = {
- username: username,
- password: password,
- };
- let additionalHeaders = new Headers;
- additionalHeaders.append('Image-Dimension', '200x200');
- let requestOptions = new RequestOptions();
- requestOptions.headers = additionalHeaders;
- return this.authHttpService.post(url, payload )
- .map(response => {
- let body = response.json();
- console.log(body);
- this._setUser(body);
- return body;
- // return Observable.fromPromise(this._setUser(body));
- })
- .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.authHttpService.post(url, payload)
- .map(response => {
- let body = response.json();
- return body;
- })
- .catch(this._handleError.bind(this));
- }
- /**
- * Get logged in "front-end" user information
- * @returns {Observable<R>}
- */
- me(): Observable<any> {
- if(!this.TOKEN) {
- return Observable.throw(new Error('MISSING_TOKEN'));
- }
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.me
- ].join('/');
- let additionalHeaders = new Headers;
- additionalHeaders.append('Image-Dimension', '200x200');
- let requestOptions = new RequestOptions();
- requestOptions.headers = additionalHeaders;
- return this.authHttpService.get(url, this.TOKEN, additionalHeaders)
- .map(response => {
- let body = response.json();
- this._setUser(body);
- return body;
- })
- .catch(this._handleError.bind(this));
- }
- updateMe(user: User) {
- if(!this.TOKEN) {return}
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.editUser
- ].join('/');
- return this.authHttpService.patch(url, user, this.TOKEN)
- .map(response => {
- let body = response.json();
- this._setUser(body);
- return body;
- })
- .catch(this._handleError.bind(this));
- }
- updatePassword(user: UserUpdatePassword){
- if(!this.TOKEN) {return}
- let url = [
- this.endpoints.root.production,
- this.endpoints.frontendUser.editPassword
- ].join('/');
- return this.authHttpService.patch(url, user, this.TOKEN)
- .map(response => {
- console.log('response', response);
- let body = response.json();
- this._setUser(body);
- console.log("RETURN BODY", body);
- return body;
- })
- .catch(this._handleError.bind(this));
- }
- /**
- * Check if the user is authenticated based on their auth token being present in Storage
- * @returns {Promise<boolean>|PromiseLike<boolean>}
- */
- isAuthenticated() {
- const token = localStorage.getItem(this.STORAGE_IDENTIFIER + '_TOKEN');
- return !!token;
- }
- /**
- * Helper method for updating user and authentication state
- * @param data
- * @returns {Observable<T>}
- * @private
- */
- private _setUser(data) {
- let user = Object.assign(new User(), data);
- this.TOKEN = user.token;
- this._currentUser.next(user);
- localStorage.setItem(this.STORAGE_IDENTIFIER + '_TOKEN', this.TOKEN);
- }
- /**
- * Helper method for clearing user and authentication state
- * @private
- */
- private _clearUser() {
- this.TOKEN = undefined;
- localStorage.removeItem(this.STORAGE_IDENTIFIER + '_TOKEN');
- 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.errors || {};
- console.error(response);
- return Observable.throw(response);
- }
- }
Add Comment
Please, Sign In to add comment