DEV Community

Ipicky2
Ipicky2

Posted on • Updated on

How to create a session / login with ejs ?

Hi, for a web development project, I want to make a login page on my website, but I don't know how to create a session, and compare the login with my .json.
I tried to do my login system with passport, express-session ans socket.io, but I didn't succeed. I don't understand the logic required.

Could someone please help me ? Explain to me the logic ? Show me an example code which help me ?

Top comments (1)

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.