我正在创建一个应用程序angular和firebase。在那儿我有3个角色。超级管理员,员工,用户。超级管理员可以创建读取更新和删除,而用户和员工只能进行更新和创建。基于那里的用户角色,我想显示或隐藏我的用户界面的某些部分。请找到我的身份验证服务和用户界面代码,并提出实现此目标的最佳方法。
身份验证服务:
export class AuthService {
userData: any; // Save logged in user data
constructor(
public afAuth: AngularFireAuth, // Inject Firebase auth service
public afs: AngularFirestore, // Inject Firestore service
) {
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
})
}
SetUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const userData: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
emailVerified: user.emailVerified
}
return userRef.set(userData, {
merge: true
})
}
doRegister(name, email, password) {
return new Promise<any>((resolve, reject) => {
this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((result) => {
up and returns promise */
//Updating User name in Firebase User Table
result.user
.updateProfile({
displayName: name
})
.then(() => {
this.SetUserData(result.user);
})
.catch(error => { });
resolve(result);
}).catch((error) => {
reject(error);
})
});
}
doLogin(email, password) {
return new Promise<any>((resolve, reject) => {
this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
this.SetUserData(result.user);
resolve(result);
console.log(result);
}).catch((error) => {
console.log(error);
reject(error);
})
});
}
// Returns true when user is looged in and email is verified
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null && user.emailVerified !== false) ? true : false;
}
}
用户界面:
export interface User {
uid: string;
email: string;
displayName: string;
emailVerified: boolean;
}