1

I have an express server and want to build a website with an authentication form. I was using mongodb, and everything was going well. But when I came to the final part i.e. authenticating and redirecting the user to their respective URL's, I hit the problem: It tells that the user enters invalid credentials even when they were right. Here's my HTML:

<!DOCTYPE html>
<html>
<head>
    <title> PAL - Play and Learn | Login & Signup page </title>
</head>
<body>
<div class="container" id="container">
    <div class="form-container sign-up-container">
        <form method="post" action="signup">
            <h1>Create Account</h1><br>
            <span>or use your email for registration</span><br>
            <input type="text" id="signupUsername" placeholder="Username" />
            <input type="email" id="signupEmail" placeholder="Email" />
            <input type="password" id="signupPassword" placeholder="Password" />
            <input type="number" id="signupAge" placeholder="Age" />
            <label for="">Date of Birth</label>
            <input type="date" id="signupDOB">
            <button id="signupCont" type="submit">Sign Up</button>
        </form>
    </div>
    <div class="form-container sign-in-container">
        <form method="post" action="login">
            <h1>Sign in</h1><br>
            <span>or use your account</span><br>
            <input type="text" id="loginUsername" name="loginUser" placeholder="Username" />
            <input type="password" id="loginPassword" name="loginPass" placeholder="Password" />
            <button id="loginCont" type="submit">Sign In</button>
        </form>
    </div>
    <div class="overlay-container">
        <div class="overlay">
            <div class="overlay-panel overlay-left">
                <h1>Welcome Back!</h1>
                <p>Already created an account? Click here to login to your account!</p>
                <button class="ghost" id="signIn">Sign In</button>
            </div>
            <div class="overlay-panel overlay-right">
                <h1>Hello, Friend!</h1>
                <p>Don't have an account? Don't worry! Click here to create one.</p>
                <button class="ghost" id="signUp">Sign Up</button>
            </div>
        </div>
    </div>
</div>
</body>
<style>
@import url('https://fonts.googleapis.com/css?family=Quicksand:400,800');

* {
    box-sizing: border-box;
    font-family: 'Quicksand', sans-serif;
}

body {
    background: #f6f5f7;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 100vh;
    margin: -20px 0 50px;
}

h1 {
    font-weight: bold;
    margin: 0;
}

h2 {
    text-align: center;
}

p {
    font-size: 14px;
    font-weight: 100;
    line-height: 20px;
    letter-spacing: 0.5px;
    margin: 20px 0 30px;
}

span {
    font-size: 12px;
}

a {
    color: #333;
    font-size: 14px;
    text-decoration: none;
    margin: 15px 0;
}

button {
    border-radius: 20px;
    border: 1px solid #FF4B2B;
    background-color: #FF4B2B;
    color: #FFFFFF;
    font-size: 12px;
    font-weight: bold;
    padding: 12px 45px;
    letter-spacing: 1px;
    text-transform: uppercase;
    transition: transform 80ms ease-in;
}

button:active {
    transform: scale(0.95);
}

button:focus {
    outline: none;
}

button.ghost {
    background-color: transparent;
    border-color: #FFFFFF;
}

form {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 50px;
    height: 100%;
    text-align: center;
}

input {
    background-color: #eee;
    border: none;
    padding: 12px 15px;
    margin: 8px 0;
    width: 100%;
}

.container {
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 14px 28px rgba(0,0,0,0.25), 
            0 10px 10px rgba(0,0,0,0.22);
    position: relative;
    overflow: hidden;
    width: 768px;
    max-width: 100%;
    min-height: 480px;
}

.form-container {
    position: absolute;
    top: 0;
    height: 100%;
    transition: all 0.6s ease-in-out;
}

.sign-in-container {
    left: 0;
    width: 50%;
    z-index: 2;
}

.container.right-panel-active .sign-in-container {
    transform: translateX(100%);
}

.sign-up-container {
    left: 0;
    width: 50%;
    opacity: 0;
    z-index: 1;
}

.container.right-panel-active .sign-up-container {
    transform: translateX(100%);
    opacity: 1;
    z-index: 5;
    animation: show 0.6s;
}

@keyframes show {
    0%, 49.99% {
        opacity: 0;
        z-index: 1;
    }
    
    50%, 100% {
        opacity: 1;
        z-index: 5;
    }
}

.overlay-container {
    position: absolute;
    top: 0;
    left: 50%;
    width: 50%;
    height: 100%;
    overflow: hidden;
    transition: transform 0.6s ease-in-out;
    z-index: 100;
}

.container.right-panel-active .overlay-container{
    transform: translateX(-100%);
}

.overlay {
    background: #FF416C;
    background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);
    background: linear-gradient(to right, #FF4B2B, #FF416C);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0 0;
    color: #FFFFFF;
    position: relative;
    left: -100%;
    height: 100%;
    width: 200%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
    transform: translateX(50%);
}

.overlay-panel {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 40px;
    text-align: center;
    top: 0;
    height: 100%;
    width: 50%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

.overlay-left {
    transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
    transform: translateX(0);
}

.overlay-right {
    right: 0;
    transform: translateX(0);
}

.container.right-panel-active .overlay-right {
    transform: translateX(20%);
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
const container = document.getElementById('container');
const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');

const loginUser = document.getElementById("loginUsername");
const loginPass = document.getElementById("loginPassword");
const loginCont = document.getElementById("loginCont");

const signupUser = document.getElementById("signupUsername");
const signupEmail = document.getElementById("signupEmail");
const signupPass = document.getElementById("signupPassword");
const signupAge = document.getElementById("signupAge");
const signupDOB = document.getElementById("signupDOB");
const signupCont = document.getElementById("signupCont");

signUpButton.addEventListener('click', () => {
    container.classList.add("right-panel-active");
});

signInButton.addEventListener('click', () => {
    container.classList.remove("right-panel-active");
});

loginCont.addEventListener("click", () => {
    
});

signupCont.addEventListener("click", () => {
    
});
</script>
</html>

And here's my server-side code:

var express = require('express');
var app = express();
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser')
app. use( bodyParser.json() );
app.use(bodyParser.urlencoded({ extended: true })); 

var mongo_profiles_url = 'mongodb+srv://signup:vesh2021@raspberry-target.7qt1j.mongodb.net/user-profiles?retryWrites=true&w=majority';

async function createDocument(db, db_name, clction, obj) {
  var dbo = db.db(db_name);
  dbo.collection(clction).insertOne(obj, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
}

app.get('/', function (req, res) {
  fs.readFile('./login-signup.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(data)
  });
});

app.post('/login', function (req, res) {
  var inuser = req.body.loginUser;
      inpass = req.body.loginPass;

  var myobj = { "user": inuser, "pass": inpass };
  console.log(`Login credentials: ` + JSON.stringify(myobj));

  MongoClient.connect(mongo_profiles_url).then(function(db, err) {
    if (err) throw err;
    
    var dbo = db.db("PAL");
    ob = dbo.collection("user-profiles").find(myobj).toArray();

    console.log(ob);

    if (ob.length > 0) {
      fs.readFile('./home.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data)
      });
    } else {
      console.log("Incorrect credentials given.")
    }
  });
});

app.listen(1000, function () {
    console.log("Server listening to http://localhost:1000");
});

For more info, I've creates both the files in the same folder.

Here's a snapshot my VSCode console:

I have found out that the response given by mongodb is a promise and isn't being converted to an array so that I could authenticate properly. I've googled a lot about this, with 0% chance of success. Hope someone could help.

Thanks in advance!

rioV8
  • 24,506
  • 3
  • 32
  • 49
viewy
  • 27
  • 7
  • Are you sure you're connected to the database? Have you tried console.logging something from there? – Raphael Morgan Dec 02 '21 at 16:41
  • Your lookup via the find operation in the db is returning a Promise which is still pending so when you compare `ob.length > 0' it's evaluating to false, so the else always executes. Have a look at how to handle [asynchronous javascript](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Brian Dec 02 '21 at 21:32

1 Answers1

1

You are retrieving data from the MongoDB database's collection through find and when you are doing so, you will need to use a callback function with it or a promise handler.

You need to add a promise handler (.then) or a callback function with this statement: ob = dbo.collection("user-profiles").find(myobj).toArray();

In the same way you used with mongodb connection statement: MongoClient.connect(mongo_profiles_url).then(function(db, err) {

Here's some information from the official website:

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback. A query also has a .then() function and thus can be used as a promise.

Hope this makes clear and solves the problem you are stuck in.

Daniyal Malik
  • 578
  • 2
  • 6
  • 15