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