Skip to content

Commit

Permalink
chore - add cipher to cron token
Browse files Browse the repository at this point in the history
  • Loading branch information
ashtrindade committed Sep 20, 2024
1 parent a7a5f4d commit e822c95
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 15 deletions.
22 changes: 13 additions & 9 deletions src/controller/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,23 +197,27 @@ export default class UserController {
}
}

public static readonly scheduledDelete = async(_req: Request, res: Response, next: NextFunction): Promise<void> => {
public static readonly scheduledDelete = async (_req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
const currentTime = new Date().toISOString()
const query = { $and: [{ isDisabled: true }, { expiresIn: { $lt: currentTime } }] }

const accounts = await collections.users.find(query, { projection: { email: 1, settings: { language: 1 } } }).toArray()
const deleteAccounts = await collections.users.deleteMany(query)

const result = await ScheduledDelete.deleteAndNotify(accounts as unknown as AccountsToDelete, deleteAccounts)
if (accounts.length > 0) {
const deleteAccounts = await collections.users.deleteMany(query)

const result = await ScheduledDelete.deleteAndNotify(accounts as unknown as AccountsToDelete, deleteAccounts)

if (deleteAccounts.acknowledged && result) {
res.status(200).send(result)
if (deleteAccounts.acknowledged && result) {
res.status(200).send(result)
} else {
next(new InternalServerError(CustomErrorMessage.INTERNAL_SERVER_ERROR))
next()
}
} else {
next(new InternalServerError(CustomErrorMessage.INTERNAL_SERVER_ERROR))
next()
res.status(204).send()
}

Log.info('controller', 'UserController :: Calling Endpoint :: ScheduledDelete')
} catch (error) {
Log.error('controller', 'UserController :: Calling Endpoint :: ScheduledDelete', error)
Expand Down
15 changes: 9 additions & 6 deletions src/middleware/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextFunction, Request, Response } from 'express'
import { BadRequest, Unauthorized } from '../error/CustomError'
import CustomErrorMessage from '../util/enum/CustomErrorMessage'
import JWT from '../util/security/JWT'
import Cipher from 'src/util/security/Cipher'

export default class Auth {
public static readonly jwt = (req: Request, _res: Response, next: NextFunction) => {
Expand All @@ -27,13 +28,15 @@ export default class Auth {
if (!token) {
next(new BadRequest(CustomErrorMessage.AUTH_NOT_PROVIDED))
next()
}

if (token === process.env.CRON_TOKEN) {
next()
} else {
next(new Unauthorized(CustomErrorMessage.UNAUTHORIZED))
next()
const decodedToken = Cipher.decode(token, next)

if (decodedToken === process.env.CRON_TOKEN) {
next()
} else {
next(new Unauthorized(CustomErrorMessage.UNAUTHORIZED))
next()
}
}
} catch (error) {
next(error)
Expand Down
45 changes: 45 additions & 0 deletions src/util/security/Cipher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import crypto from 'crypto'
import * as dotenv from 'dotenv'
import { NextFunction } from 'express'
import { BadRequest } from '../../error/CustomError'
import Log from '../log/Log'
dotenv.config({ path: '.env' })

export default class Cipher {
private static readonly _algorithm = 'aes-256-cbc'
private static readonly _key = process.env.CIPHER_KEY as string
private static readonly _iv = crypto.randomBytes(16)

public static readonly encode = (input: string, next: NextFunction) => {
try {
const cipher = crypto.createCipheriv(this._algorithm, this._key, this._iv)
let encrypted = cipher.update(input, 'utf8', 'hex')

encrypted += cipher.final('hex')

return `${this._iv.toString('hex')}:${encrypted}`
} catch (error) {
next(error)
next()
}
}

public static readonly decode = (input: string, next: NextFunction) => {
try {
const [ivHex, encrypted] = input.split(':')
const iv = Buffer.from(ivHex, 'hex')

const decipher = crypto.createDecipheriv(this._algorithm, this._key, iv)

let decrypted = decipher.update(encrypted, 'hex', 'utf8')

decrypted += decipher.final('utf8')

return decrypted
} catch (error) {
Log.error('error', 'Cipher :: Decode', error)
next(new BadRequest('Invalid token'))
next()
}
}
}
38 changes: 38 additions & 0 deletions test/unit/src/util/security/Cipher.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { NextFunction } from 'express'
import { BadRequest } from 'src/error/CustomError'
import Cipher from 'src/util/security/Cipher'

describe('Cipher', () =>{
let next: NextFunction

beforeEach(() => {
next = jest.fn()
})

afterEach(() => {
jest.resetAllMocks()
})

const sample = 'user-name_12+alias@example.com'

it('should encode and decode', () => {
const encoded = Cipher.encode(sample, next)
console.log(encoded)
const decoded = Cipher.decode(encoded as string, next)

expect(decoded).toEqual(sample)
})

it('should call next with a BadRequest', () => {
Cipher.decode('string', next)

expect(next).toHaveBeenCalledWith(new BadRequest('Invalid token'))
})

it('should call next with an error', () => {
Cipher.encode(undefined as unknown as string, next)

expect(next).toHaveBeenCalled()
expect(next).toHaveBeenCalledTimes(2)
})
})

0 comments on commit e822c95

Please sign in to comment.