import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, } from '@angular/router'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { map, take } from 'rxjs/operators'; import { CookieService } from 'ngx-cookie-service'; import { AuthSelector } from '../../modules/accounts/store'; import * as AppLoginStore from '../store/login'; @Injectable() export class AuthGuard implements CanActivate { constructor( private store: Store, private router: Router, private cookieService: CookieService, ) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { return this.store.pipe( take(1), select(AuthSelector.selectLogined), map((logined) => { if (!logined) { if (this.cookieService.check('jwt')) { this.store.dispatch(new AppLoginStore.LoginToken({ token: this.cookieService.get('jwt'), returnURL: state.url })); } else { this.store.dispatch(new AppLoginStore.LoginRedirect({ returnURL: state.url })); } return false; } return true; }), ); } }