#概要
今回はGoogleのログインを実装していきます。
目標としてはstateにログイン情報を置いて、それがtrueならば"login with google!!", falseならば"I can not see your google account!!" と文字を出したいと思います。
#実装
まずはGoogle APIのライブラリを使うためにscriptで読み込んであげないといけません。
<script src="https://apis.google.com/js/api.js"></script>
こうすることでgapiと呼ばれるメソッドを使うことができます。
メソッドの説明に関しては以下を参考にしてください。
ページを読み込んだ際に、ログインしているか否かを判断したいので、componentDidMount()の中に実装していきます。
以下のコードを見てください。
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
clientId: "clientID", //"clientID"は個人で取得する
scope: "email"
}).then(() => {
const auth = window.gapi.auth2.getAuthInstance();
this.setState({ isSignedIn: auth.isSignedIn.get() });
});
});
}
"clientID"は以下のサイトからプロジェクトを登録して取得する必要があります。
プロジェクトを作成したら認証情報をクリックし、そこのOAuth同意画面でアプリケーション名を決めた後、認証情報を作成からOAuth クライアントIDをクリックしたら取得できると思います。
上のコードではログイン状態をstateに保存しています。
src/components/App.jsの全体を見ましょう。
import React, { Component } from 'react';
class App extends Component {
state = { isSignedIn: null };
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
clientId: "clientID",
scope: "email"
}).then(() => {
const auth = window.gapi.auth2.getAuthInstance();
this.setState({ isSignedIn: auth.isSignedIn.get() });
});
});
}
renderAuth() {
if (this.state.isSignedIn === null) {
return <div>i dont know your google account</div>
} else if (this.state.isSignedIn) {
return <div>login with google!!</div>
} else {
return <div>I can not see your google account!!</div>
}
}
loginWithGoogle = () => {
window.gapi.auth2.getAuthInstance().signIn();
}
logoutFromGoogle = () => {
window.gapi.auth2.getAuthInstance().signOut();
}
render() {
return (
<div>
{this.renderAuth()}
<button onClick={this.loginWithGoogle}>
login with google
</button>
<button onClick={this.logoutFromGoogle}>
logout from google
</button>
</div>
);
}
}
export default App;
renderAuth()で条件分岐してstateの状態によって表示する文字を変えます。
ボタンを2つ配置し、それぞれログインとログアウトのボタンです。
これらをクリックし、ページをリロードするとそれにあった文字が表示されるはずです。
#まとめ
Google認証を作ってみました。
何かサービスを作るときに利用できればと思ってます。
参考になれば幸いです。