skip to Main Content

I have created a webpage and using postgresql as database. It works simply :-

  • register users name, email and password
  • login using registered email and password and then a welcome messege appears

Now, i added another button ‘forgot password’ button which redirects user to the forgot password page then, User enter the registered email and enters a new password which simply updates the old password.
here is the code


//this is server.js code which can be executed using npm start

const express =require('express');
const path=require ('path');
const bodyParser = require('body-parser');
const knex = require('knex');



const db=knex({
    client:'pg',
    connection:{
        host: '127.0.0.1',
        user:'postgres',
        password:'******',
        database:'loginform1'

    }
})


const app=express();

let initialPath=path.join(__dirname,"public");

app.use(bodyParser.json());
app.use(express.static(initialPath));

app.get('/',(req,res)=>{
    res.sendFile(path.join(initialPath,"index.html"));
})


app.get('/login',(req,res)=>{
    res.sendFile(path.join(initialPath,"login.html"));
})


app.get('/register',(req,res)=>{
    res.sendFile(path.join(initialPath,"register.html"));
})




app.post('/register-user',(req,res)=>{
    const {name, email, password } = req.body;


    if(!name.length || !email.length || !password.length){
        res.json('fill all the fields');

    }

    else{
        db("users").insert({
            name:name,
            email:email,
            password:password
        })
        .returning(["name", "email"])
        .then(data=>{
            res.json(data[0])
        })
        .catch(err =>{
            if(err.detail.includes('already exists')){
                res.json('email already exists');
            }
        })

    }


})




app.post('/login-user',(req,res)=>{
    const{email, password}=req.body;

    db.select('name','email')
    .from('users')
    .where({
        email:email,
        password:password
    })
    .then(data=>{
        if(data.length){
            res.json(data[0]);
        }else{
            res.json('email or password is incorrect');
        }
    })
})


app.listen(3000,(req,res)=>{
    console.log('lsitening on port 3000......')
})

Here the form.js which shows most of the errors

const form =[...document.querySelector('.form').children];

form.forEach((item,i)=>{
    setTimeout(()=>{
        item.style.opacity =1;
    }, i*100);
})

window.onload=()=>{
    if(sessionStorage.name){
        location.href ='/';
    }

}




//form validation

const name=document.querySelector('.name') || null;
const email=document.querySelector('.email');
const password=document.querySelector('.password')||null;
const submitBtn=document.querySelector('.submit-btn');
const reemail=document.querySelector('.reemail')||null;
const repassword=document.querySelector('.repassword')||null;


if(reemail==null && repassword==null){
    //means login page is open
    submitBtn.addEventListener('click',()=>{
        fetch('/login-user',{
            method : 'post',
            headers:new Headers({'Content-Type':'application/json'}),
            body:JSON.stringify({
                email:email.value,
                password:password.value
            })

        })
        .then(res=>res.json())
        .then(data=>{
            validateData(data);
        })


    })



}

//forgot password 
else if(name==null || password==null){

    submitBtn.addEventListener('click',()=>{
        fetch('/forgot-user',{
            method : 'post',
            headers:new Headers({'Content-Type':'application/json'}),
            body:JSON.stringify({
                
                password:repassword.value
            })

        })
        .then(res=>res.json())
        .then(data=>{
            validateData(data);
        })


    })




}








else{
    //means register page is open

    submitBtn.addEventListener('click',()=>{
        fetch('/register-user',{
            method:'post',
            headers: new Headers({'Content-Type':'application/json'}),
            body:JSON.stringify({
                name:name.value,
                email:email.value,
                password:password.value
            })
        })
        .then(res=>res.json())
        .then(data=>{
            validateData(data);
        })

    })


}

const validateData=(data)=>{
    if(!data.name){
        alertBox(data);
    }
    else{
        sessionStorage.name=data.name;
        sessionStorage.email=data.email;
        sessionStorage.password=data.password;
        sessionStorage.reemail=data.reemail;
        sessionStorage.repassword=data.repassword;

        location.href ='/';
    }
}

const alertBox =(data)=>{
    const alertContainer=document.querySelector('.alert-box');
    const alertMsg = document.querySelector('.alert-box');
    alertMsg.innerHTML =data;

    alertContainer.style.top = `5%`;
    setTimeout(()=>{
        alertContainer.style.top=null;
    },5000);
}

for more info plese look at the repo: Github

Error i’m facing: Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

I have tried everything i want to know how i can solve this error or you can suggest a better way to write code for updating password in postgresql server using knex.js. As i have already gave you guys all the insights do checkout and help me out.

2

Answers


  1. First, you have security flaw in this, with this implementation any one can change the password with email address.

    Solution to Error:

    event.preventDefault();
    

    Add this in your code & you are good to go.

    Code:

    //forgot password 
    else if(name==null || password==null){
        event.preventDefault();
        submitBtn.addEventListener('click',()=>{
            fetch('/forgot-user',{
                method : 'post',
                headers:new Headers({'Content-Type':'application/json'}),
                body:JSON.stringify({
                    
                    password:repassword.value
                })
    
            })
            .then(res=>res.json())
            .then(data=>{
                validateData(data);
            })
        })
    

    Tested it by cloning your repo & making changes.

    Login or Signup to reply.
  2. May I add another point to Huzaifa’s answer:

    Please hash the password so that it is not written in plain text in the DB, that is a security issue and we do bear responsibility against our customers to not mess around with their passwords lightly.

    const bcryptjs = require('bcryptjs');
    ...
    
    app.post('/register-user', async (req, res) => {
        const { name, email, password } = req.body;
    
        if(!name.length || !email.length || !password.length){
            res.json('fill all the fields');
        } else {
            const hashedPassword = await bcryptjs.hash(password, 10); // this hashes the password so it is not written in plain text in db. see below how to compare during login. The 10, is the number of saltrounds.
            db("users").insert({
                name,
                email,
                password: hashedPassword
            })
            .returning(["name", "email"])
            .then((data) => {
                res.json(data[0])
            })
            .catch((err) => {
                if(err.detail.includes('already exists')) {
                    res.json('email already exists');
                }
            })
        }
    })
    
    
    app.post('/login-user', async (req, res) => {
        const { email, password } = req.body;
    
        db.select('name','email', 'password')
        .from('users')
        .where({ email })
        .then(async (data) => {
            if(data.length) {
                const passwordsMatch = await bcrypt.compare(password, data[0].password);
                if (passwordsMatch) {
                   const { password, ...result } = data[0];
                   res.json(result);
                } else {
                    res.json('email or password is incorrect');
                }
            } else {
              res.json('email is incorrect');
            }
        })
    })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search