-
Notifications
You must be signed in to change notification settings - Fork 8
/
is-auth.js
34 lines (32 loc) · 934 Bytes
/
is-auth.js
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
27
28
29
30
31
32
33
34
const axios = require('axios');
const { createRemoteJWKSet } = require('jose/jwks/remote');
const { jwtVerify } = require('jose/jwt/verify');
const BACKEND_URL = 'http://localhost:80';
const JWKS = createRemoteJWKSet(new URL(`${BACKEND_URL}/auth/publicKey`));
exports.isAuth = async (req, res, next) => {
try {
const authHeader = req.get('Authorization');
if (!authHeader) {
const error = new Error('Not authenticated.');
error.statusCode = 401;
throw error;
}
const token = authHeader.split(' ')[1];
const { payload } = await jwtVerify(token, JWKS, {
issuer: 'wmtech',
audience: 'auth.wmtech.cc'
});
if (!payload) {
const error = new Error('Not authenticated.');
error.statusCode = 401;
throw error;
}
req.userId = payload['userId'];
next();
} catch (err) {
if(!err.statusCode){
err.statusCode = 500;
}
next(err);
}
};