import * as jwt from 'jsonwebtoken' import { Response, Body } from './types' export const verifyJwt = (token, authKey) => { try { const decoded = jwt.verify(token, authKey) as jwt.JwtPayload if (!('exp' in decoded) || !decoded.exp) { throw new Error('No expiry data for provided jwt.') } return { jwt: jwt.verify(token, authKey), success: (Date.now() / 1000) < decoded.exp!, } } catch (e) { return { e, success: false, } } } const validateBody = (body: Body) => { if (!body.authKeys || !body.authKeys.current || !body.authKeys.previous) { throw new Error('Failed to validate body. Improper authkeys provided.') } if (!body.jwt) { throw new Error('Failed to validate body. Improper jwt provided.') } } export async function ServerUtils_IsUserAuthorised(body: Body) { const response: Response = { access: true, } try { // Check the JWT using the authKey // Check the authKey against the last 2 cached on the server. validateBody(body) const decodedCurrent = verifyJwt(body.jwt, body.authKeys.current) const decodedPrevious = verifyJwt(body.jwt, body.authKeys.previous) if (!decodedCurrent.success && !decodedPrevious.success) { response.error = 'Not Authorised, Log In' response.access = false return response } const decoded = (decodedCurrent.success ? decodedCurrent.jwt : decodedPrevious.jwt) as jwt.JwtPayload const encoded = body.jwt return { ...response, ...decoded, encoded } } catch (err) { return new Promise((resolve) => { response.error = 'Fatal error in ServerUtils_IsUserAuthorised. Investigate.' response.errorMessage = err.message response.success = false response.access = false return resolve(response) }) } }