Skip to content

Instantly share code, notes, and snippets.

@ChaoLiangSuper
Last active May 11, 2019 04:00
Show Gist options
  • Save ChaoLiangSuper/86c8312619cede7be77b2cc41aa1f44c to your computer and use it in GitHub Desktop.
Save ChaoLiangSuper/86c8312619cede7be77b2cc41aa1f44c to your computer and use it in GitHub Desktop.
JsonWebToken usage 'generate', 'verify' and 'refresh' token
import jwt from 'jsonwebtoken';
interface payload {
data: object;
}
type GenerateToken = (data: object) => string;
type VerifyToken = (
token: string
) => {
isValid: boolean;
data?: object;
message?: string;
};
type RefreshToken = (
token: string
) => {
isValid: boolean;
token?: string;
message?: string;
};
const issuer = 'BIG_USER_SYSTEM';
const subject = '[email protected]';
const audience = 'example.com';
const SIGNATURE_KEY = process.env.SIGNATURE_KEY!;
const signOptions = {
issuer,
subject,
audience,
expiresIn: '1h',
algorithm: 'HS256'
};
export const generateToken: GenerateToken = (data) =>
jwt.sign({ data } as payload, SIGNATURE_KEY, signOptions);
export const verifyToken: VerifyToken = (token) => {
try {
const { data } = jwt.verify(token, SIGNATURE_KEY, signOptions) as payload;
return {
isValid: true,
data
};
} catch (err) {
return {
isValid: false,
message: err.message
};
}
};
export const refreshToken: RefreshToken = (token) => {
const { isValid, data, message } = verifyToken(token);
return isValid
? {
isValid,
token: generateToken(data!)
}
: {
isValid,
message
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment