如果未使用AngularFire 2

时间:2016-06-20 11:51:04

标签: javascript angular firebase angularfire

如果用户未使用Angular2 / AngularFire2进行身份验证,那么将用户重定向到登录页面的最佳方法是什么?

例如;我想保护 /信息中心页面免受未经过身份验证的用户的攻击。用户应立即重定向到 / login 页面

我正在使用

  • angular2 版本2.0.0-rc.1
  • angular2 / router 版本2.0.0-rc.1
  • firebase 版本3.0.5
  • angularfire2 版本2.0.0-beta.1

3 个答案:

答案 0 :(得分:3)

您可以使用Angular 2的UI路由器保护条件保护网址。 https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

使用firebase的示例

警卫组件

请注意,在此处使用身份验证服务替换引用AF可能会更好。

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AngularFire } from 'angularfire2';

@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
    user;
    constructor(private af: AngularFire, private router: Router) {
        this.af.auth.subscribe(user => {
            if (user) {
                this.user = user;
            } else {
                this.user = undefined;
            }
        });
    }

    canActivate() {
        if (this.user) {
            return true;
        }
        this.router.navigate(['/login']);
        return false;
   }
}

申请路线

import { CanActivateViaAuthGuard} from './CanActivateViaAuthGuard';

const routes: Routes = [
    {path: '/Login', component: LoginComponent},
    {path: '/dashboard', component: DashboardComponent, canActivate: [CanActivateViaAuthGuard]}
];

export const routing = RouterModule.forRoot(routes);

最后登录代码

onSubmit() {
    this.af.auth.login({
      email: this.email,
      password: this.password,
    }).then(() => {
      this.submitted = true;
      this.router.navigate(['/dashboard', this.dashboard]);
    });
  }

答案 1 :(得分:0)

您可以在此处使用Auth方法。

if ($scope.auth === null) {
  $state.go('login');
}

注入$ firebaseAuth并将其分配给$ scope.auth然后让if检查其真或假

答案 2 :(得分:0)

找到了解决方案。

感谢来自r-park的todo-angular-2

import { ReflectiveInjector } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { AuthService } from './auth-service';


let appInjector: ReflectiveInjector;

/**
 * This is a workaround until `CanActivate` supports DI
 * @see https://github.com/angular/angular/issues/4112
 */

export class AuthRouteHelper {
  static dependencies(): {auth: AuthService, router: Router} {
    const injector: ReflectiveInjector = AuthRouteHelper.injector();
    const auth: AuthService = injector.get(AuthService);
    const router: Router = injector.get(Router);
    return {auth, router};
  }

  static injector(injector?: ReflectiveInjector): ReflectiveInjector {
    if (injector) appInjector = injector;
    return appInjector;
  }

  static requireAuth(): boolean {
    const { auth, router } = AuthRouteHelper.dependencies();
    if (!auth.authenticated) router.navigate(['/SignIn']);
    return auth.authenticated;
  }

  static requireUnauth(): boolean {
    const { auth, router } = AuthRouteHelper.dependencies();
    if (auth.authenticated) router.navigate(['/Tasks']);
    return !auth.authenticated;
  }
}