0
1

More than 3 years have passed since last update.

【Firebase】Firebase Authenticationでユーザーを識別する

Last updated at Posted at 2021-04-05

ユーザーを識別する

やりたいこと

vue + firebaseで投げ銭アプリ作成中。
ログイン時、ユーザ(ドキュメント)を識別して、そのデータを取得したい。

新規登録時にuidをドキュメントIDに指定

        // 新規登録
        signUp (context, payload) {
            // firebase Authにユーザ情報登録
            firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
                .then(() => {
                    // firebase Authのユーザ名更新
                    const user = firebase.auth().currentUser
                    user.updateProfile({
                    displayName: payload.username,
                    },)
                .then(() => {
                    // データベースへ登録
                    const db = firebase.firestore();
                    db.collection("userData").doc(user.uid).set({
                        uid: user.uid,
                        email: payload.email,
                        password: payload.password,
                        username: payload.username,
                        myWallet: payload.myWallet,
                    })
                })
                .then(() => {
                    context.commit('registerUserData', payload)
                })
                .then(() => {
                    router.push('/')
                })
                })
                .catch(error => {
                    alert(error.message)
                })
        },

指定したuidでドキュメントを識別し、ユーザを取得する


        // ログイン
        signIn (context, payload) {
            // 登録済みのメールアドレスとパスワードでログイン
            firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
            .then(() => {
                const user = firebase.auth().currentUser
                const docRef = firebase.firestore().collection("userData").doc(user.uid);
                docRef.get()
                .then((doc) => {
                    if (doc.exists) {
                        context.commit('setUserData', doc)
                    } else {
                        console.log("No such document!");
                    }
                }).catch((error) => {
                    alert(error.message)
                });
            })
            .then(() => {
                router.push('/')
            })
            .catch(error => {
                alert(error.message)
            })
        }

参考

0
1
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
0
1