【发布时间】:2019-11-03 21:20:17
【问题描述】:
src
|_auth/
|_authentication/
|_auth-service.ts
|_auth-guard.ts
|_is-logged-guard.ts
|_dashboard/
auth-guard-service.ts
export class AuthService {
public user: Observable<firebase.User>;
public userDetails: firebase.User = null;
public userProfileRef: firebase.database.Reference;
userData: any[] = [];
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.userProfileRef = firebase.database().ref('/userProfile');
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
} else {
this.userDetails = null;
}
}
);
}
isLoggedIn() {
if (this.userDetails == null) {
return false;
} else {
return true;
}
}
doSignOut() {
this._firebaseAuth.auth.signOut()
.then((res) => this.router.navigate(['/auth/login']));
}
}
auth-guard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) { }
canActivate() {
return this.auth.user.take(1).map(authState => !!authState).do(authenticated => { new Promise<boolean>( (resolve, reject) => {
if (!authenticated) {
this.router.navigate(['auth/sigin']);
return resolve(false);
} else {
return resolve(true);
}
}
}
is-logged-guard.ts - 我知道这是问题所在。我将如何解决它?
@Injectable()
export class IsLoggedGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) { }
canActivate() {
return !this.auth.isLoggedIn();
}
}
app-routing.module.ts
const routes: Routes = [
{ path: 'dashboard',
canActivate: [AuthGuard],
loadChildren: './dashboard/dashboard.module#DashboardModule'
},
{
path: 'auth',
component: NbAuthComponent,
canActivate: [IsLoggedGuard],
children: [
{
path: '',
component: SignInComponent,
},
{
path: 'SignIn',
component: SignInComponent,
},
{
path: 'SignUp',
component: SignUpComponent,
},
],
},
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: 'dashboard' },
];
const config: ExtraOptions = {
useHash: true,
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
案例 1:用户未登录
没问题。身份验证保护保护仪表板免受未经身份验证的用户的攻击,并将他们重定向到身份验证页面(即登录页面)。
案例2:用户已经登录#
没问题。如果经过身份验证的用户通过 localhost:4200 或 localhost:4200/#/dashboard 或 localhost:4200/#/ 或 localhost:4200/#/RANDOM_INVALID_URL 访问仪表板,则一切正常。守卫还将阻止已经在仪表板内的经过身份验证的用户访问身份验证页面。
案例 3:用户已经登录
问题。如果经过身份验证的用户通过 localhost:4200/#/auth 或 localhost:4200/#/auth/signin 访问仪表板,则守卫将无法保护并将用户重定向到仪表板主页。 (即 John 已经登录并打开一个新的 Chrome 选项卡,并输入 localhost:4200/#/auth 守卫不会阻止他访问它)。如果 John 已经通过身份验证,我该如何修复我的守卫以阻止他访问身份验证页面?
【问题讨论】:
标签: angular typescript firebase