DEV Community

Discussion on: How to create a session / login with ejs ?

Collapse
 
nicolasparada profile image
Nicolás Parada • Edited

Normally, first you check the credentials, then you create a JWT and return it (you can set a cookie for it).

const bodyParser = require('body-parser')
const express = require('express')
const jsonwebtoken = require('jsonwebtoken')

const withBody = bodyParser.json()
const jwtKey = process.env['JWT_KEY'] || 'shared-secret'

const app = express()

app.post('/api/login', withBody, (req, res) => {
  const userId = 1 /* Get credentials somehow */
  const jwt = jsonwebtoken.sign({ sub: userId }, jwtKey)
  res.coookie('jwt', jwt)
  res.json({ jwt })
})

Then in each endpoint you require auth, you get that token, parse and validate to get it content (claims).

const cookieParser = require('cookie-parser')

const withAuthUserId = [
  cookieParser(),
  (req, res, next) => {
    const claims = jsonwebtoken.verify(req.cookies['jwt'], jwtKey)
    req['authUserId'] = claims['sub']
    next()
  }
]

app.get('/api/auth-user', ...withAuthUserId, (req, res) => {
  /* See: req['authUserId'] */
})

There is more things to get done, like expiration dates, refresh tokens, etc. So I recommend using a service like auth0.