我正在尝试使用Firebase创建用户身份验证。
我在应用程序中扮演两个角色:学生和老师,我在注册时将其添加到名为users
的Firebase集合中,并且具有现场角色。
我的问题是我想将学生重定向到学生资料页面,并将老师重定向到老师资料页面。我有两种不同的形式,一种用于学生的登录,一种用于教师的登录。
当我在学生登录名中输入老师的数据时,由于该用户不存在,我想收到该错误。
现在我没有任何错误,如果我只有一种登录形式,那么一切都可以正常工作,但是我有两种登录形式,因此如果用户是老师并登录到学生,我希望它给我带来错误。
这是我为我的身份验证服务中的学生登录的信息
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也是如此。 这是在我的auth组件中,用于提交学生登录的表单。
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();
}
答案 0 :(得分:0)
第一个选项:
为什么对学生和教师都没有简单的login
方法,它将解析为具有学生或教师属性的对象。
在您的onSubmit
方法中,您可以相应地处理错误。
第二个选项
可以使几乎所有内容保持不变,但是您会抛出特定的错误,而不是在this.router.navigate(['/student/profile']);
方法中使用重定向(login
)。
然后您在onSubmit
中捕获了该特定错误。