DEV Community

Cover image for How to add auth system to Express.js
orl0pl
orl0pl

Posted on

How to add auth system to Express.js

Sometimes you have great app idea, but you need to make authentication. Without further ado, I'll show you how to do it.

Part 1

Let's assume you have installed express and now you need to:

npm i body-parser cookie-parser
Enter fullscreen mode Exit fullscreen mode

Now you need to make file called accounts.json
Replace content of accounts.json file with this:

[
  {
    "name": "user",
    "password": "user",
    "data": "I'm user"
  },
  {
    "name": "user2",
    "password": "user2",
    "data": "I'm second user"
  },
  {
    "name": "user3",
    "password": "user3",
    "data": "I'm third *special* user"
  }
]
Enter fullscreen mode Exit fullscreen mode

⚠ This is only example. Storing unhashed passwords is dangerous. If you know how to use databases you can use database.

Part 2

Now you need to have accounts list in an object and have sessions array.
Add this lines below const app in your index.js

const accounts = require("accounts.json")
const sessions = {};
app.use(bodyParser.urlencoded());
app.use(cookieParser());

function randomSID() {
    var sID = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    if(!sessions.hasOwnProperty(sID)){
        return sID;
    }
    return randomSID();
  }
Enter fullscreen mode Exit fullscreen mode

Part 3

Create an /login API endpoints.

app.get('/login', (req,res)=>{
  res.send(`
<form type="post">
<input name="name">
<input name="password" type="password">
<button type="submint">Log In</button>
</form>
`)
})
app.post('/login', (req,res)=>{
  if(accounts.find(x=>x.name == req.body.name && x.password == req.body.password){
    const newSessionID = randomSID()
    res.cookie('sID', newSessionID)
    sessions[newSessionID] = accounts.findIndex(x => x.name === 
    body.name && x.password === body.password)
    res.redirect('/')
  }
  else {
  res.send("Bad password")  
  }
})
Enter fullscreen mode Exit fullscreen mode

Create logout API endpoint:

app.get('/logout', (req, res) => {
  delete loggedInSessions[req.cookies.sID]
  res.clearCookie('sID')
  res.redirect('/')
})
Enter fullscreen mode Exit fullscreen mode

Part 4

Create an account middleware

function accountMiddleware(req,res,next){
  if(accounts[sessions[req.cookies.sID]]){
    req.account = accounts[sessions[req.cookies.sID]]
  }
  else {
    req.account = null;
  }
  next()
}
Enter fullscreen mode Exit fullscreen mode

Also add this line next to app.use's.

app.use(accountMiddleware)
Enter fullscreen mode Exit fullscreen mode

Part 5

Now you can easily get account data using req.account.
Example endpoint:

app.get('/', (req, res) => {
  if(req.account){
    res.send(`You are logged in as ${req.account.name} and here is your data: ${req.account.data}`)
  }
  else {
    res.send("You are logged out")
  }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)