Login / Regisration HELP!

I have put together a login / registration web app with React, Express, Node and PostgreSQL. I think i have my backend connected to PostgreSQL pgAdmin 4 but i am having trouble getting my login and regisration posts working correctly with Postman/ Insomnia. I am also using Sequelize / Redux.

auth.controller.js

const db = require("../server/models");
const config = require("../config/auth.config");
const User = db.userLogin;
//const Role = db.userRoles;

//const Op = db.Sequelize.Op;

var jwt = require("jsonwebtoken");
var bcrypt = require("bcrypt");

exports.signUp = (req, res) => {
    // user being added to the db
    User.create({
        userName: req.body.userName,
        password: bcrypt.hashSync(req.body.password, 8),
        userEmail: req.body.userEmail,
        userFirstName: req.body.userFirstName,
        userSurname: req.body.userSurname,
    })
        // set user role to 1 to get basic user access on sign up
        .then(user => {
            user.set(user.userRole[1]).then(() => {
                res.send({ message: "User registered."});
                });
            })
        .catch(err => {
            res.status(500).send({ message: err.message });
        });
};

exports.signIn = (req, res) => {
    User.findOne({
        where: {
            // checks login input to stored details
            userName: req.body.userName
        }
        })
        .then(user => {
            if (!user) {
                return res.status(404).send({ message: "User not registered."});
            }
            var passwordIsValid = bcrypt.compareSync(
                req.body.password,
                user.password
            );
            if (!passwordIsValid) {
                return res.status(401).send({
                    accessToken: null,
                    message: "Incorrect password"
                });
            }
            var token = jwt.sign({ id: user.userID }, config.secretKey, {
                expiresIn: 86400
            });

            var permissions = [];
            user.get(user.userRole).then(userRole => {
                permissions.push(userRole);
            })

            res.status(200).send({
                userID: user.userID,
                userName: user.userName,
                userEmail: user.userEmail,
                userRoles: permissions,
                accessToken: token
            });
        })
        .catch(err => {
            res.status(500).send({ message: err.message});
        });
};
// controllers interact with PostgreSQL db via sequelize and send
// HTTP res (token, user info etc) to client

authJWT.js

const jwt = require("jsonwebtoken");
const config = require("../config/auth.config");
const db = require("../server/models");
const User = db.userLogin;

verifyToken = (req, res, next) => {
    let token = req.headers["x-access-token"];

    if (!token){
        return res.status(403).send({
            message: "No token returned"
        });
    }

    jwt.verify(token, config.secretKey, (err, decoded) => {
        if (err) {
            return res.status(401).send({
                message: "You're not authorised"
            });
        }
            req.userID = decoded.id;
            next(); // stops execution
        });
    };


// check registered user access level
isRegUser = (req, res, next) => {
    User.findByPK(req.userID).then(user => {
        user.get(user.userRole).then(userRole => {
            for (let i = 0; i < userRole.length; i++) {
                if (userRole[i].name === "1") {
                    next();
                    return;
                }
            }
            res.status(403).send({
                message: "Requires registered user status"
            });
        });
    });
};

// scuba school access level
// find by primary key
    isSchool = (req, res, next) => {
        User.findByPK(req.userID).then(user => {
            user.get(user.userRole).then(userRole => {
                    for (let i = 0; i < userRole.length; i++) {
                        if (userRole[i].name === "2") {
                            next();
                            return;
                        }
                    }
                    res.status(403).send({
                        message: "Requires school access"
                    });
                });
            });
    };


 // site admin access level
isSiteAdmin = (req, res, next) => {
    User.findByPK(req.userID).then(user => {
        user.get(user.userRole).then(userRole => {
                for (let i = 0; i < userRole.length; i++) {
                    if (userRole[i].name === "3") {
                        next();
                        return;
                    }
                }
                res.status(403).send({
                    message: "Requires site admin access"
                });
            });
        });
};

// access for everything (testing)
isSuperUser = (req, res, next) => {
    // Seq method that finds by primary key
    User.findByPK(req.userID).then(user => {
        user.get(user.userRole).then(userRole => {
                for (let i = 0; i < userRole.length; i++) {
                    if (userRole[i].name === "4") {
                        next();
                        return;
                    }
                }
                res.status(403).send({
                    message: "NO ENTRY"
                });
            });
        });
};

const authJWT = {
    verifyToken: verifyToken,
    isRegUser: isRegUser,
    isSchool: isSchool,
    isSiteAdmin: isSiteAdmin,
    isSuperUser: isSuperUser
};
module.exports = authJWT;

As the postman queries are timing out and not giving error messages i assume it is a problem with my backend rather than my frontend. Any advice would be much appreciated.

An example below is the json i am posting to the signUp api for new users. The method above should automatically assign new users the userRole 1 by default.

{
“userName”: “AdamBell”,
“password”: “bell1”,
“userEmail”: “adamBell@hotmail.com”,
“userFirstName”: “Adam”,
“userSurname”: “Bell”
}

I have the same problem with the signIn api where the timer just starts and keeps going when i try to post.

Whats the error message? Any screenshot of the error message? And when does it happen?

When i trying to test the API’s using insomnia the timer of my requests just keeps going up. My database / backend is running and when i try to post from the front end login / registration screen it does the same thing.

I included an example above of the json i am trying to post.

I think this is the timeline of events …

  • Preparing request to http://localhost:5000/api/auth/signup
  • Current time is 2020-12-20T14:47:37.228Z
  • Using libcurl/7.69.1-DEV OpenSSL/1.1.1d zlib/1.2.11 WinIDN libssh2/1.9.0_DEV nghttp2/1.40.0
  • Using default HTTP version
  • Disable timeout
  • Enable automatic URL encoding
  • Enable SSL validation
  • Enable cookie sending with jar of 0 cookies
  • Trying ::1:5000…
  • Connected to localhost (::1) port 5000 (#16)

POST /api/auth/signup HTTP/1.1
Host: localhost:5000
User-Agent: insomnia/2020.5.2
Content-Type: application/json
Accept: /
Content-Length: 140

| {
| “userName”: “AdamBell”,
| “password”: “bell1”,
| “userEmail”: “adamBell@hotmail.com”,
| “userFirstName”: “Adam”,
| “userSurname”: “Bell”
| }

  • upload completely sent off: 140 out of 140 bytes

You should try catching your errors or exceptions some of the blocks you forgot and use a debugger like ndb so you can check every step of the code. You will have a hard time pointing out whats happening. Usually when its timing out the cause is you forgot to next() in every middleware, or you forgot to trim the process.env variable process.env.samplevar.trim() and lack ram on your pc usually happens on mongodb.

Just try checking the login handler first using ndb debugger put some breakpoints on the part that you think is the cause.

can someone look at my post. Im stuck with my code

Cheers. I just noticed this error message in the developer options debugger:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/auth/signUp. (Reason: CORS request did not succeed)

Would this mean there wasn’t any matched routes? or a firewall issue?

I think you need to download cors module to your express backend.
That usually happens when your frontend and backend have different port or url. Call it app.use(cors())