Commit 1c4cbe5d authored by Matthieu - Greep's avatar Matthieu - Greep

Update directory and methods for token check

parent 1cab9dfa
...@@ -20,37 +20,50 @@ const connection = mysql.createConnection({ ...@@ -20,37 +20,50 @@ const connection = mysql.createConnection({
connection.connect(); connection.connect();
// Get the authorization token from the request header /**
function checkToken(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.
*/
function checkToken(req, res, sql, cb){
var auth = req.get('Authorization') var auth = req.get('Authorization')
if (!auth){ 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"}}) renderError(res, 403, 'No authorization token provided');
return false;
} else { } else {
if (auth.includes('Basic ')){ if (auth.includes('Basic ')){
var token = auth.replace('Basic ', '') var token = auth.replace('Basic ', '')
sql.query("SELECT * FROM Auth WHERE token = ?", token, async (err, result)=>{ sql.query("SELECT * FROM Auth WHERE token = ?", token, async (err, result)=>{
if (err){ if (err){
console.error(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 { } else {
if (result.length < 1){ if (result.length < 1){
res.status(401).json({error: {code: 401, message: "Authorization Token not found."}}) renderError(res, 401, "Authorization Token not found.")
} else { } else {
if (result[0].validate == 0){ 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 { } else {
console.log('Connexion from '+ result[0].description); console.log('Connexion from '+ result[0].description);
next() cb();
} }
} }
} }
}); });
} else { } 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
*/
function renderError(res, status, message){ function renderError(res, status, message){
res.status(status || 500).json({ res.status(status || 500).json({
error: { error: {
...@@ -73,7 +86,7 @@ const app = express() ...@@ -73,7 +86,7 @@ const app = express()
app.use(function(req, res, next){ app.use(function(req, res, next){
var ua = req.get('User-Agent') var ua = req.get('User-Agent')
if (!ua){ 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.")
} else { } else {
var blacklistUA = JSON.parse(fs.readFileSync(path.join(__dirname, 'user-agent-blacklist.json'))) var blacklistUA = JSON.parse(fs.readFileSync(path.join(__dirname, 'user-agent-blacklist.json')))
var blacklisted = false var blacklisted = false
...@@ -86,7 +99,7 @@ app.use(function(req, res, next){ ...@@ -86,7 +99,7 @@ app.use(function(req, res, next){
if (blacklisted) { if (blacklisted) {
console.log('BLACKLISTED UA: ' + ua) console.log('BLACKLISTED UA: ' + ua)
res.status(403).json({error: {code: 403, message: "Your User-Agent '"+ ua +"' is blacklisted, please change it to something I can understand!"}}) renderError(res, 403, "Your User-Agent '"+ ua +"' is blacklisted, please change it.")
} else { } else {
next() next()
} }
...@@ -97,16 +110,8 @@ app.get('/', (req, res) => { ...@@ -97,16 +110,8 @@ app.get('/', (req, res) => {
res.json({'online': true}) res.json({'online': true})
}) })
// Set pages for requests that does not require a token fs.readdirSync(path.join(__dirname, 'route')).filter(file => file.endsWith('.js')).forEach(function(file) {
fs.readdirSync(path.join(__dirname, 'route', 'noToken')).filter(file => file.endsWith('.js')).forEach(function(file) { require(path.join(__dirname, 'route', file))(app, connection, checkToken, renderError)
require(path.join(__dirname, 'route', 'noToken', file))(app, connection, renderError)
});
// Set pages that require token
app.use((req,res,next)=>checkToken(req,res,next,connection));
fs.readdirSync(path.join(__dirname, 'route', 'token')).filter(file => file.endsWith('.js')).forEach(function(file) {
require(path.join(__dirname, 'route', 'token', file))(app, connection, checkToken, renderError)
}); });
// catch 404 and forward to error handler // catch 404 and forward to error handler
......
...@@ -5,7 +5,7 @@ const path = require('path'), ...@@ -5,7 +5,7 @@ const path = require('path'),
* @param {import('express').Express} app * @param {import('express').Express} app
* @param {import('mysql').Connection} sql * @param {import('mysql').Connection} sql
*/ */
module.exports = function(app, sql, errorHandler) { module.exports = function(app, sql, token, errorHandler) {
app.get('/'+scriptName, function(req, res) { app.get('/'+scriptName, function(req, res) {
const mapId = req.query.map; const mapId = req.query.map;
if (!mapId) { if (!mapId) {
......
const path = require('path'), const path = require('path'),
scriptName = path.basename(__filename).replace(/\.js$/i,''); scriptName = path.basename(__filename).replace(/\.js$/i,'');
module.exports = function(router) { module.exports = function(app) {
router.get('/'+scriptName, function(req, res) { app.get('/'+scriptName, function(req, res) {
res.json({status: "Test valid!"}); res.json({status: "Test valid!"});
}); });
}; };
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment