LoginSignup
1
2

More than 5 years have passed since last update.

ionicでfirebaseへ認証できるように

Posted at

ionic環境準備とプロジェクトを作成

Firebase configとアプリ設定

Email/Password認証方法を有効する

  • Firebase console画面 -> 開発 -> Authentication -> ログイン方法
  • メール/パスワードを有効にする

Firebaseへ接続できるように

  • Project Overview -> アプリを追加 -> Web platformを選択する
  • 以下のような情報をコピー
    apiKey: "XXX",
    authDomain: "XXX.firebaseapp.com",
    databaseURL: "https://XXX.firebaseio.com",
    projectId: "XXX",
    storageBucket: "XXX.appspot.com",
    messagingSenderId: "XXX"
  • ionicプロジェクトのsrc/config.tsファイル内容を追加
export const fCon = {
    fireSetting: {
            apiKey: "XXX",
            authDomain: "XXX.firebaseapp.com",
            databaseURL: "https://XXX.firebaseio.com",
            projectId: "XXX",
            storageBucket: "XXX.appspot.com",
            messagingSenderId: "XXX"
    }
};

モジュールのインストール

インストール

$ npm install firebase angularfire2 --save

config内容を導入

  • app.modules.ts
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth } from 'angularfire2/auth';
import { firebaseConfig } from '../config';

AngularFireModule.initializeApp(fCon.fireSetting),

サービス実装

src/service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import AuthProvider = firebase.auth.AuthProvider;

@Injectable()
export class AuthService {
    private currentUser: firebase.currentUser;

    constructor(public bAuth: AngularFireAuth) {
        bAuth.authState.subscribe(user => {
            this.currentUser = user;
        });
    }

    signInWithEmail(c) {
        return this.bAuth.auth.signInWithEmailAndPassword(c.email,
             c.password);
    }

}

ログインページ実装

  • ログイン画面を省略して、ロジック部分のみを説明する
login.ts
import { AuthService } from '../../services/auth.service';

private auth: AuthService


login() {
        let d = this.loginForm.value;

        if (!d.email) {
            return;
        }

        let c = {
            email: d.email,
            password: d.password
        };
        this.auth.signInWithEmail(c)
            .then(
                () => this.navCtrl.setRoot(HomePage),
                error => this.loginError = error.message
            );
    }

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2