Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
let issuer;
if (decoded.payload.ver === '1.0') {
issuer = usGovernmentAuthentication.tokenIssuerV1;
} else if (decoded.payload.ver === '2.0') {
issuer = usGovernmentAuthentication.tokenIssuerV2;
} else {
// unknown token format
res.status(401);
res.end();
return;
}
try {
(req as any).jwt = jwt.verify(token, key, {
audience: usGovernmentAuthentication.botTokenAudience,
clockTolerance: 300,
issuer,
// TODO: "jwtId" is a typo, it should be "jwtid"
// But when we enable "jwtid", it will fail the verification
// because the payload does not specify "jti"
// When we comment out "jwtId", it also works (because it is a typo)
// jwtId: botId
});
} catch (err) {
res.status(401);
res.end();
return;
function decodeAuthToken(req, done) {
var token = req.headers.authorization || '';
if (!token) {
return done(true);
}
return jwt.verify(token, SECRET, done);
}
export function decodeToken(token: string): string | object | boolean {
let config: any = getConfig();
try {
let decoded = jwt.verify(token, config.secret);
return decoded;
} catch (e) {
return false;
}
}
jwks.getSigningKey(header.kid, (err, key) => {
if (err) {
return reject(
new AuthenticationError(
`${invalidTokenMessage} Could not get signing key: ${err.message}`
)
)
}
jwt.verify(
idToken,
key.publicKey,
{ algorithms: ['RS256'] },
(err, decoded) =>
err
? reject(
new AuthenticationError(
`${invalidTokenMessage} JWT verification error: ${err.message}`
)
)
: resolve(decoded)
)
})
})
App.decodeByKey = function (data, keyURL, type) {
var cert = fs.readFileSync(keyURL);
if (type) {
return jwt.verify(data, cert, {algorithm: type})
} else {
return jwt.verify(data, cert);
}
};
async parse(token) {
if (token) {
try {
return jwt.verify(token, secret);
} catch (err) {
return null;
}
}
return null;
}
return new Promise((resolve, reject) => {
if (!token) {
return reject(new Error(`token must provided`));
}
if (!secret) {
return reject(new Error(`secret must provided`));
}
debug('Verifying token', token);
jwt.verify(token, secret, pick(settings, VALID_KEYS), (error, payload) => {
if (error) {
debug('Error verifying token', error);
return reject(error);
}
debug('Verified token with payload', payload);
resolve(payload);
});
});
};
export async function authenticate(
req: any,
res: Response,
next: NextFunction
) {
const token = req.token;
if (!token)
return res
.status(401)
.json({ message: 'Access denied! No token provided.' });
try {
req.user = await jwt.verify(token, process.env.JWT_SECRET_KEY || '');
next();
} catch (error) {
return res.status(400).send(error.message);
}
}
(!req.headers.authorization && !req.headers.Authorization)
) {
throw new AuthorizationError({ message: "No authorization token." });
}
const token = req.headers.authorization || req.headers.Authorization;
try {
const id_token = token.replace("Bearer ", "");
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
throw new Error(
"No JWT secret set. Set environment variable JWT_SECRET to decode token."
);
}
const decoded = jwt.verify(id_token, JWT_SECRET, {
algorithms: ["HS256", "RS256"]
});
return decoded;
} catch (err) {
throw new AuthorizationError({
message: "You are not authorized for this resource"
});
}
};
export async function getUserId(ctx: Context) {
const authorization = ctx.request.get('Authorization')
if (authorization) {
const token = authorization.replace('Bearer ', '')
try {
const { userId } = jwt.verify(token, process.env.JWT_SECRET) as {
userId: string
}
const exist = await ctx.prisma.$exists.user({ id: userId })
if (!exist) throw new Error('User not found!')
return userId
} catch (e) {
throw new Error(`Session error: ${e}`)
}
}
throw new Error('Not authorized')
}