diff --git a/backend/app/config/checkFormat.config.js b/backend/app/config/checkFormat.config.js new file mode 100644 index 0000000..6b74fe0 --- /dev/null +++ b/backend/app/config/checkFormat.config.js @@ -0,0 +1,9 @@ +const {sendError} = require ("./response.config"); + +function checkFormat(req, res){ + if(req.get('Content-Type') !== 'application/json') { + return sendError(res, 401, -1, "Invalid header format (please use JSON)"); + } + return true; // Is valid +} +module.exports = checkFormat diff --git a/backend/app/config/response.config.js b/backend/app/config/response.config.js index 625a6cc..dcf5145 100644 --- a/backend/app/config/response.config.js +++ b/backend/app/config/response.config.js @@ -1,9 +1,9 @@ function sendMessage (res, successCode, data) { - return res.status(200).json({ status: 'success', successCode: successCode, data: data }); + res.status(200).json({ status: 'success', successCode: successCode, data: data }); } function sendError (res, statusCode, errorCode, reason) { - return res.status(statusCode).json({ status: 'error', errorCode: errorCode, reason: reason }); + res.status(statusCode).json({ status: 'error', errorCode: errorCode, reason: reason }); } module.exports = { sendMessage, sendError }; diff --git a/backend/app/config/sessionJWT.config.js b/backend/app/config/sessionJWT.config.js index 5f525b5..0a50b10 100644 --- a/backend/app/config/sessionJWT.config.js +++ b/backend/app/config/sessionJWT.config.js @@ -1,6 +1,6 @@ const sessionJWTConfig = require ('jsonwebtoken'); require('dotenv').config({ path: './app/.env' }); -const {sendError, sendMessage} = require ("./response.config"); +const {sendError} = require ("./response.config"); if(process.env.JWTRS256_PRIVATE_KEY === undefined || process.env.JWTRS256_PUBLIC_KEY === undefined){ console.log('Error Env Variables'); @@ -8,8 +8,9 @@ if(process.env.JWTRS256_PRIVATE_KEY === undefined || process.env.JWTRS256_PUBLIC } console.log('Env variables received'); -const JWTRS256_PRIVATE_KEY = Buffer.from(process.env.JWTRS256_PRIVATE_KEY, 'base64'); -const JWTRS256_PUBLIC_KEY = Buffer.from(process.env.JWTRS256_PUBLIC_KEY, 'base64'); +const JWTRS256_PRIVATE_KEY = Buffer.from(process.env.JWTRS256_PRIVATE_KEY, 'base64').toString('utf-8'); +const JWTRS256_PUBLIC_KEY = Buffer.from(process.env.JWTRS256_PUBLIC_KEY, 'base64').toString('utf-8'); + function createSessionJWT (mail) { return sessionJWTConfig.sign( @@ -37,31 +38,50 @@ function createSessionCookie(req, res, payload) { } res.cookie('SESSIONID', jwtToken, {httpOnly:true, secure:false}); } -module.exports.createSessionCookie = createSessionCookie; -function decodeSessionCookie(sessionid, res) { +function decodeSessionCookie(sessionid) { if (typeof sessionid === 'undefined') { - return { mail: -1 }; + return {mail: -1}; } try { const token = sessionJWTConfig.verify( sessionid, JWTRS256_PUBLIC_KEY, {algorithms: ['RS256']}); - return sendMessage(res,1,{token: token}); + return {token: token}; } catch (err) { - return sendError(res,-1,{mail: -1}); + return {mail: -1}; } } -module.exports.decodeSessionCookie = decodeSessionCookie; -function getSession (sessionid, res) { - return decodeSessionCookie(sessionid, res); +function getSession(sessionid) { + return decodeSessionCookie(sessionid); } -module.exports.getSession = getSession; +module.exports.getSession = getSession function setSessionCookie (req, res, session) { createSessionCookie(req, res, session); } module.exports.setSessionCookie = setSessionCookie; + +function getMail(session) { + if (typeof session === 'undefined' || typeof session.token === 'undefined') return -1; + return session.token; +} +module.exports.getMail = getMail; + +function checkLogin(req, res){ + if(typeof req.cookies !== 'undefined'){ + const session = getSession(req.cookies.SESSIONID); + const token = getMail(session); + if(token.mail === 'undefined' || token.mail === -1){ + return sendError(res, 500, -1, "User not authenticated."); + } else{ + return token; + } + } else { + return sendError(res, 500, -1, "Cookies don't exist."); + } +} +module.exports.checkLogin = checkLogin; diff --git a/backend/app/controllers/user.controller.js b/backend/app/controllers/user.controller.js index b0cc4cf..9659cef 100644 --- a/backend/app/controllers/user.controller.js +++ b/backend/app/controllers/user.controller.js @@ -1,11 +1,13 @@ const db = require("../models/mongodb.model"); const {sendError, sendMessage} = require ("../config/response.config"); +const checkFormat = require("../config/checkFormat.config"); const sessionJWT = require('../config/sessionJWT.config'); +const {checkLogin} = require("../config/sessionJWT.config"); const User = db.users; - // Authenticate an User exports.auth = (req, res) => { + checkFormat(req, res); // Validate request if (!req.body.mail || !req.body.hashPass) { sendError(res, 400,-1,"Content can not be empty ! (mail and hashPass needed)"); @@ -19,7 +21,7 @@ exports.auth = (req, res) => { return sendMessage(res, 1, true); } else { sessionJWT.setSessionCookie(req, res, { mail: -1 }); - return sendError(res, -1, "Invalid mail or password."); + return sendError(res, 500, -1, "Invalid mail or password."); } }) .catch(err => { @@ -28,8 +30,19 @@ exports.auth = (req, res) => { } }; +// Disconnect an User +exports.disconnect = (req, res) => { + let token; + if(checkFormat(req, res) && (token = checkLogin(req, res))) { + console.log(token); + sessionJWT.setSessionCookie(req, res, {mail: -1}); + return sendMessage(res, 1, {message: "User disconnected"}); + } +}; + // Create and Save a new User exports.create = (req, res) => { + checkFormat(req, res); // Validate request if (!req.body.login || !req.body.hashPass || !req.body.mail || !req.body.role) { sendError(res, 400,-1,"Content can not be empty ! (login, hashPass, mail and role needed"); @@ -67,20 +80,25 @@ exports.create = (req, res) => { // Retrieve all Users from the database. exports.findAll = (req, res) => { - const login = req.query.login; - let condition = login ? { login: { $regex: new RegExp(login), $options: "i" } } : {}; + let token; + if(checkFormat(req, res) && (token = checkLogin(req, res))){ + console.log(token); + const login = req.query.login; + let condition = login ? { login: { $regex: new RegExp(login), $options: "i" } } : {}; - User.find(condition, {hashPass: false}) - .then(data => { - sendMessage(res, 1, data) - }) - .catch(err => { - sendError(res,500,-1,err.message || "Some error occurred while retrieving users."); - }); + User.find(condition, {hashPass: false}) + .then(data => { + sendMessage(res, 1, data) + }) + .catch(err => { + sendError(res,500,-1,err.message || "Some error occurred while retrieving users."); + }); + } }; // Find a single User with an id exports.findOne = (req, res) => { + checkFormat(req, res); const id = req.params.id; User.findById(id, {hashPass: false}) @@ -98,6 +116,7 @@ exports.findOne = (req, res) => { // Update a User by the id in the request exports.update = (req, res) => { + checkFormat(req, res); if (!req.body) { sendError(res,400,-1,"Data to update can not be empty!"); } else{ @@ -119,6 +138,7 @@ exports.update = (req, res) => { // Delete a User with the specified id in the request exports.delete = (req, res) => { + checkFormat(req, res); const id = req.params.id; User.findByIdAndRemove(id) @@ -136,6 +156,7 @@ exports.delete = (req, res) => { // Delete all Users from the database. exports.deleteAll = (req, res) => { + checkFormat(req, res); User.deleteMany({}) .then(data => { sendMessage(res, 1,{ diff --git a/backend/app/models/user.model.js b/backend/app/models/user.model.js index bf8a5c8..fe29d74 100644 --- a/backend/app/models/user.model.js +++ b/backend/app/models/user.model.js @@ -14,5 +14,5 @@ module.exports = mongoose => { return object; }); - return User = mongoose.model("user", schema); + return mongoose.model("user", schema); }; diff --git a/backend/app/routes/user.routes.js b/backend/app/routes/user.routes.js index 7eee3e1..b3ba76f 100644 --- a/backend/app/routes/user.routes.js +++ b/backend/app/routes/user.routes.js @@ -23,5 +23,8 @@ module.exports = app => { // Authenticate a User router.post("/auth", users.auth); + // Disconnect a User + router.delete("/auth/disconnect", users.disconnect); + app.use('/api/users', router); }; diff --git a/backend/package.json b/backend/package.json index 1316b91..15a6c33 100644 --- a/backend/package.json +++ b/backend/package.json @@ -16,5 +16,6 @@ "express": "^4.17.1", "jsonwebtoken": "^8.5.1", "mongoose": "^6.0.12" - } + }, + "devDependencies": {} }