// Get the authorization token from the request header
functioncheckToken(req,res,next,sql){
/**
* Get the authorization token from the request header
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('mysql').Connection} sql
* @param {Function} cb the callback function to call only if the token is valid. There are no parameters.
*/
functioncheckToken(req,res,sql,cb){
varauth=req.get('Authorization')
if(!auth){
res.status(403).json({error:{code:403,message:"No Authorization header found, please add a Authorization header. If you don't have one, then do nothing lol"}})
sql.query("SELECT * FROM Auth WHERE token = ?",token,async(err,result)=>{
if(err){
console.error(err)
res.status(503).json({error:{code:503,message:"Error while getting token list for authentificating."}})
renderError(res,500,"Internal Server Error")
}else{
if(result.length<1){
res.status(401).json({error:{code:401,message:"Authorization Token not found."}})
renderError(res,401,"Authorization Token not found.")
}else{
if(result[0].validate==0){
res.status(403).json({error:{code:403,message:"Your Token is not validated."}})
renderError(res,403,"Authorization Token not validated.")
}else{
console.log('Connexion from '+result[0].description);
next()
cb();
}
}
}
});
}else{
res.status(403).json({error:{code:403,message:"Token not found in Authorization header, please set a Token in Authorization header like this: 'Authorization: Basic [token]'."}})
renderError(res,403,"Token not found in Authorization header, please set a Token in Authorization header like this: 'Authorization: Basic [token]'.")
}
}
}
/**
* Render a JSON response for an error
* @param {import('express').Response} res
* @param {Number} status
* @param {String} message
*/
functionrenderError(res,status,message){
res.status(status||500).json({
error:{
...
...
@@ -73,7 +86,7 @@ const app = express()
app.use(function(req,res,next){
varua=req.get('User-Agent')
if(!ua){
res.status(403).json({error:{code:403,message:"No User-Agent found, please add a user-agent to something I can understand!"}})
renderError(res,403,"No User-Agent header found, please add a User-Agent header.")