Created
January 20, 2019 05:02
-
-
Save GeoffMahugu/5a9169e51e8f5cf4373c6795b31cbb1e to your computer and use it in GitHub Desktop.
Angular FireAuth Phone-Login
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 { Component, OnInit } from '@angular/core'; | |
import { WindowService } from '../core/window.service'; | |
import { MatSnackBar } from '@angular/material'; | |
import { Router } from '@angular/router'; | |
import * as firebase from 'firebase/app'; | |
import { environment } from '../../environments/environment'; | |
import { AuthService } from '../core/auth.service'; | |
interface User { | |
uid: string; | |
email: string; | |
} | |
export class PhoneNumber { | |
country: string = "+254"; | |
phone_number: string = ""; | |
get e164() { | |
const num = this.country + this.phone_number | |
return `+${num}` | |
} | |
} | |
@Component({ | |
selector: 'app-phone-login', | |
templateUrl: './phone-login.component.html', | |
styleUrls: ['./phone-login.component.css'], | |
providers: [ WindowService] | |
}) | |
export class PhoneLoginComponent implements OnInit { | |
windowRef: any; | |
phoneNumber = new PhoneNumber() | |
verificationCode: string; | |
private social_user:any; | |
constructor( private snackBar: MatSnackBar, private router: Router, private win: WindowService, private auth_service: AuthService) { } | |
ngOnInit() { | |
this.windowRef = this.win.nativeWindow | |
firebase.initializeApp(environment.firebase) | |
this.windowRef.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container') | |
this.windowRef.recaptchaVerifier.render() | |
} | |
sendLoginCode() { | |
const appVerifier = this.windowRef.recaptchaVerifier; | |
const num = this.phoneNumber.e164; | |
firebase.auth().signInWithPhoneNumber(num, appVerifier) | |
.then(result => { | |
this.windowRef.confirmationResult = result; | |
}) | |
.catch( error => | |
this.snackBar.open(error, 'CLOSE', { | |
duration: 3500 | |
}) | |
); | |
} | |
verifyLoginCode() { | |
this.windowRef.confirmationResult | |
.confirm(this.verificationCode) | |
.then( result => { | |
this.auth_service.updateUserData(result.user); | |
this.snackBar.open('Successfully authenticated', 'CLOSE', { | |
duration: 3500 | |
}); | |
window.location.reload() | |
}) | |
.catch( error =>{ | |
this.snackBar.open(error.message, 'CLOSE', { | |
duration: 3500 | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment