From 0e56b583350d4371e774ff94890abf61b23f294b Mon Sep 17 00:00:00 2001 From: Lautaro Dragan Date: Wed, 5 Jun 2019 23:38:06 -0300 Subject: [PATCH] refactor: interface JWTData (#964) --- src/controllers/AccountController.ts | 16 +++++++++++++--- src/interfaces/JWTData.ts | 11 +++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 src/interfaces/JWTData.ts diff --git a/src/controllers/AccountController.ts b/src/controllers/AccountController.ts index ff8859454..85dedb51b 100644 --- a/src/controllers/AccountController.ts +++ b/src/controllers/AccountController.ts @@ -14,6 +14,7 @@ import { } from '../errors/errors' import { tokenMatch } from '../helpers/token' import { uuid4 } from '../helpers/uuid' +import { isJWTData, JWTData } from '../interfaces/JWTData' import { Network } from '../interfaces/Network' import { Account } from '../models/Account' import { processPassword, passwordMatches } from '../utils/Password' @@ -84,9 +85,7 @@ export const AccountController = ({ }: Arguments): AccountController => { const authorizeRequest = async (token: string) => { try { - const decoded = verify(token.replace('TEST_', ''), configuration.jwtSecret) - const { client_token, email } = decoded as any - + const { client_token, email } = decodeJWT(token) const tokenData = await Vault.verifyToken(client_token) const account = await findByEmail(email) return { jwt: configuration.jwtSecret, tokenData, account } @@ -273,6 +272,17 @@ export const AccountController = ({ return sign({ email, client_token, network }, configuration.jwtSecret) } + const decodeJWT = (token: string): JWTData => { + const decoded: unknown = verify(token.replace('TEST_', ''), configuration.jwtSecret) + + if (!isJWTData(decoded)) { + logger.error({ decoded }, 'Unrecognized JWT') + throw new Error(`Unrecognized JWT`) + } + + return decoded + } + const poeAddressChallenge = async (issuer: string) => { const { email } = await accountDao.findOne({ issuer }) const poeAddressMessage = `Proof of POE ${email} ${new Date().toISOString()}` diff --git a/src/interfaces/JWTData.ts b/src/interfaces/JWTData.ts new file mode 100644 index 000000000..c0eba1b48 --- /dev/null +++ b/src/interfaces/JWTData.ts @@ -0,0 +1,11 @@ +import { Network } from './Network' + +export interface JWTData { + readonly iat: number + readonly client_token: string + readonly email: string + readonly network?: Network +} + +export const isJWTData = (a: any): a is JWTData => + typeof a === 'object' && typeof(a.client_token) === 'string' || typeof(a.email) === 'string'