diff --git a/src/api/Security.ts b/src/api/Security.ts index 0d96067..95a2412 100644 --- a/src/api/Security.ts +++ b/src/api/Security.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-underscore-dangle */ import crypto from 'crypto'; import { Request } from 'express'; import { Client } from '..'; @@ -27,19 +28,25 @@ export default class Security { public async createBearer(_id: string): Promise { 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); let encrypted = cipher.update(JSON.stringify(account), 'utf8', 'base64'); encrypted += cipher.final('base64'); - return encrypted; + account.updateOne({ salt }); + return `${salt}:${encrypted}`; } public async checkBearer(bearer: string): Promise { const decipher = crypto.createDecipheriv('aes-256-gcm', this.keys.key, this.keys.iv); try { - let decrypted = decipher.update(bearer, 'base64', 'utf8'); + 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'); decrypted += decipher.final('utf8'); const json = JSON.parse(decrypted); const account = await this.client.db.Account.findOne({ username: json.username }); + if (account._id !== saltCheck._id) return null; return account; } catch { return null;