Skip to content

Instantly share code, notes, and snippets.

@hieuhani
Created August 24, 2018 02:55
Show Gist options
  • Save hieuhani/730aa25354ca6ed3023304b091757e4d to your computer and use it in GitHub Desktop.
Save hieuhani/730aa25354ca6ed3023304b091757e4d to your computer and use it in GitHub Desktop.
import Joi from 'joi'
import jwt from 'jsonwebtoken'
import logger from '../logger'
import RestController from './RestController'
import AppError from '../AppError'
export default class ApplicationsController extends RestController {
async validateAppToken(payload) {
logger.debug('validate application token with data', payload)
const validationSchema = Joi.object().keys({
appId: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required(),
accessToken: Joi.string().min(3).max(500).required(),
}).with('appId', 'accessToken')
const result = Joi.validate(payload, validationSchema)
if (result.error) {
logger.debug('Validation error for validating application token')
throw new AppError(AppError.INPUT_VALIDATION_ERROR, result.error.message)
}
const { response: application } = await this.show(payload.appId)
if (!application) {
throw new AppError(AppError.APPLICATION_NOT_FOUND, this.translate('error:Application is not found'))
}
const { secretKey } = application
if (!secretKey) {
logger.error(`Cound not find the secret key for the application ${payload.appId}`)
throw new Error(this.translate('error:The application secrete key is not configured properly'))
}
return new Promise((resolve) => {
jwt.verify(payload.accessToken, secretKey, (err, decoded) => {
if (err) {
logger.error(err)
throw new AppError(AppError.INVALID_APPLICATION_TOKEN, this.translate('error:Invalid access token'))
}
if (application._id.toString() !== decoded.id) {
throw new Error(this.translate('error:The access token is valid but forbidden for this application'))
}
return resolve({
response: application,
})
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment