forked from engineering/cloudservices
change from crypto to jwt for bearer tokens
parent
59f8336d25
commit
e09665bad6
|
@ -1,5 +1,5 @@
|
|||
/* eslint-disable no-underscore-dangle */
|
||||
import crypto from 'crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { Request } from 'express';
|
||||
import { Client } from '.';
|
||||
import { AccountInterface } from '../models';
|
||||
|
@ -26,16 +26,9 @@ export default class Security {
|
|||
* @param _id The Mongoose Document property labeled ._id
|
||||
*/
|
||||
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.`);
|
||||
const salt = crypto.randomBytes(50).toString('base64');
|
||||
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}`;
|
||||
return jwt.sign({ id: account.id }, this.keys.key, { issuer: 'Library of Code sp-us | CSD' });
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -43,20 +36,12 @@ export default class Security {
|
|||
* @param bearer The bearer token provided.
|
||||
*/
|
||||
public async checkBearer(bearer: string): Promise<null | AccountInterface> {
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.keys.key, this.keys.iv);
|
||||
try {
|
||||
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');
|
||||
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;
|
||||
const res: any = jwt.verify(bearer, this.keys.key, { issuer: 'Library of Code sp-us | CSD' });
|
||||
const account = await this.client.db.Account.findOne({ _id: res.id });
|
||||
if (!account) return null;
|
||||
return account;
|
||||
} catch (error) {
|
||||
this.client.util.handleError(error);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue