From e09665bad641ee651ad197799436c21957f49195 Mon Sep 17 00:00:00 2001 From: Matthew R Date: Mon, 29 Jun 2020 17:54:42 -0400 Subject: [PATCH] change from crypto to jwt for bearer tokens --- src/class/Security.ts | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/src/class/Security.ts b/src/class/Security.ts index 7dee703..2a3a126 100644 --- a/src/class/Security.ts +++ b/src/class/Security.ts @@ -1,5 +1,5 @@ /* eslint-disable no-underscore-dangle */ -import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; import { Request } from 'express'; import { Client } from '.'; import { AccountInterface } from '../models'; @@ -26,16 +26,9 @@ export default class Security { * @param _id The Mongoose Document property labeled ._id */ public async createBearer(_id: string): Promise { - let account = await this.client.db.Account.findOne({ _id }); + const account = await this.client.db.Account.findOne({ _id }); if (!account) throw new Error(`Account [${_id}] cannot be found.`); - const salt = crypto.randomBytes(50).toString('base64'); - const cipher = crypto.createCipheriv('aes-256-gcm', this.keys.key, this.keys.iv); - await account.updateOne({ salt }); - account = await this.client.db.Account.findOne({ _id }); - let encrypted = cipher.update(JSON.stringify(account), 'utf8', 'base64'); - encrypted += cipher.final('base64'); - await account.updateOne({ authTag: cipher.getAuthTag() }); - return `${salt}:${encrypted}`; + return jwt.sign({ id: account.id }, this.keys.key, { issuer: 'Library of Code sp-us | CSD' }); } /** @@ -43,20 +36,12 @@ export default class Security { * @param bearer The bearer token provided. */ public async checkBearer(bearer: string): Promise { - const decipher = crypto.createDecipheriv('aes-256-gcm', this.keys.key, this.keys.iv); try { - const salt = bearer.split(':')[0]; - const saltCheck = await this.client.db.Account.findOne({ salt }); - const encrypted = bearer.split(':')[1]; - let decrypted = decipher.update(encrypted, 'base64', 'utf8'); - decipher.setAuthTag(saltCheck.authTag); - decrypted += decipher.final('utf8'); - const json = JSON.parse(decrypted); - const account = await this.client.db.Account.findOne({ username: json.username }); - if (saltCheck.salt !== account.salt) return null; + const res: any = jwt.verify(bearer, this.keys.key, { issuer: 'Library of Code sp-us | CSD' }); + const account = await this.client.db.Account.findOne({ _id: res.id }); + if (!account) return null; return account; - } catch (error) { - this.client.util.handleError(error); + } catch { return null; } }