DEV Community

Henri de la Hoz
Henri de la Hoz

Posted on

Authentication using Firebase in Angular

Adding firebase variables to our app

export const environment = {
  production: false,
  url_api: '',
  firebaseConfig: {
    apiKey: '',
    authDomain: '',
    databaseURL: '',
    projectId: '',
    storageBucket: '',
    messagingSenderId: '',
    appId: '',
  },
};
Enter fullscreen mode Exit fullscreen mode

Importing firebase modules

import { AngularFireAuthModule } from '@angular/fire/auth';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { environment } from './../environments/environment';

@NgModule({
//declarations
  imports: [
    //other modules
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule
  ],
  // providers: [],
  // bootstrap: [AppComponent],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Adding our fire module to an auth service

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private fireAuth: AngularFireAuth) {}

  createUser(email: string, password: string) {
    return this.fireAuth.createUserWithEmailAndPassword(email, password);
  }
  login(email: string, password: string) {
    return this.fireAuth.signInWithEmailAndPassword(email, password);
  }
  logout() {
    return this.fireAuth.signOut();
  }
  hasUser() {
    return this.fireAuth.authState;
  }
}

Enter fullscreen mode Exit fullscreen mode

Consuming our service in a login component

  login(event: Event) {
    event.preventDefault();
    if (this.form.valid) {
      const value = this.form.value;
      this.authService
        .login(value.email, value.password)
        .then(() => {
          this.router.navigate(['/admin']);
        })
        .catch(() => {
          alert('Invalid credentials');
        });
    }
  }
Enter fullscreen mode Exit fullscreen mode

Bonus

The following commands are useful to deploy our to firebase

firebase init
ng build --prod
firebase deploy
Enter fullscreen mode Exit fullscreen mode

The following lines can be added to firebase.json in order to avoid not found exception in case we want to go to an specific path directly in the browser.

"hosting": {
  // ...

  // Serves index.html for requests to files or directories that do not exist
  "rewrites": [ {
    "source": "**",
    "destination": "/index.html"
  } ]
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (1)

Collapse
 
jdgamble555 profile image
Jonathan Gamble

You need to update to FB 9.