When a new user is registered, certain values for user access control are set up immediately.
The issue arises when the data set is only visible in the subsequent sessions after logging out of the authenticated user session that was created.
My challenge lies in retrieving claims right after creating a new user in Firebase Authentication, without the need to log out and back in to obtain this crucial data.
auth.service.ts
public user: any;
public firestoreCollection: string;
public admin: boolean;
constructor(private _angularFireauth: AngularFireAuth) {
this.getUser().subscribe((user: firebase.User) => {
this.user = user;
if (this.user) {
// Obtaining claims requires a logout() followed by login().
user.getIdTokenResult().then(idTokenResult => {
this.firestoreCollection = idTokenResult.claims.firestoreCollection;
this.admin = idTokenResult.claims.admin;
});
}
});
}
public getUser(): Observable<firebase.User> {
return this._angularFireauth.authState;
}
public async createAccount(user: any): Promise<void> {
const auth = await this._angularFireauth.auth
.createUserWithEmailAndPassword(user.email, user.password);
const userObject = {
displayName: user.nome.trim(),
photoURL: 'assets/images/avatars/profile.jpg'
};
await auth.user.updateProfile(userObject);
const setUserControlAccess = firebase.functions()
.httpsCallable('setUserControlAccess');
await setUserControlAccess({
admin: true, assinante: true, profissional: true,
firestoreCollection: auth.user.uid,
email: auth.user.email
});
// Attempted re-authentication to fetch claims.
await this.reauthenticateUser(user.email, user.password);
}
Cloud Functions
export const setUserControlAccess = functions.https.onCall(async (data, context) => {
try {
const customUserClaims = {
admin: data.admin,
firestoreCollection: data.firestoreCollection
};
const user = await admin.auth().getUserByEmail(data.email);
await authentication.setCustomUserClaims(user.uid, customUserClaims);
} catch (error) {
console.error(error);
return error;
}
});