LoginSignup
2
0

More than 3 years have passed since last update.

Auth0で作成した認証付きカレンダーサイトをElectronでアプリ化

Last updated at Posted at 2020-01-08

リベンジ!!!

超初心者がログイン機能のついたサイトのデスクトップアプリ化に挑戦(あんど失敗・・)でAuth0のサンプルファイルを用い、elecronでデスクトップアプリ化しようとしました。

が、とログインボタンが消えるというトラブル発生(泣)。正直言って、ファイルの内容は私には理解不能。新年なので再度カレンダーにチャレンジを決意!対応を難しかったのでファイル一つコピペで試すAuth0+Vue.jsのログインサンプルを参考に今回はシンプルな1つのファイルで再挑戦です。

シンプルなコードでも組み合わせると、それなりの機能を付けられるということを書き残していきたいと思います。

目標

1)認証付きサイトをelectron化
2)上記サイトにてログイン後、ID写真付きカレンダーを表示する。

環境

Windows 10
Node.js v12.4.0
Visual Studio Code version 1.41

方法

Step1.ログインしたあなたが操る[リアル]クリスマスツリー(前編)
  「Electoron でデスクトップアプリを作ろう」の部分を参照にデスクトップアプリを
   まず作成。
Step2.「ファイル一つコピペで試すAuth0+Vue.jsのログインサンプル」を参考に、
    Index.htmlファイルを作成します。
Step3.上記index.html内でログイン後のID表示やアクセストークンについて
    記述されている部分を消去
    image.png

Step4."You are seeing this content because you're currently "を
   "カレンダーを作ろう"に変更
image.png
Step5.Step3にて削除した部分にカレンダーを作成。今回は1枚のファイルで作ることをコンセプトに万年カレンダーのソースと解説を参考にさせていただきました。
Step5.Step4で作成したindex.htmlファイルをStep1のPublicフォルダ階下のindex.htmlへ
   上書きする。
    ※ auth_config.jsonなどその他のファイルのコピーは不要です。
Step6. Terminalで"npm start"で起動
npm start

コード

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>SPA SDK Sample</title>

</head>

  <body>
    <div id="app">
        <h2>Calender Sample Project</h2>

        <button id="btn-login" v-on:click="auth0login()">Log in</button>
        <button id="btn-logout" v-on:click="auth0logout()">Log out</button>

        <div v-if="login" id="gated-content">
          <p>
            カレンダーを作ってみよう
          </p>

              <i class="text-center"></i> カレンダー例
            </a>
          <a class="auth-visible hidden">
            <img :src="userData.picture" id="ipt-user-profile-image" width="40px">
          </a>
          <script type="text/javascript">
            //日付と時間の設定
            now = new Date();
            year = now.getFullYear();
            mon = now.getMonth()+1;
            day = now.getDate();
            you = now.getDay();

            //曜日の選択肢
            youbi = new Array("<font color='#ff0000'>日</font>","","","","","","<font color='#0000ff'>土</font>");

            //表示の設定
            today = year + "" + mon + "" + day + "" + "(" + youbi[you] + ")"; 


            //画面に表示
            //document.write(today);
            //document.write("<hr>");
 //1日
    fday = new Date(year + "/" + mon + "/1");
    fyou = fday.getDay();
    //末日
        lday = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { lday[1]++; }

            //カレンダー表示
    document.write("<table border='2'>");
    document.write("<tr><th colspan='7'>" + year + "" + mon + "</th></tr>");
    document.write("<tr>");
    for (m = 0; m < 7; m++) {
        document.write("<th>" + youbi[m] + "</th>");
    }
    document.write("</tr>");
    for (n = 0; n < 6; n++) {
    document.write("<tr>");
    for (m = 0; m < 7; m++){
        document.write("<td>");
        d = (n*7+m+1-fyou);
        if (d > 0 && d <= lday[mon-1]) {document.write(d);} 
        else {document.write("&nbsp;");}
        document.write("</td>");
    }
    document.write("</tr>");
    if (d >= lday[mon-1]) break;
}
document.write("</table>"); 
</script>
        </div>
        </h3>
        </div>
    </div>

    <script src="https://cdn.auth0.com/js/auth0-spa-js/1.2/auth0-spa-js.production.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
        const app = new Vue({
            el: '#app',

            data: {
                login: false,
                auth0: {},
                APP_PATH: '/',
                userData: {}
            },

            methods: {
                async configureClient(){
                    const config = {
                        "domain": "", //Auth0の管理画面よりAuth0.comと記載のあるURL
                        "clientId": "" //Auth0の管理画面より
                    };
                    //Auth0オブジェクト生成
                    this.auth0 = await createAuth0Client({
                        domain: config.domain,
                        client_id: config.clientId
                    });
                },

                async updateUI(){
                    const isAuthenticated = await this.auth0.isAuthenticated();
                    if (isAuthenticated) {
                        this.login = true; //ログイン後の情報が表示
                        this.userData = await this.auth0.getUser();
                        this.userData.token = await this.auth0.getTokenSilently();
                    }
                },

                async auth0login(){
                    await this.auth0.loginWithRedirect({
                        redirect_uri: window.location.origin + this.APP_PATH
                    });
                },

                auth0logout(){
                    this.auth0.logout({
                        returnTo: window.location.origin + this.APP_PATH
                    });
                }
            },

            async mounted() {
                await this.configureClient();
                this.updateUI();
                const isAuthenticated = await this.auth0.isAuthenticated();    
                if (isAuthenticated) {
                    return;
                }

                // NEW - check for the code and state parameters
                const query = window.location.search;
                if (query.includes("code=") && query.includes("state=")) {

                    // Process the login state
                    await this.auth0.handleRedirectCallback();

                    this.updateUI();

                    // Use replaceState to redirect the user away and remove the querystring parameters
                    window.history.replaceState({}, document.title, this.APP_PATH);
                }
            },

        })
    </script>
  </body>
</html>

結果

image.png

感想

ログイン機能、デスクトップアプリ化、カレンダーの作成が何とかファイル1枚を工夫することで出来ました!自分のレベルにあったシンプルなファイルを使うと、改めて理解力も深まるなと実感。
これまでは方法をコピペするみたいな事ばかりですが、先人の知恵を借りつつ少しは工夫できるようになってきたのがうれしいでs。
単純にコードを繋げば思い通りに出力可能というわけではないと感じますが、知識の組み合わせでちょっとずつ進歩できると嬉しいです!地道なプログラミングの勉強もがんばろ~。

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