forked from engineering/cloudservices
add salt
parent
009bdad83e
commit
b0cf9bfc1e
|
@ -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<string> {
|
||||
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<null | AccountInterface> {
|
||||
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;
|
||||
|
|
Loading…
Reference in New Issue