Create custom JWT login Last updated: 16. Jan 2024

How to implement a custom JWT login for your web application, encompassing the creation of a unique login page, the setup of an authentication endpoint, and integration with your user database for seamless and secure user management.

Create a login end point: #/API/Login.js

This section details the process of creating a /API/Login.js endpoint for user authentication in your web application. The provided code snippet includes essential validations such as checking for the presence of login credentials, verifying the format of the email, and ensuring the accuracy of the user's password through hashing. Upon successful validation, it generates a JWT containing user details, thereby completing the login process.

if (!query.login) docly.assert("Please specify your login");
if (!query.password) docly.assert("Please specify your password");

let login = query.login.trim().toLowerCase();
let pass = query.password;

if (!docly.isEmail(login)) {
    console.warn("Login failed! No such user - invalid email", login);
    docly.assert("Wrong username or password");
}

let user = docly.getFile("Users/" + login);
if (user == null) {
    console.warn("Login failed! No such user, file not found", login);
    docly.assert("Wrong username or password");
}

let hash = docly.MD5(docly.MD5(login + pass) + pass);
if (user.PasswordHash != hash && user.PasswordHash != pass) {
    console.warn("Login failed! Wrong password.", login, hash);
    docly.assert("Wrong username or password");
}


let jwt = {
    email : login,
    member : user.Member,
    name : user.Name,
    phone : user.Phone,
    image : user.Image
};

docly.writeJwt(jwt);

console.log("Login success", jwt);

return jwt;

Get current user: #/API/GetUser.js

This segment outlines the creation of the /API/GetUser.js endpoint, designed to retrieve the current user's information. It includes code for validating the presence of a JWT in the request and, if authenticated, returns the user details encoded in the JWT, ensuring secure and efficient access management.

if (request.Jwt == null)
    return docly.denyAccess();

return request.Jwt;

Create the following file: Login.hash

This section guides you through setting up the Login.hash file, which serves as the HTML template for the login page of your web application. It includes a detailed HTML structure featuring a user-friendly login form where users can enter their email and password. The form is equipped with a JavaScript function to handle the submission, sending the credentials to the /API/Login endpoint for authentication. This setup provides an intuitive and secure interface for user login.

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <section id="content">
        <h6>Login</h6>
        <p>Please log in with your email and password.</p>
        <form id="LoginForm" onsubmit="handleSubmit(event)">
            <label>Email</label>
            <input type="email" placeholder="Email" id="Login">
            <label>Password</label>
            <input type="password" placeholder="Password" id="Password">
            <button type="submit">Login</button>
            <a href="#" onclick="handleReset()">Forgot password?</a>
        </form>
    </section>

    <script>
        function handleSubmit(event) {
            event.preventDefault();
            let login = document.getElementById("Login").value;
            let pass = document.getElementById("Password").value;
            let url = `API/Login?login=${encodeURIComponent(login)}&password=${encodeURIComponent(pass)}`;

            fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => response.ok ? window.location.href = "~/": response.json())
            .then(data => data && data.Message && alert("Login failed", data.Message))
            .catch(error => alert("Login failed", error));
        }

        function handleReset() {
            // Implement reset password logic here
        }
    </script>
</body>
</html>