· 7 years ago · Aug 24, 2018, 05:46 AM
1import Joi from 'joi'
2import jwt from 'jsonwebtoken'
3import logger from '../logger'
4import RestController from './RestController'
5import AppError from '../AppError'
6
7export default class ApplicationsController extends RestController {
8 async validateAppToken(payload) {
9 logger.debug('validate application token with data', payload)
10 const validationSchema = Joi.object().keys({
11 appId: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required(),
12 accessToken: Joi.string().min(3).max(500).required(),
13 }).with('appId', 'accessToken')
14 const result = Joi.validate(payload, validationSchema)
15 if (result.error) {
16 logger.debug('Validation error for validating application token')
17 throw new AppError(AppError.INPUT_VALIDATION_ERROR, result.error.message)
18 }
19 const { response: application } = await this.show(payload.appId)
20 if (!application) {
21 throw new AppError(AppError.APPLICATION_NOT_FOUND, this.translate('error:Application is not found'))
22 }
23 const { secretKey } = application
24 if (!secretKey) {
25 logger.error(`Cound not find the secret key for the application ${payload.appId}`)
26 throw new Error(this.translate('error:The application secrete key is not configured properly'))
27 }
28 return new Promise((resolve) => {
29 jwt.verify(payload.accessToken, secretKey, (err, decoded) => {
30 if (err) {
31 logger.error(err)
32 throw new AppError(AppError.INVALID_APPLICATION_TOKEN, this.translate('error:Invalid access token'))
33 }
34 if (application._id.toString() !== decoded.id) {
35 throw new Error(this.translate('error:The access token is valid but forbidden for this application'))
36 }
37 return resolve({
38 response: application,
39 })
40 })
41 })
42 }
43}