summaryrefslogtreecommitdiffstats
path: root/middleware/auth.js
blob: a62812e099f373da3082042d93b054156176b0a4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const fs = require('fs')
const jwt = require('jsonwebtoken')

const cert = fs.readFileSync(`${process.cwd()}/cert/jwt_256_rsa.pub`, 'utf8')

const auth = async (req, res, next) => {
  try {
    const jwtToken = req.body.jwtToken

    if (!jwtToken) throw new Error()

    const user = jwt.verify(jwtToken, cert, { algorithms: ['RS256'], issuer: 'pruss.it' })

    if (!user) throw new Error()

    req.user = user

    return next()
  } catch (err) {
    const error = err === 'jwt expired' ? err.message : 'unauthorized'

    res.status(401).send({ error })
  }
}

module.exports = auth