Home > Mobile >  Login Authentification: No response from Rest API after Post Request
Login Authentification: No response from Rest API after Post Request

Time:02-28

I recently switched from php development to Javascript (I'm really amazed by the performance and possibilities).

Currently I try to create a simple authentification function (Username,hashed Password checked to mariadb Database)

After following some tutorials I managed to create the following structure:

But when I try to test the API via Postman and Insomnia I just get no response. Not even an Error Code. Just going on forever, just like an infinite Loop?

I'm thankful for any tip as I'm new to this. Thanks in advance.

My Stack: React, Nodejs, Mariadb, Express & Jwt / bcryptjs

My Express Router router.js:

    router.post('/login', (req, res, next) => {
    pool.query(
        `SELECT * FROM TABLE WHERE username = ${pool.escape(req.body.username)};`,
        (err, result) => {
            // user does not exists
            if (err) {
                throw err;
                return res.status(400).send({
                    msg: err
                });
            }
            if (!result.length) {
                return res.status(401).send({
                    msg: 'Username or password is incorrect!'
                });
            }
            // check password
            bcrypt.compare(
                req.body.password,
                result[0]['password'],
                (bErr, bResult) => {
                    // wrong password
                    if (bErr) {

                        throw bErr;
                    }
                    if (bResult) {
                        const token = jwt.sign({
                            username: result[0].username,
                            userId: result[0].id
                        },
                            process.env.API_SecretKey, {
                            expiresIn: '2h'
                        }
                        );
                        return res.status(200).send({
                            msg: 'Logged in!',
                            token,
                            user: result[0]
                        });
                    }
                    return res.status(401).send({
                        msg: 'Username or password is incorrect!'
                    });
                }
            );
        }
    );
});
router.post('/sign-up', userMiddleware.validateRegister, (req, res, next) => {
    pool.query(
        `SELECT * FROM TABLE WHERE LOWER(username) = LOWER(${pool.escape(
            req.body.username
        )});`,
        (err, result) => {
            if (result.length) {
                return res.status(409).send({
                    msg: 'This username is already in use!'
                });
            } else {
                // username is available
                bcrypt.hash(req.body.password, 10, (err, hash) => {
                    if (err) {
                        return res.status(500).send({
                            msg: err
                        });
                    } else {
                        // has hashed pw => add to database
                        pool.query(
                            `INSERT INTO TABLE (SecurityID, userPassword, username, userOTP) VALUES ('${pool.escape}', ${pool.escape(
                                req.body.SecurityID,
                                req.body.username,
                                req.body.password,
                                req.body.userOTP
                            )}, ${pool.escape(hash)}, now())`,
                            (err, result) => {
                                if (err) {
                                    throw err;
                                    return res.status(400).send({
                                        msg: err
                                    });
                                }
                                return res.status(201).send({
                                    msg: 'Registered!'
                                });
                            }
                        );
                    }
                });
            }
        }
    );

    pool.end;
});

router.get('/secret-route', userMiddleware.isLoggedIn, (req, res, next) => {
    console.log(req.userData);
    res.send('This is the secret content. Only logged in users can see that!');
});
module.exports = router;

My Middleware users.js

    module.exports = {
        validateRegister: (req, res, next) => {
            // username min length 3
            if (!req.body.username || req.body.username.length < 3) {
                return res.status(400).send({
                    msg: 'Passwort:'   req.body.username   'Please enter a username with at least 3 chars',
                    
                });
            }
            // password min 6 chars
            if (!req.body.password || req.body.password.length < 6) {
                return res.status(400).send({
                    
                    msg: 'Passwort:'   req.body.password   'Please enter a password with at least 6 chars'
                });
            }
            // password (repeat) does not match
            if (
                !req.body.password_repeat ||
                req.body.password != req.body.password_repeat
            ) {
                return res.status(400).send({
                    msg: 'Both passwords must match'
                });
            }
            next();
        },
    
    
        isLoggedIn: (req, res, next) => {
            try {
                const token = req.headers.authorization.split(' ')[1];
                const decoded = jwt.verify(
                    token,
                    process.env.API_SecretKey
                );
                req.userData = decoded;
                next();
            } catch (err) {
                return res.status(401).send({
                    msg: 'Your session is not valid!'
                });
            }
        }
    };

My index.js:

const express = require("express");
const DigitalMangement = express();
const cors = require('cors');

require("dotenv").config();
DigitalMangement.use(cors());
DigitalMangement.use(express.json());


// add routes
const router = require('./Routes/router.js');
DigitalMangement.use("/api", router);


DigitalMangement.listen(process.env.Application_Port, () => {
    console.log("Server is running on Port "   process.env.Application_Port)
});

CodePudding user response:

I haven't reviewed the whole code but, if you throw the error the code block will not continue. In this case, it won't be logged or sent as a response. Try removing the throw err line and rerun the code.

if (err) {
    throw err; //! here
    return res.status(400).send({
        msg: err
    });
}

CodePudding user response:

Thanks for all the help fellow Coders:

It seems to be that the import "mariadb" isn't 100% correct in this situation. I changed it to "mariadb/callback" and it started to work.

The mariadb libary returns Promises and mariadb/callback allows callbacks.

  • Related