1
0
Fork 0

change from crypto to jwt for bearer tokens

refactor/models
Matthew 2020-06-29 17:54:42 -04:00
parent 59f8336d25
commit e09665bad6
No known key found for this signature in database
GPG Key ID: 210AF32ADE3B5C4B
1 changed files with 7 additions and 22 deletions

View File

@ -1,5 +1,5 @@
/* eslint-disable no-underscore-dangle */ /* eslint-disable no-underscore-dangle */
import crypto from 'crypto'; import jwt from 'jsonwebtoken';
import { Request } from 'express'; import { Request } from 'express';
import { Client } from '.'; import { Client } from '.';
import { AccountInterface } from '../models'; import { AccountInterface } from '../models';
@ -26,16 +26,9 @@ export default class Security {
* @param _id The Mongoose Document property labeled ._id * @param _id The Mongoose Document property labeled ._id
*/ */
public async createBearer(_id: string): Promise<string> { public async createBearer(_id: string): Promise<string> {
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.`); if (!account) throw new Error(`Account [${_id}] cannot be found.`);
const salt = crypto.randomBytes(50).toString('base64'); return jwt.sign({ id: account.id }, this.keys.key, { issuer: 'Library of Code sp-us | CSD' });
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}`;
} }
/** /**
@ -43,20 +36,12 @@ export default class Security {
* @param bearer The bearer token provided. * @param bearer The bearer token provided.
*/ */
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);
try { try {
const salt = bearer.split(':')[0]; const res: any = jwt.verify(bearer, this.keys.key, { issuer: 'Library of Code sp-us | CSD' });
const saltCheck = await this.client.db.Account.findOne({ salt }); const account = await this.client.db.Account.findOne({ _id: res.id });
const encrypted = bearer.split(':')[1]; if (!account) return null;
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;
return account; return account;
} catch (error) { } catch {
this.client.util.handleError(error);
return null; return null;
} }
} }