66 lines
2.0 KiB
TypeScript
Raw Normal View History

2018-04-06 15:59:49 +09:00
import { Injectable } from '@angular/core';
import {
CanActivate,
CanActivateChild,
ActivatedRouteSnapshot,
2018-05-28 14:41:56 +09:00
RouterStateSnapshot,
Router,
2018-04-06 15:59:49 +09:00
} from '@angular/router';
2018-05-28 19:09:38 +09:00
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
2018-04-06 15:59:49 +09:00
import { CookieService } from 'ngx-cookie-service';
2018-05-28 19:09:38 +09:00
import { AuthContainerSelector } from '@overflow/shared/auth/store';
import * as MemberEntityStore from '@overflow/member/store/entity/member';
import * as SigninContaifnerStore from '../store/container/signin';
2018-04-06 15:59:49 +09:00
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(
2018-05-28 19:09:38 +09:00
private store: Store<any>,
2018-05-28 14:41:56 +09:00
private router: Router,
2018-04-06 15:59:49 +09:00
private cookieService: CookieService,
) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
2018-05-28 19:09:38 +09:00
return this.store.pipe(
select(AuthContainerSelector.selectSignined),
map(signined => {
2018-04-06 15:59:49 +09:00
if (!signined) {
if (this.cookieService.check('authToken')) {
2018-05-28 19:09:38 +09:00
this.store.dispatch(new MemberEntityStore.SigninCookie({authToken: this.cookieService.get('authToken'), returnURL: state.url}));
2018-04-06 15:59:49 +09:00
} else {
2018-05-28 19:09:38 +09:00
this.store.dispatch(new SigninContaifnerStore.SigninRedirect({returnURL: state.url}));
2018-04-06 15:59:49 +09:00
}
return false;
}
return true;
2018-05-28 19:09:38 +09:00
}),
take(1)
);
2018-04-06 15:59:49 +09:00
}
canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
2018-05-28 19:09:38 +09:00
return this.store.pipe(
select(AuthContainerSelector.selectSignined),
map(signined => {
2018-04-06 15:59:49 +09:00
if (!signined) {
2018-05-28 19:09:38 +09:00
if (this.cookieService.check('authToken')) {
this.store.dispatch(new MemberEntityStore.SigninCookie({authToken: this.cookieService.get('authToken'), returnURL: state.url}));
} else {
this.store.dispatch(new SigninContaifnerStore.SigninRedirect({returnURL: state.url}));
}
2018-04-06 15:59:49 +09:00
return false;
}
return true;
2018-05-28 19:09:38 +09:00
}),
take(1)
);
2018-04-06 15:59:49 +09:00
}
2018-05-28 19:09:38 +09:00
2018-04-06 15:59:49 +09:00
}