LoginSignup
0
0

More than 3 years have passed since last update.

【Nuxt.js】firebase基礎編(Auth版):Twitterログインをできるようにしよう

Posted at

前置き

スクリーンショット 2020-06-04 23.46.00.png
今回はTwitterアカウントでログイン🐥
Twitterはユーザー数が多いので
これができたらすっごく便利です💕

メールアドレスログインと
要領は同じです!
コードもこちらに付け足します✍️
https://note.com/aliz/n/n7f4ae08ba828

ということで
firebaseAuthを使います💡

Step1: Twitter Developerアカウント作成の申請

Googleログインとは違い
外部のアカウントでログインします。
Twitter Developerを使用します🌟

まずはfirebaseのGuidesを見てみましょう👀
4. Register your app
API keyなどが必要ですね💡
Before you begin

Twitter Developer へ飛びましょう!🐥
ここでアプリを作成し、
API keyを入手します!

Twitter Developer

Twitterアカウントでログインし、
メニュー右上のAppsをクリック
Create an appをクリック
申請の仕方などはここが参考になります
https://www.itti.jp/web-direction/how-to-apply-for-twitter-api/
https://digitalnavi.net/internet/3072/

Frame 7.png

ここで皆さんビックリすることでしょう😲
申請理由を英語200文字以上で
書かねばなりません!笑
ログインです、ログイン!笑
とにかくログイン機能の実装したい!
ってことを伝えましょう🌟
Google翻訳を使いました📚

例文)
I want to implement login with a Twitter account on my website. I have already implemented login with a google account. All I have to do now is Twitter and facebook! It is very convenient to be able to log in with an already created account.

グーグルアカウントの
ログインは実装しちゃってて
あとはこのTwitterとFacebookアカウントでの
ログインをしたいんです!
って内容です。
これで無事承認されました🤗

Step2: アプリを作成する

申請が通るとメールが届きます💌
メール内のbutton押すと
アカウントが作成されます🌟

次は実際にアプリを作成していきましょう!

  1. Header > アカウント名 > Apps
    Frame 8.png

  2. Create an app
    Frame 9.png

  3. 必須項目の入力し、createを押す
     ・App name:アプリの名前
     ・Application description:
      アプリの説明(英語10〜200文字)
     ・Website URL:
      アプリを使用するウェブサイトのURL
     ・Tell us how this app will be used:
      アプリの使用方法
      アプリの説明とほぼ同じでOK
      (英語100文字〜)

 こちらは必須ではないですが
 後ほど入力します!
 ・Callback URLs
スクリーンショット 2020-06-04 23.11.59.png

これでアプリの完成です🤗

Step3: firebaseと連携

アプリが完成したので
API keyなどの確認をしていきましょう!

  1. アプリのDetailsをクリック!

Frame 10.png

  1. Keys and tokensタブをクリック
     API key, API secret key が見れます👀
     これをfirebaseにコピペしましょう!
    Frame 11.png

  2. firebaseにコピペ
     プロジェクトサイドメニューAuthentication
     > Sign-in method > Twitter
     > App ID とApp secretをペースト
     ここでコールバックURLをコピーしましょう!

Frame 12.png

  1. コールバックURLを貼り付け  Twitter DevelopersアプリのDetailsで  App detailsタブのEditをクリック  Step2で一旦空欄にしていた  Callback URLsにペーストしましょう🌟

Frame 13.png

これで設定は完了です🤗

Step4: コードを追加

firebase Guides
Handle the sign-in flow with the Firebase SDK

【解説/store/index.js】
必須項目:1, 4
Optional:2, 3

ということで必須項目だけ
Vuexにコピペしていきます。

・actions loginTwitterを作成
 ログインできたら
 ログイン状態をtrueにしたいので
 それを行うcheckLoginをdispatchで呼ぶ
・不要な物を削除
 コメント
 セミコロン(;)
 var token
 var user
 state, checkLoginのemail
  →メールアドレスログイン時に
   ユーザーのemailを取得し、
   表示させるために記載していたもの
   SNSアカウントを使用するため不要

store/index.js
import firebase from '~/plugins/firebase'

export const state = () => ({
 user: {
  uid: '',
  login: false,
 },
})

export const getters = {
 user: state => {
  return state.user
 }
}

export const actions = {
 login({ dispatch }, payload) {
  firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
    .then(user => {
        console.log('成功!')
        dispatch('checkLogin')
      }).catch((error) => {
        alert(error)
      })
 },
 loginTwitter ({ dispatch }) {
  var provider = new firebase.auth.TwitterAuthProvider()
  firebase.auth().signInWithPopup(provider).then(function (result) {
    dispatch('checkLogin')
  }).catch(function (error) {
    console.log(error)
  })
 },
 checkLogin ({ commit }) {
  firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      commit('getData', { uid: user.uid })
      commit('switchLogin')
    }
  })
 },
}

export const mutations = {
 getData (state, payload) {
  state.user.uid = payload.uid
 },
 switchLogin (state) {
  state.user.login = true
 },
}
Login.vue
<template>
 <div class="login">
  <p
  v-if="user.login"
  class="text"
  >
  {{ user }}
  </p>
  <form
  v-else
  class="form"
  @submit.prevent
  >
   <label class="label">
    <span class="label">
      email
    </span>
    <input
      class="input"
      type="text"
      v-model="email"
    >
   </label>
   <label class="label">
    <span class="label">
      password
    </span>
    <input
      class="input"
      type="password"
      v-model="password"
    >
   </label>
   <button
    class="button"
    type="submit"
    @click="login"
   >
    Login
   </button>
   <button
     class="button"
     type="submit"
     @click="loginTwitter"
   >
     twiiterでログイン
   </button>
  </form>
 </div>
</template>

<script>
export default {
 computed: {
  user () {
   return this.$store.getters['user']
  },
 },
 data () {
  return {
   email: '',
   password: '',
  }
 },
 methods : {
  login (email, password) {
   this.$store.dispatch('login', {email: this.email, password: this.password})
  },
  loginTwitter () {
   this.$store.dispatch('loginTwitter')
  },
 }
}
</script>
index.vue
<template>
 <div class="page">
  <Login />
   <p
    v-if="user.login"
    class="text"
   >
    ログインに成功!
  </p>
 </div>
</template>

<script>
import Login from '~/components/Login.vue'

export default {
 components: {
  Login: Login,
 },
 computed: {
  user () {
   return this.$store.getters['user']
  },
 },
}
</script>

ログインはこれだけです🌟
Twitter Developerの申請さえ通れば簡単ですね♪

また別記事でこちらも公開していきます!
・アカウント作成の方法
・ログアウトの仕方

次回予告

【Nuxt.js】Nuxt文法編:v-show
6/9(火)公開です!

【Nuxt.js】アプリ開発実践編:Nuxt + Vuex + firebaseでログイン付きToDoリスト②
こちらの記事は内容を整理中です🙇‍♀️
きちんとした内容にします💪

記事が公開したときにわかる様、
フォローをお願いします😀💕

https://twitter.com/aLizlab

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