Search code examples
javascripthtmlgogo-templates

How to pass the value of a JavaScript variable to a golang function using HTML template


I have a GO web application that is using the HTML templating feature. I am attempting to encrypt the user's password before it is submitted in a form. The steps to accomplish this are:

  1. Use JavaScript to capture the raw value passed by the user in the input field
  2. Call the Go encrypt function provided the in the Go template which takes in a password parameter that returns an encrypted value.
  3. The newly encrypted value should then be forwarded as the new password value to the POST form value.

However as the listed steps are being executed the expected output is incorrect. Instead of encrypting the value of the input, it encrypts the variable name as shown below.

username: mass 
encrypted: ABZT7a7K+l7uMu2ZMq/K8ucyJKwdq0TVTmKlShBLo40iPeA3U2Pm9oTCCw==
decrypted:  ' + raw_val + '

So how do I get the JavaScript value passed into the encrypt function as opposed to the variable name being passed in? I am not very familiar with JavaScript, so either I am concatenating the strings incorrectly or I could be trying the impossible but I am not aware.

Below is the HTML source code I have in the template.

<!DOCTYPE html>
<html>
<head></head>
<title>Buy Bot</title>
<body>
  <form name="login" action="/login" method="POST" onsubmit="encrypt()">
    <div>
    <label for="username">username:</label>
    <input id="username" type="text" name="username" placeholder={{.KycInfo}} required>
    <div>
    </br>
    <div>
    <label for="password">password:</label>
    <input id="password" type="password" name="password" placeholder="password" required>
    </div>
    </br>
    <div>
      remember me <input id="rememberme" type="checkbox" name="rememberme">
    </div>
    </br>
    <div>
    <input type="submit" value="login">
    </div>
  </form>
</body>
</html>

<script  
  type="text/javascript">
  function encrypt(){
    var raw_val = document.getElementById("password").value
    console.log("password: ",raw_val)
    let encrypted = '{{.Encrypt "' + raw_val + '"}}'
    console.log("encrypted: ",encrypted)
    document.login.password.value = encrypted;
    return true;
  } 
</script>


Solution

  • You can't pass a JavaScript variable value to a Go function using a template (the template will be already generated on the client when assigning a value to the JavaScript variable).

    In a login form, you usually send the raw password value and encrypt/hash it server-side. You should already be securely sending the password by using SSL.