Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import {Observable} from 'rxjs';
- import 'rxjs/add/operator/map';
- import {AuthState, LOGIN, LOGOUT, LOGIN_SUCCESS, LOGIN_FAILURE, AuthHeaders, currentUser} from '../reducers/auth';
- import {select, Store} from '@ngrx/store';
- import {ApiService} from '../services/api.service';
- import {LocalStorageService} from '../services/local-storage.service';
- @Injectable()
- export class AuthService {
- // Auth Headers
- private _authHeaders;
- get authHeaders(): AuthHeaders {
- return this._authHeaders;
- }
- set authHeaders(val: AuthHeaders) {
- this._authHeaders = val;
- // only save to local storage if headers exist
- if (val) {
- this.storage.setAuthHeaders(val);
- }
- }
- // Auth State Observable
- private _auth$: Observable<AuthState>;
- get auth$(): Observable<AuthState> { return this._auth$; }
- // Auth Store
- get store(): Store<AuthState> { return this._store; }
- constructor(private _store: Store<AuthState>, private api: ApiService, private storage: LocalStorageService) {
- this._auth$ = _store.pipe(select('auth'));
- this.auth$.subscribe((state: AuthState) => {
- this.authHeaders = state.authHeaders;
- });
- }
- login(data) {
- this.store.dispatch({ type: LOGIN });
- this.api.login(data)
- .subscribe(
- res => {
- this.login_success(res);
- },
- err => {
- this.login_failure(err.json().errors[0]);
- }
- );
- }
- validateToken(): Observable<any> {
- if (!this.authHeaders) {
- // set directly with _ so we don't save into local storage the same value again
- this._authHeaders = this.storage.getAuthHeaders();
- }
- return this.api.validateToken(this.authHeaders).map(
- res => {
- res.headers = this.authHeaders;
- this.login_success(res);
- return res;
- }
- );
- }
- logout() {
- this.api.logout(this.authHeaders)
- .subscribe(
- res => {
- this.logout_success();
- },
- err => {
- this.logout_success();
- }
- );
- }
- getLoggedInUser() {
- return this.store.pipe(select(currentUser));
- }
- private logout_success() {
- this.storage.deleteAuthHeaders();
- this.store.dispatch({ type: LOGOUT });
- }
- private login_success(res) {
- this.store.dispatch({
- type: LOGIN_SUCCESS,
- payload: {
- user: res.body.data,
- authHeaders: res.headers
- }
- });
- }
- private login_failure(error: string = 'Unknown error') {
- this.store.dispatch({ type: LOGIN_FAILURE, payload: {error: error} });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement