Skip to content

Instantly share code, notes, and snippets.

@reyco1
Created September 16, 2022 15:04
Show Gist options
  • Save reyco1/e4f8747289efd9c981c3babb2be4218e to your computer and use it in GitHub Desktop.
Save reyco1/e4f8747289efd9c981c3babb2be4218e to your computer and use it in GitHub Desktop.
Angular Firebase Auth Service
import { Injectable } from '@angular/core';
import {
Auth, authState, createUserWithEmailAndPassword, GoogleAuthProvider, OAuthCredential,
signInWithCredential, signInWithEmailAndPassword, signInWithPopup, signOut
} from '@angular/fire/auth';
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
import { Capacitor } from '@capacitor/core';
import { AlertController, LoadingController } from '@ionic/angular';
import { switchMap } from 'rxjs/operators';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private auth: Auth,
private alertCtrl: AlertController,
private userService: UserService,
private loadingCtrl: LoadingController
) {
authState(this.auth)
.pipe(switchMap(user => this.userService.getUserData(user)))
.subscribe({
next: user => {
if (user) {
this.userService.currentUser.next(user);
} else {
this.userService.currentUser.next(null);
}
console.log('currentUser', this.userService.currentUser.value);
}
});
}
registerUserWithEmailAndPassword(email: string, password: string) {
createUserWithEmailAndPassword(this.auth, email, password)
.then(userCredential => this.userService.getUserData(userCredential.user))
.catch(err => this.showErrorAlert(err));
}
signInUserWithEmailAndPassword(email: string, password: string) {
signInWithEmailAndPassword(this.auth, email, password)
.then(userCredential => this.userService.getUserData(userCredential.user))
.catch(err => this.showErrorAlert(err));
}
async signInWithGoogle() {
const isNativePlatform = Capacitor.isNativePlatform();
const loading = await this.loadingCtrl.create();
loading.present();
if (isNativePlatform) {
const result = await FirebaseAuthentication.signInWithGoogle();
const oAuthCreds: OAuthCredential = GoogleAuthProvider.credential(result.credential?.idToken);
signInWithCredential(this.auth, oAuthCreds)
.then(userCredential => this.userService.getUserData(userCredential.user))
.then(() => loading.dismiss())
.catch(err => this.showErrorAlert(err));
} else {
signInWithPopup(this.auth, new GoogleAuthProvider())
.then(userCredential => this.userService.getUserData(userCredential.user))
.then(() => loading.dismiss())
.catch(err => this.showErrorAlert(err));
}
};
async signOut() {
await FirebaseAuthentication.signOut();
await signOut(this.auth);
}
private showErrorAlert(error: any) {
console.log(error);
this.alertCtrl.create({
header: error.error.message,
message: error.error.error,
buttons: ['OK']
}).then(alert => alert.present());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment