Skip to content
loading...

How to create a session / login with ejs ?

adrien09972856 profile image Ipicky2 twitter logo github logo Updated on ・1 min read  

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 ?

twitter logo DISCUSS (1)
Discussion
markdown guide
 

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.

Classic DEV Post from Feb 22 '18

Four Security Principles That Software Developers Should Follow

Security is a topic that is often poorly understood by developers because many of them focus on the technical side of security rather than the wider topic

Ipicky2 profile image