我正在尝试使用Firebase身份验证实现angular6 webapp。我已经能够使用基本的Firebase身份验证,但这是我遇到的问题。用户通过Firebase进行身份验证后,我需要向后端发出请求,以从数据库中获取有关用户的更多信息:
@Injectable()
export class UserService {
private endpoint = '/api/user';
public user: InternalUser;
constructor(private afAuth: AngularFireAuth,
private httpClient: HttpClient) {
console.log('[UserService] Instantiating user service.');
this.afAuth.auth.onAuthStateChanged((user) => {
console.log('[UserService] Auth State Changed.');
if (user) {
this.updateUserInfo()
.subscribe((curUser: any) => {
console.log('[UserService] curUser: ', curUser);
this.user = {firstName: curUser.first, lastName: curUser.last, roles: curUser.roles};
});
}
});
}
updateUserInfo(): Observable<InternalUser> {
console.log('[UserService] Updating user info @ ', this.endpoint);
return this.httpClient
.get(this.endpoint)
.pipe(
map((body: any) => body),
catchError(() => of('Error, could not load user.'))
);
}
}
还有我的身份验证保护:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private afAuth: AngularFireAuth, private router: Router, private userService: UserService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.afAuth.auth.currentUser) {
console.log('fb user found');
return true;
}
return this.afAuth.authState
.take(1)
.map(user => !!user)
.do(loggedIn => {
if (!loggedIn) {
console.log('access denied');
this.router.navigate(['/pages/auth/login']);
}
});
}
}
我是Angular的新手,但是可以使用,但是问题是Firebase身份验证已完成,并允许用户在我的用户服务能够完成其请求以获取有关用户的更多信息(例如角色)之前进入站点。显然,现在在auth Guard中,它仅检查firebase身份验证,因此这是可以预期的,我只是不确定如何正确地更改它。我试图查看angularfire2库并复制设置的可观察对象,以使我的用户服务模仿其auth服务,但我不太了解它是如何工作的。寻找有关用户服务/身份验证防护的提示,或者是否应该退后一步,以不同的方式进行操作。
edit:这是我的登录方法,我只是在调用Firebase身份验证:
login() {
this.isLoading = true;
this.afAuth.auth.signInWithEmailAndPassword(this.loginForm.value.email, this.loginForm.value.password)
.then(credentials => {
console.log('[Login] Login success!');
this.router.navigate(['/'], { replaceUrl: true });
this.isLoading = false;
if (this.loginForm.value.remember) {
console.log('[Login] Saving credentials because remember = ', this.loginForm.value.remember);
this.afAuth.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
console.log('[Login] Successfully changed persistence to LOCAL');
})
.catch(error => {
console.log('Unable to update persistence: ', error.message);
});
}
})
.catch(error => {
this.loginForm.controls['password'].setErrors({'invalid': true});
this.loginForm.controls['email'].setErrors({'invalid': true});
this.onLoginFormValuesChanged();
this.isLoading = false;
});
}
我想在auth Guard中完成此操作的原因是,如果用户重新打开其他页面,它将有机会首先重新加载详细信息。