Last active
October 20, 2022 07:03
-
-
Save evlymn/812743a9cd06acfc14e3194c9c75c5cd to your computer and use it in GitHub Desktop.
Authentication Service Modular Firebase 9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, NgZone } from '@angular/core'; | |
import { | |
Auth, signOut, user, signInWithEmailAndPassword, createUserWithEmailAndPassword, | |
updateProfile, sendEmailVerification, sendPasswordResetEmail, User, authState, onAuthStateChanged, | |
ActionCodeSettings | |
// getAdditionalUserInfo, | |
// OAuthProvider, | |
// linkWithPopup, | |
// unlink, | |
// updateEmail, | |
// updatePassword, | |
// reauthenticateWithPopup, | |
// signInWithPopup, | |
} from '@angular/fire/auth'; | |
import { Router } from '@angular/router'; | |
import { onIdTokenChanged } from '@firebase/auth'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthenticationService { | |
private _route = ''; | |
constructor(private auth: Auth, private router: Router, | |
private ngZone: NgZone) { | |
this.onAuthStateChanged(); | |
} | |
setActiveRoute(url: string) { | |
this._route = url; | |
} | |
public get authState() { | |
return authState(this.auth); | |
} | |
public get user() { | |
return user(this.auth); | |
} | |
onIdTokenChanged() { | |
onIdTokenChanged(this.auth, async usr => { | |
const tokenResult = await usr?.getIdTokenResult(); | |
console.log('IdToken', tokenResult?.authTime); | |
}) | |
} | |
private onAuthStateChanged() { | |
onAuthStateChanged(this.auth, usr => { | |
if (usr) { | |
this.ngZone.run(() => { | |
this.router.navigate([this._route]).catch(reason => console.log(reason)); | |
}); | |
} else { | |
this.ngZone.run(() => { | |
this.router.navigate(['login']).catch(reason => console.log(reason)); | |
}); | |
} | |
}); | |
} | |
signInWithEmailAndPassword(email: string, password: string) { | |
return signInWithEmailAndPassword(this.auth, email, password); | |
} | |
createUserWithEmailAndPassword(email: string, password: string) { | |
return createUserWithEmailAndPassword(this.auth, email, password); | |
} | |
updateProfile(data: any) { | |
return updateProfile(this.auth.currentUser as User, data) | |
} | |
sendEmailVerification(actionCodeSettings?: ActionCodeSettings) { | |
return sendEmailVerification(this.auth.currentUser as User, actionCodeSettings); | |
} | |
sendPasswordResetEmail(email: string, actionCodeSettings?: ActionCodeSettings) { | |
return sendPasswordResetEmail(this.auth, email, actionCodeSettings); | |
} | |
signOut() { | |
signOut(this.auth); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment