Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular4 Firebase authentication service using OAuth, Anonymous, and Email/Password. Designed specifically for changes introduced in AngularFire2 4.0.0
import { Injectable } from '@angular/core';
import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { Router } from "@angular/router";
import * as firebase from 'firebase';
@Injectable()
export class AuthService {
authState: any = null;
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router:Router) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth
});
}
// Returns true if user is logged in
get authenticated(): boolean {
return this.authState !== null;
}
// Returns current user data
get currentUser(): any {
return this.authenticated ? this.authState : null;
}
// Returns
get currentUserObservable(): any {
return this.afAuth.authState
}
// Returns current user UID
get currentUserId(): string {
return this.authenticated ? this.authState.uid : '';
}
// Anonymous User
get currentUserAnonymous(): boolean {
return this.authenticated ? this.authState.isAnonymous : false
}
// Returns current user display name or Guest
get currentUserDisplayName(): string {
if (!this.authState) { return 'Guest' }
else if (this.currentUserAnonymous) { return 'Anonymous' }
else { return this.authState['displayName'] || 'User without a Name' }
}
//// Social Auth ////
githubLogin() {
const provider = new firebase.auth.GithubAuthProvider()
return this.socialSignIn(provider);
}
googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.socialSignIn(provider);
}
facebookLogin() {
const provider = new firebase.auth.FacebookAuthProvider()
return this.socialSignIn(provider);
}
twitterLogin(){
const provider = new firebase.auth.TwitterAuthProvider()
return this.socialSignIn(provider);
}
private socialSignIn(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.authState = credential.user
this.updateUserData()
})
.catch(error => console.log(error));
}
//// Anonymous Auth ////
anonymousLogin() {
return this.afAuth.auth.signInAnonymously()
.then((user) => {
this.authState = user
this.updateUserData()
})
.catch(error => console.log(error));
}
//// Email/Password Auth ////
emailSignUp(email:string, password:string) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((user) => {
this.authState = user
this.updateUserData()
})
.catch(error => console.log(error));
}
emailLogin(email:string, password:string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((user) => {
this.authState = user
this.updateUserData()
})
.catch(error => console.log(error));
}
// Sends email allowing user to reset password
resetPassword(email: string) {
var auth = firebase.auth();
return auth.sendPasswordResetEmail(email)
.then(() => console.log("email sent"))
.catch((error) => console.log(error))
}
//// Sign Out ////
signOut(): void {
this.afAuth.auth.signOut();
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 = {
email: this.authState.email,
name: this.authState.displayName
}
this.db.object(path).update(data)
.catch(error => console.log(error));
}
}
@jacobedawson

This comment has been minimized.

Copy link

@jacobedawson jacobedawson commented Jun 17, 2017

Hi - I'm trying to adapt this code but it doesn't completely make sense - you keep referencing 'this.authenticated' but 'authenticated' is never actually declared within auth.service.ts. Using the same code in my project brings up an error:
Property 'authenticated' does not exist on type 'AuthService'.

Is there a reason for this? Is it something that has been omitted on purpose, or by design?

@codediodeio

This comment has been minimized.

Copy link
Owner Author

@codediodeio codediodeio commented Jul 20, 2017

Just saw your comment. It is defined as a typescript getter at line 24. You should not be getting an error...

get authenticated(): boolean {
    return this.authState !== null;
  }
@shishirkumarm

This comment has been minimized.

Copy link

@shishirkumarm shishirkumarm commented Sep 1, 2017

Hi @codediodeio,

Please help me knowing how recover Location/Home Location from 19 LOC. (this.authState = auth). I can find all the details like

  • Display Name
  • Email ID
  • UID number
  • Phone number

Is there something I need to set in the social account ( facebook, google) for this or any specific key I need to look at in the this.authState object ?

@ziaongit

This comment has been minimized.

Copy link

@ziaongit ziaongit commented Nov 14, 2017

How I can bind errors to my dom?

@Tooluloope

This comment has been minimized.

Copy link

@Tooluloope Tooluloope commented Nov 22, 2017

pls, how do I store a users display name when using createUserWithEmailAndPassword? thanks in advance

@tonymathewt

This comment has been minimized.

Copy link

@tonymathewt tonymathewt commented Dec 8, 2017

Do we get a token after authentication?

@iamonuwa

This comment has been minimized.

Copy link

@iamonuwa iamonuwa commented Feb 8, 2018

currentUserToken(): any { return firebase.auth().currentUser.getIdToken(false).then(idToken => { return localStorage.setItem('userToken', idToken); }).catch(error => { return error; }) }

@mikgross

This comment has been minimized.

Copy link

@mikgross mikgross commented Apr 9, 2018

Hi -- Please note that 'FirebaseListObservable' throws the following error: Module "module" has no exported member 'FirebaseListObservable'

@alexfung888

This comment has been minimized.

Copy link

@alexfung888 alexfung888 commented May 14, 2018

Can you make the code work beyond firebase@4.12.1? Importing the full package from the 'firebase' gets a runtime warning, but all my attempts to import from 'firebase/app' and 'firebase/auth' failed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment