diff --git a/server/controllers/middleware/index.js b/server/controllers/middleware/index.js deleted file mode 100644 index e69de29..0000000 diff --git a/server/middleware/index.js b/server/middleware/index.js new file mode 100644 index 0000000..4c1cf4e --- /dev/null +++ b/server/middleware/index.js @@ -0,0 +1,5 @@ +const isAuth = require('./isAuth'); + +module.exports = { + isAuth, +}; diff --git a/server/middleware/isAuth.js b/server/middleware/isAuth.js new file mode 100644 index 0000000..605b18c --- /dev/null +++ b/server/middleware/isAuth.js @@ -0,0 +1,22 @@ +const { verifyToken } = require('../utils'); + +const isAuth = async (req, res, next) => { + try { + const { + cookies: { token }, + } = req; + if (!token) { + return res.status(401).json({ + message: 'You are not authorized ', + }); + } + const decoded = await verifyToken(token); + req.user = decoded; + return next(); + } catch (err) { + return res.status(401).json({ + message: 'You are not authorized ', + }); + } +}; +module.exports = isAuth; diff --git a/server/utils/index.js b/server/utils/index.js index e69de29..ce115b5 100644 --- a/server/utils/index.js +++ b/server/utils/index.js @@ -0,0 +1,6 @@ +const { signToken, verifyToken } = require('./tokenFunction'); + +module.exports = { + signToken, + verifyToken, +}; diff --git a/server/utils/tokenFunction.js b/server/utils/tokenFunction.js new file mode 100644 index 0000000..c7ac90e --- /dev/null +++ b/server/utils/tokenFunction.js @@ -0,0 +1,25 @@ +const { verify, sign } = require('jsonwebtoken'); + +const { + env: { ACCESS_TOKEN_SECRET }, +} = process; + +const verifyToken = (token) => new Promise((resolve, reject) => { + verify(token, ACCESS_TOKEN_SECRET, (err, decoded) => { + if (err) { + reject(err); + } else { + resolve(decoded); + } + }); +}); +const signToken = (payload) => new Promise((resolve, reject) => { + sign(payload, ACCESS_TOKEN_SECRET, (err, token) => { + if (err) { + return reject(err); + } + return resolve(token); + }); +}); + +module.exports = { signToken, verifyToken };