Skip to content

Instantly share code, notes, and snippets.

@WEEFAA
Last active March 11, 2022 08:55
Show Gist options
  • Select an option

  • Save WEEFAA/610148b9bf9a7c8fe5259b2f7e834d4d to your computer and use it in GitHub Desktop.

Select an option

Save WEEFAA/610148b9bf9a7c8fe5259b2f7e834d4d to your computer and use it in GitHub Desktop.
[JWT] decode/sign
const asyncVerify = nodeUtil.promisify(jwt.verify)
const JWT_SECRET = 'jwt.secret'
const f = {}
f.signToken = (id) => {
// 24 hours
let tokenExpiry = 60 * 60 * 24
return jwt.sign(
{
username: id
},
JWT_SECRET,
{ expiresIn: tokenExpiry }
)
}
f.decodeToken = async token => {
try {
const decoded = await asyncVerify(token, JWT_SECRET)
return decoded
} catch (err) {
if (err instanceof jwt.JsonWebTokenError) {
if (
err.name == 'JsonWebTokenError' ||
err.name == 'TokenExpiredError'
) {
return Promise.reject(new AuthenticationError())
} else if (err.name == 'NotBeforeError') {
// not before mech
return Promise.reject(
new AuthenticationError('Cannot used token before.')
)
}
}
// Catch the JWT Expired or Invalid errors
return Promise.reject(new OtherErrors())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment