From 1a9c1bf898d2297a4112e1784a48d89c7a5e249c Mon Sep 17 00:00:00 2001 From: AbegaM Date: Wed, 13 Mar 2024 17:46:10 +0300 Subject: [PATCH] Add access for endpoints that can be accessed by any user --- src/constants/api.js | 8 ++++++++ src/constants/httpVerbs.js | 6 ------ src/middlewares/auth.js | 10 ++++++++-- 3 files changed, 16 insertions(+), 8 deletions(-) delete mode 100644 src/constants/httpVerbs.js diff --git a/src/constants/api.js b/src/constants/api.js index 799ee77..b898b09 100644 --- a/src/constants/api.js +++ b/src/constants/api.js @@ -1,6 +1,7 @@ module.exports = { defaultRoutes: ['_users', '_roles', '_roles_permissions', '_users_roles'], baseTableUrl: '/api/tables', + universalAccessEndpoints: ['/api/auth/change-password'], fields: { _users: { SALT: 'salt', @@ -14,4 +15,11 @@ module.exports = { TOO_WEAK: 'Too weak', WEAK: 'Weak', }, + + httpVerbs: { + POST: 'CREATE', + GET: 'READ', + PUT: 'UPDATE', + DELETE: 'DELETE', + }, }; diff --git a/src/constants/httpVerbs.js b/src/constants/httpVerbs.js deleted file mode 100644 index 4dfb16c..0000000 --- a/src/constants/httpVerbs.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - POST: 'CREATE', - GET: 'READ', - PUT: 'UPDATE', - DELETE: 'DELETE', -}; diff --git a/src/middlewares/auth.js b/src/middlewares/auth.js index c4e4e1e..a73875a 100644 --- a/src/middlewares/auth.js +++ b/src/middlewares/auth.js @@ -1,11 +1,12 @@ const config = require('../config'); const { decodeToken, toBoolean } = require('../utils/index'); -const httpVerbs = require('../constants/httpVerbs'); +const { apiConstants } = require('../constants'); const isAuthenticated = async (req, res, next) => { let payload; const { name: tableName } = req.params; const verb = req.method; + const originalURL = req.originalUrl; try { if (config.auth) { @@ -25,6 +26,11 @@ const isAuthenticated = async (req, res, next) => { return next(); } + // if the endpoint is set to be accessed by any user regardless of there roles, then allow access + if (apiConstants.universalAccessEndpoints.includes(originalURL)) { + return next(); + } + // if table_name is not passed from the router throw unauthorized error if (!tableName) { return res.status(403).send({ message: 'Not authorized' }); @@ -45,7 +51,7 @@ const isAuthenticated = async (req, res, next) => { let hasPermission = false; permissions.some((resource) => { - const httpMethod = httpVerbs[verb].toLowerCase(); + const httpMethod = apiConstants.httpVerbs[verb].toLowerCase(); if (toBoolean(resource[httpMethod])) { hasPermission = true;