node.js Express - how to do login sessions?

Viewed 2321

I'm working doing a login function with node.js Express and are having trouble with sending the session data so my app.js routes know the user is allowed to enter the various sites.

My first thought was to send it when i approve of the login information and redirect to the frontpage in my Auth.js but i can't figure out how to send it so that my frontpage route can see it and handle it with my checkAuth function.

The other idea i had was using a couple of "set/get" routes as shown in my users.js. But can't figure out how i would further implement that.

I don't know which way would be optimal for this sort of application.

This is the Auth.js which is responsible for the login:

const router = require('express').Router();

const User = require("../models/User.js");

const bcrypt = require('bcrypt');
const saltRounds = 12;

router.post('/login', (req, res) => {
    // get request from body
    const { username, password } = req.body;
    //console.log(req.body);

    // ask if this is a username with a password
    if (username && password) {

        // goes through db to see if username exists 
        User.query().select('username').where('username', username).then(foundUsername => {
            try {
                if (foundUsername[0].username == username) {          
                    console.log(foundUsername[0].username);

                    User.query().select("password").where('username', foundUsername[0].username).then(foundPassword => {
                        console.log(foundPassword[0].password);

                        bcrypt.compare(password, foundPassword[0].password).then(result => {
                            console.log(result) 
                            if (result == true) {
                                // this is where i want to set the req.session.user_id = true;
                                // and send it to my /frontpage
                                return res.redirect("/frontpage");
                            } else {
                                return res.status(400).send({ response: "wrong username or password" });
                            };
                        });                        
                    });      
                } else {
                    return res.status(400).send({ response: "wrong username or password" });
                }; 
            } catch (error) {
                return res.status(400).send({ response: "wrong username or password" });
            };
        });
    };
});

module.exports = router;

This is my app.js which checks the incoming request for req.session.user_id

const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.json());


// You need to copy the config.template.json file and fill out your own secret
const session = require('express-session');
const config = require('./config/config.json');
app.use(session({
    secret: config.sessionSecret,
    resave: false,
    saveUninitialized: true
}));


const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
});

app.use(limiter);

const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 8 // limit each IP to 8 requests per windowMs
});

app.use('/signup', authLimiter);
app.use('/login', authLimiter);


/* Setup Knex with Objection */

const { Model } = require('objection');
const Knex = require('knex');
const knexfile = require('./knexfile.js');

const knex = Knex(knexfile.development);

Model.knex(knex);


app.get("/", (req, res) => {

    return res.sendFile(__dirname + "/public/login.html");
});

function checkAuth(req, res, next) {
    if (!req.session.user_id) {
      res.send('You are not authorized to view this page');
    } else {
      next();
    }
  }

app.get("/frontpage", checkAuth, (req, res) => {
    console.log(req.body);
    return res.sendFile(__dirname + "/public/frontpage.html");
});



const authRoute = require('./routes/auth.js');
const usersRoute = require('./routes/users.js');

app.use(authRoute);
app.use(usersRoute);

const PORT = 3000;

app.listen(PORT, (error) => {
    if (error) {
        console.log(error);
    }
    console.log("Server is running on the port", PORT);
})
});

This is my users.js. This is another way i thought of getting and setting my session value:

router.get('/setsessionvalue', (req, res) => {
    req.session.user_id = true;
    return res.send({ response: "OK" });
});

router.get('/getsessionvalue', (req, res) => {
    return res.send({ response: req.session.user_id });
});

0 Answers
Related