【发布时间】:2020-08-13 20:55:53
【问题描述】:
我正在尝试使用 Firebase 创建用户身份验证。
我的应用程序中有两个角色:学生和教师,我在注册时将其添加到名为 users 的 Firebase 集合中,其中有一个字段角色。
我的问题是我想将学生重定向到学生个人资料页面,并将教师重定向到教师个人资料页面。我有两种不同的表格,一种用于学生登录,另一种用于教师登录。
当我在学生登录时输入教师的数据时,我想收到错误,因为用户不存在。
现在我没有收到任何错误,如果我只有一种登录形式,一切都会正常工作,但我有两种,所以如果用户是教师并登录学生,我希望它给我错误。
这是我的 auth.service 中学生的登录名
loginEmailStudent(email: string, pass: string) {
return new Promise((resolve, reject) => {
this.auth.signInWithEmailAndPassword(email, pass)
.then( (user) => {
this.afs.collection("users").ref.where("email","==", user.user.email).onSnapshot(snap => {
snap.forEach(userRef => {
if(userRef.data().role == "student"){
this.router.navigate(['/student/profile']);
} else {
//error
}
})
})
}).catch(err => console.log(reject(err)));
});
}
除了角色之外,loginTeachers 也是如此。 这是在我的身份验证组件中提交学生登录表单的地方。
onSubmit(form: NgForm) {
if(!form.valid) {
return
}
const email = form.value.email;
const password = form.value.password;
this.isLoading = true;
if(this.isLoginMode) {
this.authService.loginEmailStudent(email, password)
.then( (res) => {
this.isLoading = false;
}).catch(errorRes => {
console.log(errorRes);
switch(errorRes.code) {
case 'auth/user-not-found' :
this.error = 'There is no existing user with this email address!';
break;
case 'auth/wrong-password' :
this.error = 'The password is invalid!';
break;
case 'auth/invalid-email' :
this.error = 'The email address is badly formatted!';
break;
default:
this.error = 'An error occured!';
}
this.isLoading = false;
});
} else {
this.authService.registerStudent(email, password)
.then((res) => {
this.isLoading = false;
this.authService.isAuth().subscribe( student => {
if(student) {
student.updateProfile({
displayName: '',
photoURL: this.inputImageUser.nativeElement.value
}).then( () => {
this.onLoginStudentRedirect();
}).catch( (error) => console.log('error', error));
}
});
}).catch(errorRes => {
console.log(errorRes);
switch(errorRes.code) {
case 'auth/email-already-in-use' :
this.error = 'The email address is already in use by another account!';
break;
case 'auth/invalid-email' :
this.error = 'The email address is badly formatted!';
break;
default:
this.error = 'An error occured!';
}
this.isLoading = false;
});
}
form.reset();
}
【问题讨论】:
标签: angular firebase authentication collections roles