WikiLerni/middleware/auth.js

37 lines
1.1 KiB
JavaScript

const jwt=require("jsonwebtoken");
const config=require("../config/main.js");
const userTools=require("../controllers/user.js");
const txt = require("../lang/"+config.adminLang+"/general");
module.exports = async (req, res, next) =>
{
try
{
if(!req.headers.authorization)
throw { message: txt.failAuthHeader, status:401 };
else
{
const token=req.headers.authorization.split(" ")[1]; // Le header contient "Bearer" avant le token lui-même.
const connectedUser=await userTools.checkTokenUser(token);
if(connectedUser===false)
throw { message: txt.failAuthToken, status:403 };
else
{
if (req.body.UserId && req.body.UserId !== connectedUser.User.id && connectedUser.User.status==="user")
throw { message: txt.failAuthId+req.body.UserId +" vs "+connectedUser.User.id, status:403 };
else
{
req.connectedUser=connectedUser;
next();
}
}
}
}
catch(e)
{
next(e);
}
};