merge-requests/1/merge
Matthew 2019-11-16 23:22:49 -05:00
parent 009bdad83e
commit b0cf9bfc1e
No known key found for this signature in database
GPG Key ID: 766BE43AE75F7559
1 changed files with 9 additions and 2 deletions

View File

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