0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【個人開発】WEBサービスのログイン機能をAWS Cognitoで実装する②

Last updated at Posted at 2023-03-02

はじめに

本記事は以下の続きの記事となっております。
https://qiita.com/rihib/items/e5bbd522c96925102dba

Signup検証機能画面(html)

activation.html
<!doctype html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <!-- viewport meta -->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Required bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Required cognito -->
    <script src="js/cognito/jsbn.js"></script>
    <script src="js/cognito/jsbn2.js"></script>
    <script src="js/cognito/sjcl.js"></script>
    <script src="js/cognito/aws-sdk.min.js"></script>
    <script src="js/cognito/aws-cognito-sdk.min.js"></script>
    <script src="js/cognito/amazon-cognito-identity.min.js"></script>
    <!-- Required jquery -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <!-- Required js/css -->
    <script src="js/activation.js"></script>
  </head>
  <body>
    <div>
      <!-- サインインフォーム -->
      <div id="activation" class="container-fluid w-75 p-3">
        <h1>Activation</h1>
        <div id="message"><span style="color: red;"></span></div>
            <form name="form-activation">
                <br><div class="row mb-3">
                <label class="col-sm-2 col-form-label">User ID</label>
                <div class="col-sm-10">
                    <input class="form-control" id="username" placeholder="User ID">
                </div>
                </div>
                <br><div class="row mb-3">
                <label for="inputPassword3" class="col-sm-2 col-form-label">Activation Key</label>
                <div class="col-sm-10">
                    <input class="form-control" id="activationKey" placeholder="Activation Key">
                    <div>
                        <small>※登録メールアドレスに送付された検証コードを入力ください</small>
                    </div>
                </div>
                </div>
                <br>
                <button type="button" class="btn btn-primary" id="activationButton">Activation</button>
            </form>
        </div>
      </div>
    </div>
  </body>
</html>

Signup検証機能ロジック(JavaScript)

activation.js
// ユーザープールの設定
var user_pool_id = "{USER_POOL_ID}"
var client_id = "{CLIENT_ID}"
const poolData = {
  UserPoolId : user_pool_id,
  ClientId : client_id
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

/**
* 画面読み込み時の処理
*/
$(function() {
    // 「Activate」ボタン押下時
    $("#activationButton").click(function(event) {
        activate();
    });
});

// アクティベーション処理
var activate = function() {

  //エラーメッセージ初期化
  $("div#message span").empty();

  var username = $("#username").val();
  var activationKey = $("#activationKey").val();
  
  // 何か1つでも未入力の項目がある場合、処理を中断
  if (!username | !activationKey) {
    $("div#message span").append("項目に入力漏れがあります");
    return false;
  } 

  var userData = {
      Username : username,
      Pool : userPool
  };
  var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
  
  // アクティベーション処理
  cognitoUser.confirmRegistration(activationKey, true, function(err, result){
      if (err) {
          // アクティベーション失敗の場合、エラーメッセージを画面に表示
          if (err.message != null) {
              if (err.massage == "Invalid verification code provided, please try again.") {
                $("div#message span").append("入力が正しくありません");
              } else {
                $("div#message span").append(err.message);
              }
          }
      } else {
        window.location.href = './index.html';
      }
  });
};

Signin画面(html)

signin.html
<!doctype html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <!-- viewport meta -->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Required bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Required cognito -->
    <script src="js/cognito/jsbn.js"></script>
    <script src="js/cognito/jsbn2.js"></script>
    <script src="js/cognito/sjcl.js"></script>
    <script src="js/cognito/aws-sdk.min.js"></script>
    <script src="js/cognito/aws-cognito-sdk.min.js"></script>
    <script src="js/cognito/amazon-cognito-identity.min.js"></script>
    <!-- Required jquery -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <!-- Required js/css -->
    <link rel="stylesheet" href="css/score.css">
    <script src="js/signin.js"></script>
  </head>
  <body>
    <div>
      <div>
        <div class="container-fluid w-75 p-3">
          <div class="d-flex justify-content-end" id="signinup">
            <a class="d-flex text-black-50 fs-6" href="./signup.html">会員登録</a>&emsp;<a class="d-flex text-black-50 fs-6" href="./user.html">トップページ</a>
          </div>
        </div>
      </div>
      <!-- サインインフォーム -->
      <div id="signin" class="container-fluid w-75 p-3">
        <h1>Sign In</h1>
        <div id="message"><span style="color: red;"></span></div>
            <form name="form-signin">
                <br><div class="row mb-3">
                <label class="col-sm-2 col-form-label">User ID</label>
                <div class="col-sm-10">
                    <input class="form-control" id="username" required>
                </div>
                </div>
                <br><div class="row mb-3">
                <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="password" required>
                </div>
                </div>
                <br>
                <button type="button" class="btn btn-primary" id="signinButton">Sign in</button>
            </form>
        </div>
      </div>
    </div>
  </body>
</html>

Signinロジック(JavaScript)

signin.js
// ユーザープールの設定
var user_pool_id = "{USER_POOL_ID}"
var client_id = "{CLIENT_ID}"
const poolData = {
  UserPoolId : user_pool_id,
  ClientId : client_id
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

// サインイン処理
var signIn = function() {
  var username = $('#username').val();
  var password = $('#password').val();
  
  // 何か1つでも未入力の項目がある場合、メッセージを表示して処理を中断
  if (!username | !password) { 
    $("#signin div#message span").empty();
    $("#signin div#message span").append("項目に入力漏れがあります");
    return false; 
  }
  
  // 認証データの作成
  var authenticationData = {
      Username: username,
      Password: password
  };
  var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
  
  var userData = {
      Username: username,
      Pool: userPool
  };
  var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
  
  // 認証処理
  cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: function (result) {
          var idToken = result.getIdToken().getJwtToken();          // IDトークン
          var accessToken = result.getAccessToken().getJwtToken();  // アクセストークン
          var refreshToken = result.getRefreshToken().getToken();   // 更新トークン
          
          console.log("idToken : " + idToken);
          console.log("accessToken : " + accessToken);
          console.log("refreshToken : " + refreshToken);
          
          window.location.href = './index.html';
      },
      onFailure: function(err) {
          // サインイン失敗の場合、エラーメッセージを画面に表示
          console.log(err);
          $("div#message span").empty();
          if (err.message == "Password attempts exceeded") {
            $("div#message span").append("パスワードを試行回数を超えました");
          } else if (err.message == "Incorrect username or password.") {
            $("div#message span").append("入力が正しくありません");
          };
      }
  });
};

参考

おまけ

本記事の機能は以下のサービスで利用されています。
気になった方は、お気軽にサービスも利用くださると大変嬉しいです。

観た映画を登録、管理できるサービス MyMovie

映画一覧.png

サービスURL : mymovie.jp
GitHub : github.com/hamasakiharuya/mymovie

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?