diff --git a/.env.example b/.env.example index 4cd8e7b..2eadc23 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,7 @@ APP_PIN_TV=123456 APP_PIN_SELLER=147258 APP_PIN_PIZZA=741852 APP_PIN_ADMIN=159753 +APP_PIN_PREPARATOR=000000 # Envoie un message sur Slack si activé à chaque commande SLACK_ENABLED=false diff --git a/src/controllers/order/index.ts b/src/controllers/order/index.ts index cb3ace6..1edcd4d 100644 --- a/src/controllers/order/index.ts +++ b/src/controllers/order/index.ts @@ -4,6 +4,7 @@ import list from './list'; import dispatch from './dispatch'; import editStatus from './editStatus'; import hasPermission from '../../middlewares/hasPermission'; +import hasPermissionInList from '../../middlewares/hasPermissionInList'; import { OrderUpdate } from '../../types'; import isBuck from '../../middlewares/isBuck'; import isAuth from '../../middlewares/isAuth'; @@ -14,8 +15,8 @@ export default () => { router.get('/', isAuth(), list); router.post('/', isAuth(), hasPermission('sell'), create); router.post('/dispatch', isBuck, dispatch); - router.patch('/:id/upgrade', isAuth(), hasPermission('pizza'), editStatus(OrderUpdate.UPGRADE)); - router.patch('/:id/downgrade', isAuth(), hasPermission('pizza'), editStatus(OrderUpdate.DOWNGRADE)); + router.patch('/:id/upgrade', isAuth(), hasPermissionInList(['pizza','prepare']), editStatus(OrderUpdate.UPGRADE)); + router.patch('/:id/downgrade', isAuth(), hasPermissionInList(['pizza','prepare']), editStatus(OrderUpdate.DOWNGRADE)); return router; }; diff --git a/src/middlewares/hasPermissionInList.ts b/src/middlewares/hasPermissionInList.ts new file mode 100644 index 0000000..4841f6b --- /dev/null +++ b/src/middlewares/hasPermissionInList.ts @@ -0,0 +1,35 @@ +import { Response, NextFunction, Request } from 'express'; +import jwt from 'jsonwebtoken'; +import getToken from '../utils/getToken'; +import { Token, Permission } from '../types'; +import { unauthorized, unauthenticated } from '../utils/responses'; +import errorHandler from '../utils/errorHandler'; + +export default (permissions: Array) => async (req: Request, res: Response, next: NextFunction) => { + try { + const token = getToken(req); + if (token) { + const decoded = jwt.verify(token, process.env.APP_TOKEN_SECRET) as Token; + + req.user = decoded; + + if (!permissions) { + return next(); + } + + if (decoded.permissions === Permission.ADMIN) { + return next(); + } + for (const permission of permissions) { + if (decoded.permissions === permission) { + return next(); + } + } + return unauthorized(res); + } + + return unauthenticated(res); + } catch (err) { + return errorHandler(res, err); + } +}; diff --git a/src/types.ts b/src/types.ts index ab0b91f..197619c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -22,6 +22,7 @@ export enum Permission { ADMIN = 'admin', SELLER = 'seller', PIZZA = 'pizza', + PREPARATOR = 'preparator' } export interface Token {