LoginSignup
0
1

More than 3 years have passed since last update.

[API][YouTube][第弍章]Googleアカウント認証

Last updated at Posted at 2020-03-08

HTLMの用意

haml
%section
  .container
    .container-nest
      %p.google-log Log in With Google
      %button.btn.red#authorize-button
        Log in
      %button.btn.red#signout-button
        Log Out
    %br/
      #content
        .row
          .col.s6
            %form#channel-form
              .input-field.col.s6
                %input#channel-input{:placeholder => "Enter Channel Name", :type => "text"}
                %input.btn.grey.lighten-2#submits__btn{:type => "submit", :value => "Get Channel Data"}
          .col.s6#channel-data
        .row#video-container

%script{:src => "/assets/youtube.js", :type => "text/javascript"}

%script{:onload => "this.onload=function(){};handleClientLoad()", :onreadystatechange => "if (this.readyState === 'complete') this.onload()", :src => "https://apis.google.com/js/api.js"}

id#content以下scriptまでは今回要らないhtmlですが最終章で使用するので記述しておいてください。

JavaScript記述

では、JavaScriptを記述していきます。
参考:https://developers.google.com/youtube/v3/quickstart/js

main.js
//登録したOAuth 2.0クライアントIDをCLIENT_IDに入力
var CLIENT_ID = 'YOUR_CLIENT_ID';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/youtube.readonly";

hamlに記述したDOMの取得を変数に定義していきます。
ログインボタンとログアウトボタンのDOMも取得していますが、最終章で使用しますので、一気に記述しています。

main.js
//ログインボタン要素取得
var authorizeButton = document.getElementById('authorize-button');
//ログアウトボタン要素取得
var signoutButton = document.getElementById('signout-button');
var content = document.getElementById('content');
var channelForm = document.getElementById('channel-form');
var channelInput = document.getElementById('channel-input');
var videoContainer = document.getElementById('video-container');
//デフォルトで表示するチャンネルが代入された変数
var defaultChannel = 'techguyweb';

Googleログイン認証

main.js

//auth2ライブラリの読み込み
  function handleClientLoad(){
    gapi.load('client:auth2' , initClient);
  }


  function initClient(){
    gapi.client.init({
      discoveryDocs: DISCOVERY_DOCS,
      clientId: CLIENT_ID,
      scope: SCOPES
    }).then(() => {

      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }

handleAuthClickとhandleSignoutClick関数は後で追加します。
それでは次にサインインしている状態とサインアウトしている状態での要素のdisplayを変更します。

main.js
function updateSigninStatus(isSignedIn) {
    if(isSignedIn){
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
      content.style.display = 'block';
      videoContainer.style.display = 'inline-block';

    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
      content.style.display = 'none';
      videoContainer.style.display = 'none';

    }
  }

サインインしている状態ではサインインボタンがdisplay:none;でサインアウトボタンとクリエイター情報や動画を表示するコンテンツボックスはdisplay:block;にしておきます。
サインアウトしている状態ではその逆です。

main.js
//サインイン
function handleAuthClick(){
  gapi.auth2.getAuthInstance().signIn();
}

//サインアウト
function handleSignoutClick(){
  gapi.auth2.getAuthInstance().signOut();
}

handleAuthClickはauthorizeButtonをクリックした時に動く関数です。
handleSignoutClickはsignoutButtonをクリックした時に動く関数です。
これで一連の流れができたので完成品をご覧ください。

完成品

Image from Gyazo
これでGoogle認証が完了しました。
それではここからYouTubeAPIを使ったチャンネル情報の検索機能を実装していきます。
最終章:YouTubeAPIを使用したチャンネル情報検索機能

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