Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create user Login with email and password using AngularFire2

I have created a login-service with the options to log in with google, facebook or twitter, and it is working well.

I am trying to create the option to log in with an email and a password (the option is enabled in the firebase console), and I am not able to make it work.

My login-service code is the following :

import {Injectable, OnInit} from '@angular/core';
import {AngularFire, AuthProviders, AuthMethods} from "angularfire2/angularfire2";


@Injectable()
export class LoginService implements OnInit {
public isLoged: boolean;

ngOnInit() {

}

constructor(private af: AngularFire) {
  this.af.auth.subscribe(user => {
    if (user) {
      this.isLoged = true;
      console.info("Se ha logueado correctamente")
    } else {
      this.isLoged = false;
      console.info("Se ha deslogueado correctamente");
    }
  });
}

login() {
  this.af.auth.login();
}

loginGoogle() {
  //this is the default login , that it's setup in the main.js
  this.login();
}

loginFacebook() {
  this.af.auth.login({
    provider: AuthProviders.Facebook,
    method: AuthMethods.Redirect
  });
}

loginTwitter() {
  this.af.auth.login({
    provider: AuthProviders.Twitter,
    method: AuthMethods.Redirect
  });
}

createUser(email: string, password: string) {
  this.af.auth.createUser({ email: email, password: password });
}

loginWithPassword() {
  this.af.auth.login({

    provider: AuthProviders.Password,
    method: AuthMethods.Password
  })
}

logOut() {
  this.af.auth.logout();
}

}

And the main.ts is :

import { APP_BASE_HREF } from '@angular/common';
import { disableDeprecatedForms, provideForms } from '@angular/forms';
import { enableProdMode } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';

import { APP_ROUTER_PROVIDERS } from './app.routes';
import { AppComponent } from './app.component';
import {
  FIREBASE_PROVIDERS, defaultFirebase, firebaseAuthConfig, AuthProviders,
  AuthMethods
} from "angularfire2/angularfire2";

if ('<%= ENV %>' === 'prod') { enableProdMode(); }

/**
 * Bootstraps the application and makes the ROUTER_PROVIDERS and the APP_BASE_HREF available to it.
 * @see https://angular.io/docs/ts/latest/api/platform-browser-dynamic/index/bootstrap-function.html
 */
bootstrap(AppComponent, [
  disableDeprecatedForms(),
  provideForms(),
  APP_ROUTER_PROVIDERS,
  {
    provide: APP_BASE_HREF,
    useValue: '<%= APP_BASE %>'
  },
  FIREBASE_PROVIDERS,
  defaultFirebase({ //this data is replaced
    apiKey: 'apiKey',
    authDomain: 'authDomain',
    databaseURL: 'databaseURL',
    storageBucket: 'storageBucket',
  }),
  firebaseAuthConfig({
    provider: AuthProviders.Google,
    method: AuthMethods.Popup,
  })
]);

Update :

As @JS_astronauts said , the problem is related with how the data is passed to the login service , right now I found that from the call to the loginService doesn't get the params right , I am using FormBuilder like this :

login.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, Validators, ControlGroup ,NgFormModel} from '@angular/common'
import {AngularFire, AuthProviders, AuthMethods} from 'angularfire2';
import {LoginService} from '../shared/login-service/login.service'
import {Router} from "@angular/router";

@Component({
    moduleId: module.id,
    selector: 'login',
    templateUrl: 'login.component.html',
    styleUrls : ['login.component.css'],
    directives : [NgFormModel]
})
export class LoginComponent implements OnInit {

    loginForm : ControlGroup;

    constructor(private router: Router,
                private fb : FormBuilder,
                private loginService : LoginService) {

      this.loginForm = fb.group({
        name : ["" , Validators.required],
        correo : ["" , Validators.required],
        contrasena :["",Validators.required]
      })
    }

    ngOnInit() {
    }

    loginWithPassword(){
      this.loginService.createUser( 
        this.loginForm.controls['correo'].value.toString() ,
        this.loginForm.controls['contrasena'].value.toString()
      );

  if(this.loginService.isLoged ){
    this.router.navigate(['./ejemplo']);
  }
}
}

And in the html I have :

 <form [ngFormModel]="loginForm" (submit)="loginWithPassword()">
    <div id="DIV_13">
      <div id="DIV_14">
        <span id="SPAN_15"> <i id="I_16">face</i></span>
        <div id="DIV_17">
          <input ngControl="name" type="text" placeholder="First Name..." id="INPUT_18" /><span id="SPAN_19"></span>
        </div>

      </div>
      <div id="DIV_20">
        <span id="SPAN_21"> <i id="I_22">email</i></span>
        <div id="DIV_23">
          <input ngControl="correo"  type="text" placeholder="Email..." id="INPUT_24" /><span id="SPAN_25"></span>
        </div>
      </div>
      <div id="DIV_26">
        <span id="SPAN_27"> <i id="I_28">lock_outline</i></span>
        <div id="DIV_29">
          <input  ngControl="contrasena" type="password" placeholder="Password..." id="INPUT_30" /><span id="SPAN_31"></span>
        </div>
      </div> 
    </div>

    <div id="DIV_32">
      <button type="submit" id="A_33">Get Started</button>
    </div>
    </form>

But the value that I get with this.loginForm.controls['correo'].value.toString() is equal to null , so how I get the value ?

Any idea where is the problem? Regards Roberto.

like image 333
Roberto Fernandez Diaz Avatar asked Feb 06 '23 13:02

Roberto Fernandez Diaz


1 Answers

If you can not log in with user data, there is an issue how the data gets passed to the login service.

Plunker

Here is an example with User service:

  import {Injectable} from '@angular/core';

  @Injectable()
  export class UserService {
    public auth: any;
    constructor() {
      this.auth = firebase.auth();
    }

    public login(userEmail: string, userPassword: string) {
      return new Promise((resolve, reject) => {
        this.auth.signInWithEmailAndPassword(userEmail, userPassword)
          .then(userData => resolve(userData),
            err => reject(err));
      });
    }

    public logout() {
      return this.auth.signOut();
    }
  }

Login component:

import { Component } from '@angular/core';
import { FORM_DIRECTIVES } from '@angular/common';
import { UserService } from './user.service';

@Component({
  selector: 'login',
  template: `
  <form (ngSubmit)="login()">
    <label for="userEmail">Email</label><br/>
    <input type="email" required
      [(ngModel)]="userEmail" >
    <br/>
    <label for="userPassword">Password</label><br/>
    <input type="password" required
      [(ngModel)]="userPassword" >
    <hr/>
    <button type="submit">Login!</button>
  </form>
  `,
  directives: [FORM_DIRECTIVES],
  providers: [UserService]
})
export class LoginComponent {
  public userEmail: string;
  public userPassword: string;
  constructor(private _user: UserService) {}

  public login() {
    this._user.login(this.userEmail, this.userPassword)
  }
}

Simple user login:

email: string;
pw: string;
authed: boolean;
constructor(private _us: UserService) {
  this.authed = false;
}

signup() {
  this._us.signUp(this.email, this.pw);
}

login() {
  this._us.login(this.email, this.pw).then((res) => {
    console.log(res);
    if (res.provider === 4)
      this.authed = true;
  });
}

angularfire2: plunker

login component class:

export class App {
    email: string;
    pw: string;
    authed: boolean;
    constructor(private _us: UserService) {
        this.authed = false;
    }

    signup() {
        this._us.signUp(this.email, this.pw);
    }

    login() {
        this._us.login(this.email, this.pw).then((res) => {
            console.log(res);
            if (res.provider === 4)
                this.authed = true;
        });
    }

}

service:

    import { Injectable } from '@angular/core';
    import { AngularFire, FirebaseAuth } from 'angularfire2';

    @Injectable()
    export class UserService {
        public db: any;
        constructor(private af: AngularFire, private auth: FirebaseAuth) {

        }

        signUp(email: string, password: string) {
            var creds: any = { email: email, password: password };
            this.af.auth.createUser(creds);
        }

        login(email: string, password: string): Promise<boolean> {
            var creds: any = { email: email, password: password };
            var res: Promise<boolean> = new Promise((resolve, reject) => {
                this.auth.login(creds).then(result => {
                    resolve(result);
                })
            });
            return res;
        }

    }

bootstrap:

    //main entry point
    import {bootstrap} from '@angular/platform-browser-dynamic';
    import {App} from './app';
    import {
        FIREBASE_PROVIDERS,
        defaultFirebase,
        firebaseAuthConfig,
        AuthMethods,
        AuthProviders
    } from 'angularfire2';
    import { UserService } from './user.service';

    bootstrap(App, [
        FIREBASE_PROVIDERS,
        // Initialize Firebase app  
        defaultFirebase({
            apiKey: "AIzaSyD6v-fYdZgeHtLfBctFqEQ4Ra7ZDpLZKug",
            authDomain: "plnkr-1a222.firebaseapp.com",
            databaseURL: "https://plnkr-1a222.firebaseio.com",
            storageBucket: "plnkr-1a222.appspot.com",
        }),
        firebaseAuthConfig({
            provider: AuthProviders.Password,
            method: AuthMethods.Password
        }),
        UserService
    ])
        .catch(err => console.error(err));
like image 121
KB_ Avatar answered Feb 13 '23 06:02

KB_