Aniket More
code with aniket

code with aniket

Node.js session authentication in one file

Aniket More's photo
Aniket More
·Jun 16, 2022·

2 min read

Below is one file that shows how to do session authentication in node.js and express with a minimal example. The only dependencies on the project are express and dotenv

index.js


require("dotenv").config();
const express = require("express");
const session = require("express-session");

const PORT = process.env.PORT || 8080;
const NODE_ENV = process.env.NODE_ENV || "development";
const SECRET_KEY = process.env.SECRET_KEY || "secret_key";

//user data and methods
const users = [
  {
    id: 1,
    username: "john",
    password: "password",
  },
  {
    id: 2,
    username: "jane",
    password: "password",
  },
];

function getUserById(id) {
  return users.find((user) => user.id === id);
}

function getUserByUsername(username) {
  return users.find((user) => user.username === username);
}

//middleware
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
  session({
    resave: true,
    saveUninitialized: true,
    secret: SECRET_KEY,
  })
);

//authentication middleware (used to populate req.user object if user is logged in other wise req.user is null)
app.use((req, res, next) => {
  const id = req.session.userId;
  if (id) {
    req.user = getUserById(id);
  } else {
    req.user = null;
  }
  next();
});

const router = express.Router();

router.get("/", (req, res) => {
  const user = req.user;
  const html = `
    <h1>hello world</h1>
    ${(() => {
      if (user) {
        return `<p>you are logged in as ${user.username}</p>`;
      }
      return `<p>you are not logged in</p>`;
    })()}
    ${(() => {
      if (user) {
        return `<a href="/logout">logout</a>`;
      }
      return `<a href="/login">login</a>`;
    })()}
  `;
  res.send(html);
});

router.get("/login", (req, res) => {
  const html = `
    <form action="/login" method="post">
      <input type="text" name="username" placeholder="username">
      <input type="password" name="password" placeholder="password">
      <button type="submit">login</button>
    </form>
  `;
  res.send(html);
});

router.post("/login", (req, res) => {
  const { username, password } = req.body;
  const user = getUserByUsername(username);
  if (user && user.password === password) {
    req.session.userId = user.id;
    res.redirect("/");
  } else {
    res.redirect("/login");
  }
});

router.get("/logout", (req, res) => {
  req.session.destroy();
  res.redirect("/");
});

app.use("/", router);

function main() {
  app.listen(PORT, () => {
    console.log(`Example app listening on port http://localhost:${PORT}`);
  });
}

//run the app
main();
 
Share this