diff options
author | 2023-08-21 22:19:54 +0200 | |
---|---|---|
committer | 2023-08-21 22:23:57 +0200 | |
commit | 9fb0815b575cfc23ced6722b1a164328bd3cff1a (patch) | |
tree | 971a10bb74824d007cb74082a0a1d07dba3f30e2 /middleware/auth.js | |
parent | 4d28ac359b25d89d0dbb42dd3a6d32269eebc619 (diff) | |
download | auth-service-9fb0815b575cfc23ced6722b1a164328bd3cff1a.tar.gz auth-service-9fb0815b575cfc23ced6722b1a164328bd3cff1a.tar.bz2 auth-service-9fb0815b575cfc23ced6722b1a164328bd3cff1a.zip |
refactor, new routes
Diffstat (limited to 'middleware/auth.js')
-rw-r--r-- | middleware/auth.js | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/middleware/auth.js b/middleware/auth.js new file mode 100644 index 0000000..a62812e --- /dev/null +++ b/middleware/auth.js @@ -0,0 +1,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 |