diff --git a/server/database/quieres/checkAdmin.js b/server/database/quieres/checkAdmin.js new file mode 100644 index 0000000..8e814ab --- /dev/null +++ b/server/database/quieres/checkAdmin.js @@ -0,0 +1,5 @@ +const connection = require('../config/connection'); + +const checkAdminQuery = (email) => connection.query('SELECT * FROM admins WHERE email= ($1)', [email]); + +module.exports = checkAdminQuery; diff --git a/server/database/quieres/index.js b/server/database/quieres/index.js index b3ef209..9c42a66 100644 --- a/server/database/quieres/index.js +++ b/server/database/quieres/index.js @@ -1,5 +1,6 @@ const userEstatesQuery = require('./userEstatesQuiery'); const getAllUsersQuery = require('./getAllUsersQuery'); +const checkAdminQuery = require('./checkAdmin'); const checkEmailQuery = require('./checkEmailQuery'); const editEstateQuery = require('./editEstatesQuery'); const deleteEstateQuery = require('./deleteEstateQuery'); @@ -7,6 +8,7 @@ const deleteEstateQuery = require('./deleteEstateQuery'); module.exports = { getAllUsersQuery, userEstatesQuery, + checkAdminQuery, checkEmailQuery, editEstateQuery, deleteEstateQuery, diff --git a/server/middleware/index.js b/server/middleware/index.js index 4c1cf4e..bb28dd7 100644 --- a/server/middleware/index.js +++ b/server/middleware/index.js @@ -1,5 +1,7 @@ const isAuth = require('./isAuth'); +const isAdmin = require('./isAdmin'); module.exports = { isAuth, + isAdmin, }; diff --git a/server/middleware/isAdmin.js b/server/middleware/isAdmin.js new file mode 100644 index 0000000..fa6b1ca --- /dev/null +++ b/server/middleware/isAdmin.js @@ -0,0 +1,22 @@ +const { checkAdminQuery } = require('../database/quieres'); +const { verifyToken } = require('../utils'); + +const isAdmin = async (req, res, next) => { + try { + const { token } = req.cookies; + if (!token) { + return res.status(400).json({ message: 'You are not authorized' }); + } + const decoded = await verifyToken(token); + req.email = decoded.email; + + const rows = await checkAdminQuery(req.email); + if (!rows.length) { + return res.status(400).json({ message: 'You are not authorized' }); + } + return next(); + } catch (err) { + return next(err); + } +}; +module.exports = isAdmin;