Changed JWT implementation.

This commit is contained in:
Mike Cao 2020-07-22 21:33:17 -07:00
parent cb0c912c5b
commit f3f0ad15f2
6 changed files with 48 additions and 13 deletions

View file

@ -1,9 +1,10 @@
import crypto from 'crypto';
import { v5 } from 'uuid';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { JWT, JWE, JWK } from 'jose';
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const KEY = JWK.asKey(Buffer.from(secret()));
export function sha256(...args) {
return crypto.createHash('sha256').update(args.join('')).digest('hex');
@ -25,14 +26,23 @@ export function isValidHash(s) {
return UUID_REGEX.test(s);
}
export async function createToken(payload, options) {
return jwt.sign(payload, secret(), options);
}
export async function parseToken(token, options) {
return jwt.verify(token, secret(), options);
}
export function checkPassword(password, hash) {
return bcrypt.compare(password, hash);
}
export async function createToken(payload) {
return JWT.sign(payload, KEY);
}
export async function verifyToken(token) {
return JWT.verify(token, KEY);
}
export async function createSecureToken(payload) {
return JWE.encrypt(await createToken(payload), KEY);
}
export async function verifySecureToken(token) {
const result = await JWE.decrypt(token, KEY);
return verifyToken(result.toString());
}

View file

@ -1,6 +1,6 @@
import { getWebsite, getSession, createSession } from 'lib/db';
import { getCountry, getDevice, getIpAddress } from 'lib/utils';
import { uuid, parseToken, isValidHash } from 'lib/crypto';
import { uuid, isValidHash, verifyToken } from 'lib/crypto';
export default async req => {
const { payload } = req.body;
@ -11,7 +11,7 @@ export default async req => {
}
try {
return await parseToken(session);
return await verifyToken(session);
} catch {
const ip = getIpAddress(req);
const { userAgent, browser, os } = getDevice(req);