Last active
March 11, 2022 08:55
-
-
Save WEEFAA/610148b9bf9a7c8fe5259b2f7e834d4d to your computer and use it in GitHub Desktop.
[JWT] decode/sign
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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