Tmirror

How to make a Secure login management System using Google AppScript with Google Spreadsheet ?


How to make a Secure login management System using Google AppScript with Google Spreadsheet ?

Learn how to create a secure login, logout, and user registration system using Google Apps Script. This comprehensive tutorial covers session management, login/logout functionality, user registration with duplicate checking, success and error messages, and automatic redirection after successful registration. Enhance your web app’s security and user experience today!

In this article, we have created a Secure Login System in which Session has been used which is completely secure, along with it we have also created Logout Functionality and we have also made it so that the user can register himself.

Demo Login System

SESSION MANAGEMENT

First of all, let me talk to you about Session Management, by using Session in Apps Script, we can store one or more values ​​from the Client Side at a place such as Apps Script which is executed on the Server Side. He was able to use it.

WHAT ARE THE BENEFITS OF USING SESSION IN APPS SCRIPT?

By using Session we can secure our page i.e. we can protect it from unauthorized access. In this Secure Login System, we have used Session to secure the login.

Create GOOGLE SHEET

First of all, create a Google Sheet, if you want, you can enter the ID and Password in it beforehand, and even if you don’t, when we create the User Registration Page, then if we enter from there, that shape will be stored on the Google Sheet.

LOGIN PAGE FOR SECURE LOGIN SYSTEM

This is the Login Page, from here we can enter the User ID and Password, validate it with Google Sheet and go to the Home Page. Also, if we want to do User Registration, then from here we can also go to the User Registration Page.

HTML CODE FOR SECURE LOGIN (login.html)

<!DOCTYPE html>
<html>

<head>
  <title>Login</title>
  <base target="_top">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
  </script>
  <script src="https://code.jquery.com/jquery-3.7.0.min.js"
    integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">

  <style>
    body {
      background-color:  rgba(58, 103, 177, 30%); //rgba(205, 180, 219, 30%);
    }

    .card {
      width: 400px;
      margin: auto;
      margin-top: 30px;
    }

    .input-group-text {
      width: 100px;
      display: inline-block;
    }

    .mycolor {
      background-color: #3a67b1; //#6d3b89;
    }

    .color {
      color: #3a67b1; //#6d3b89;
    }

    .img {
      width: 60px;
      margin: auto;
      display: inline-block;
    }
  </style>  <!-- Add CSS -->
  <script>
    function login() {
    var username = document.getElementById("uid").value;
    var password = document.getElementById("pass").value;
    
    google.script.run.withSuccessHandler(function(response) {
    
      if (response === "success") {
      document.getElementById("myid").click();
      } else {
        $("#RetMsg").removeClass("alert-danger").removeClass("alert-success").addClass("alert-danger");
        $("#RetMsg").html("Invalid User ID or Password");
        $("#RetMsg").show();
      }
      }).loginUser(username, password);
    }


  function ClearText()
  {
      $('#RetMsg').html("");
      $('#RetMsg').hide();
      $('#RetMsgReg').html("");
      $('#RetMsgReg').hide();
  }

  function OpenRegisterPage()
  {
        google.script.run.withSuccessHandler(ShowRegister).OpenPage("register");
  }

  function ShowRegister(data)
  {
    $('#DivLogin').hide();
    $('#DivRegister').html(data);
  }

  </script>  <!-- Add JS -->

</head>

<body>


  <div id="DivLogin" class="card shadow rounded-4 rounded ">

    <h5 class="card-header bg-secondary- text-white p-3 mycolor">Apps Script Secure Login</h5>
    <a style="display:none" id="myid" href="<?= myURL(); ?>" target="_top">Link</a>
    <div class="card-body p-4">

      <center>
        <i class="bi bi-person-circle fs-1 color"></i>
      </center>
      <br>

      <div class="input-group mb-3">
        <span class="input-group-text" >User</span>
        <input type="text" class="form-control" id="uid" required placeholder="User ID" onchange="ClearText()">
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text" >Password</span>
        <input type="password" class="form-control" id="pass" required placeholder="Password" onchange="ClearText()" >
      </div>
      <br>

      <div id="RetMsg" class="alert alert-danger " style="display:none" role="alert"> </div>




      <button type="button" onclick="login()"  class="btn btn-primary- mycolor float-end px-5 text-white" >Login</button>

      <span href="#"  onclick="OpenRegisterPage()">Register (New User)</a>
      

    </div>

    <form >
  </div>
  
  <div id="DivRegister"></div>
  
</body>

</html>

USER REGISTRATION Page

From this page we can register any new user. In this example, only those columns are taken which are necessary, if you want, you can take more columns also. We have also put some validations on this page.

If the Password and Re-enter Password are not the same, the following message will appear, this is done with JavaScript.

Password Not Matched

If the user is already registered then the message User Already Exists will appear.

User Already Exists

When the user passes all the validations, a message like this will be displayed.

User successfully login

HTML CODE FOR USER REGISTRATION (register.html)

<script>
  function Register()
  {
    
    var unm    = document.getElementById("reg_uname").value.trim();
    var uid    = document.getElementById("reg_uid").value.trim();
    var pass   = document.getElementById("reg_pass").value.trim();
    var repass = document.getElementById("reg_repass").value.trim();

    if (pass != repass)
    {
      RegReturnMsg("danger,Password Not Matched...");
    }
    else
    {
      google.script.run.withSuccessHandler(RegReturnMsg).UserRegister(uid,pass,unm);
    }
    
    
  }
  
  function RegReturnMsg(data)
  {
      let v = data.split(",");
      let type=v[0];

      $('#RetMsgReg').removeClass("alert-success").removeClass("alert-danger").addClass("alert-"+type);
      $('#RetMsgReg').html(v[1]);
      $('#RetMsgReg').show();

      if (type == 'success')
      {
        setTimeout(function(){  
           document.getElementById("myid").click();
           }, 3000);
      }

  }
</script> <!--  Add JS -->

<div class="card shadow rounded-4 rounded ">
  <h5 class="card-header bg-secondary- text-white p-3 mycolor">User Registration</h5>

  <div class="card-body p-4">


    <div id="RegBody">
      <div class="input-group mb-3">
        <span class="input-group-text" >User Name</span>
        <input type="text" class="form-control" id="reg_uname" placeholder="User Name" onchange="ClearText()">
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text" >User ID</span>
        <input type="text" class="form-control" id="reg_uid" placeholder="User ID" onchange="ClearText()">
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text" >Password</span>
        <input type="password" class="form-control" id="reg_pass" placeholder="Password" onchange="ClearText()" >
      </div>

      <div class="input-group mb-3">
        <span class="input-group-text" >Re-enter</span>
        <input type="password" class="form-control" id="reg_repass" placeholder="Re-enter Password" onchange="ClearText()" >
      </div>
    </div>

    <div id="RetMsgReg" class="alert alert-danger " style="display:none" role="alert"> </div>

    <button type="button" class="btn btn-primary- mycolor float-end px-5 text-white" onclick="Register()">Register</button>


  </div>
</div>

HOME PAGE

When the user logs in successfully, he will come to this page, it is completely secure because we have used Session in it. To exit the user from the session, we have used Logout, the functionality of which you will find on this page.

HTML CODE FOR HOME PAGE (MAIN.HTML)

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
  </script>

  <script src="https://code.jquery.com/jquery-3.7.0.min.js"
    integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">  

  <style>
    body {
      background-color:  rgba(58, 103, 177, 30%); //rgba(205, 180, 219, 30%);
    }

    .mycolor {
      background-color: #3a67b1;//#6d3b89;
    }

    .color {
      color: #3a67b1; //#6d3b89;
    }
 
  </style> <!-- Add CSS -->
  <script>
    
    function logout()
    {
      google.script.run.withSuccessHandler(AfterLogOut).logoutUser();
    }
    function AfterLogOut()
    {
         document.getElementById("myid").click();
    }

  </script>  <!-- Add JS -->
</head>

<body onload="">
   
  <button class="btn  float-end px-5 text-white" type="button" onclick="logout()">Log Out</button>
  <a style="display:none" id="myid" href="<?= myURL(); ?>" target="_top">Link</a>
  
  <h3 class="mycolor p-2 text-white">Imagination</h3>
  <br><br><br><br><br><br>
  <center>
    <h1>Welcome to Home Page</h1>
    </center>
</body>

</html>

APPS SCRIPT CODE

The code of Apps Script starts from here. All the screens and pages we have created so far communicate through this page. Therefore, on this page you will find functions related to all pages. You have to paste all the following codes in the code.gs file.

AppScript Code (code.gs)

let MySheets  = SpreadsheetApp.getActiveSpreadsheet();
let LoginSheet  = MySheets.getSheetByName("login");  
function doGet(e) {
  var output = HtmlService.createTemplateFromFile('login');
  
  var sess = getSession();
   if (sess.loggedIn) {
     output = HtmlService.createTemplateFromFile('main');
  }
  return output.evaluate();
}
function myURL() {
  return ScriptApp.getService().getUrl();
}
function setSession(session) {
  var sId   = Session.getTemporaryActiveUserKey();
  var uProp = PropertiesService.getUserProperties();
  uProp.setProperty(sId, JSON.stringify(session));
}
function getSession() {
  var sId   = Session.getTemporaryActiveUserKey();
  var uProp = PropertiesService.getUserProperties();
  var sData = uProp.getProperty(sId);
  return sData ? JSON.parse(sData) : { loggedIn: false };
}
function loginUser(pUID, pPassword) {
    
    if (loginCheck(pUID, pPassword)) {
      
      var sess = getSession();
      sess.loggedIn = true;
      setSession(sess);

        return 'success';
    } 
    else {
        return 'failure';
    }
}
function logoutUser() {
  var sess = getSession();
  sess.loggedIn = false;
  setSession(sess);
}
function loginCheck(pUID, pPassword) {
  let LoginPass =  false;
      let ReturnData = LoginSheet.getRange("A:A").createTextFinder(pUID).matchEntireCell(true).findAll();
        
        ReturnData.forEach(function (range) {
          let StartRow = range.getRow();
          let TmpPass = LoginSheet.getRange(StartRow, 2).getValue();
          if (TmpPass == pPassword)
          {
              LoginPass = true;
          }
        });

    return LoginPass;
}
function OpenPage(PageName)
{
    return HtmlService.createHtmlOutputFromFile(PageName).getContent();
}
function UserRegister(pUID, pPassword, pName) {
    
    let RetMsg = '';
    let ReturnData = LoginSheet.getRange("A:A").createTextFinder(pUID).matchEntireCell(true).findAll();
    let StartRow = 0;
    ReturnData.forEach(function (range) {
      StartRow = range.getRow();
    });

    if (StartRow > 0) 
    {
      RetMsg = 'danger, User Already Exists';
    }
    else
    {
      LoginSheet.appendRow([pUID, pPassword, pName]) ;  
      RetMsg = 'success, User Successfully Registered'; 
    }

    return  RetMsg;
}

DEPLOY CODE

After this you have to deploy the project and execute it by clicking the link that comes after deployment.

To learn deployment, you can take help of the following article.

Click Here : https://tmirror.co/how-to-deploy-code-google-appscript/

I hope you have understood the Secure Login System very well. If you have any query related to this Secure Login Article, you can comment to me without any hesitation. Don’t forget to comment how you liked this article. Thank you for giving your valuable time.

comments powered by Disqus