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; } }