为Angular 2身份验证前端添加会话超时

时间:2017-02-03 08:52:10

标签: angular

我已按照以下教程[1]为我的应用程序设置身份验证。现在我需要通过添加Angular 2前端的会话超时来修改身份验证。这是在会话过期后的20分钟内再次要求用户登录。

我如何为我的身份验证系统开发此扩展功能。

[1] http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial

1 个答案:

答案 0 :(得分:2)

import { Injectable }           from '@angular/core';
import { Observable }           from 'rxjs/Observable';
import { BehaviorSubject }      from 'rxjs/BehaviorSubject';
import                               'rxjs/add/operator/map';
import                               'rxjs/add/operator/filter';
import                               'rxjs/add/Observable/timer';
import                               'rxjs/add/operator/do';
import                               'rxjs/add/operator/switch';
@Injectable()
export class AuthService {
  private authState:    AuthState;
  private authManager:  BehaviorSubject<AuthState>;
  public  authChange$:  Observable<AuthState>;
  constructor() {
    this.authManager = new BehaviorSubject(AuthState.LOGGED_OUT);
    this.authChange$ = this.authManager.asObservable();
    this.authChange$
      .filter((authState:AuthState) => authState === AuthState.LOGGED_IN)
      .map(   (authState:AuthState) => Observable.timer(SESSION_TIMEOUT))
      .do(    () => 
        console.log('Logged In. Session Timout counting down from now'))
      .switch()
      .subscribe( () => {console.log('Timer ended: Logging out')
                         this.logout();
                        });
  }

  login() {
    this.setAuthState(AuthState.LOGGED_IN);
  }
  logout() {
    this.setAuthState(AuthState.LOGGED_OUT);
  }
  emitAuthState():void {
    this.authManager.next(this.authState);
  }

  private setAuthState(newAuthState:AuthState):void {
    console.log('AuthService: setAuthState: ', 
        AuthState[newAuthState.toString()]);
    if (newAuthState != this.authState) {
      this.authState = newAuthState;
      this.emitAuthState();
    }
  }

export enum AuthState {
  LOGGED_IN,
  LOGGED_OUT
}

const SESSION_TIMEOUT = 5000;