You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Service for Authenticating Users via Firebase and Angular
written by Jeff DelaneyThis code handles most of the heavy lifting for Firebase user auth in Angular2+, including OAuth, Anonymous, and Email/Password providers. It uses the AngularFire2 package. If you want to learn how this code works step-by-step, check out the AngularFirebase OAuth tutorial.
Gist
This file contains hidden or 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 } from '@angular/core'; | |
import { AngularFireAuth, AngularFireDatabase, FirebaseAuthState, AuthProviders, AuthMethods, AngularFire } from "angularfire2"; | |
import { Router } from "@angular/router"; | |
import * as firebase from 'firebase'; | |
@Injectable() | |
export class AuthService { | |
authState: FirebaseAuthState = null; | |
constructor(private af: AngularFire, | |
private db: AngularFireDatabase, | |
private router:Router) { | |
af.auth.subscribe((auth) => { | |
this.authState = auth; | |
}); | |
} | |
// Returns true if user is logged in | |
get authenticated(): boolean { | |
return this.authState !== null; | |
} | |
// Returns current user | |
get currentUser(): any { | |
return this.authenticated ? this.authState.auth : null; | |
} | |
// Returns current user UID | |
get currentUserId(): string { | |
return this.authenticated ? this.authState.uid : ''; | |
} | |
// Anonymous User | |
get currentUserAnonymous(): boolean { | |
return this.authenticated ? this.authState.anonymous : false | |
} | |
//// Social Auth //// | |
githubLogin(): firebase.Promise<FirebaseAuthState> { | |
return this.socialSignIn(AuthProviders.Github); | |
} | |
googleLogin(): firebase.Promise<FirebaseAuthState> { | |
return this.socialSignIn(AuthProviders.Google); | |
} | |
facebookLogin(): firebase.Promise<FirebaseAuthState> { | |
return this.socialSignIn(AuthProviders.Facebook); | |
} | |
twitterLogin(): firebase.Promise<FirebaseAuthState> { | |
return this.socialSignIn(AuthProviders.Twitter); | |
} | |
private socialSignIn(provider: number): firebase.Promise<FirebaseAuthState> { | |
return this.af.auth.login({provider, method: AuthMethods.Popup}) | |
.then(() => this.updateUserData() ) | |
.catch(error => console.log(error)); | |
} | |
//// Anonymous Auth //// | |
anonymousLogin() { | |
return this.af.auth.login({ | |
provider: AuthProviders.Anonymous, | |
method: AuthMethods.Anonymous, | |
}) | |
.then(() => this.updateUserData()) | |
.catch(error => console.log(error)); | |
} | |
//// Email/Password Auth //// | |
emailSignUp(email: string, password: string): firebase.Promise<FirebaseAuthState> { | |
return this.af.auth.createUser({ | |
email: email, | |
password: password, | |
}) | |
.then(() => this.updateUserData()) | |
.catch(error => console.log(error)); | |
} | |
emailLogin(email: string, password: string): firebase.Promise<FirebaseAuthState> { | |
return this.af.auth.login({ email, password }, | |
{ provider: AuthProviders.Password, | |
method: AuthMethods.Password | |
}) | |
.then(() => this.updateUserData()) | |
.catch(error => console.log(error)); | |
} | |
//// Sign Out //// | |
signOut(): void { | |
this.af.auth.logout(); | |
this.router.navigate(['/']) | |
} | |
//// Helpers //// | |
private updateUserData(): void { | |
// Writes user name and email to realtime db | |
// useful if your app displays information about users or for admin features | |
let path = `users/${this.currentUserId}`; // Endpoint on firebase | |
let data = { | |
name: this.currentUser.displayName, | |
email: this.currentUser.email, | |
} | |
this.db.object(path).update(data) | |
.catch(error => console.log(error)); | |
} |