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

Update directory and methods for token check

parent 1cab9dfa
Loading
Loading
Loading
Loading
+25 −20
Original line number Diff line number Diff line
@@ -20,37 +20,50 @@ const connection = mysql.createConnection({

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')
    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 {
        if (auth.includes('Basic ')){
            var token = auth.replace('Basic ', '')
            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
 */
function renderError(res, status, message){
    res.status(status || 500).json({
        error: {
@@ -73,7 +86,7 @@ const app = express()
app.use(function(req, res, next){
    var ua = 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.")
    } else {
        var blacklistUA = JSON.parse(fs.readFileSync(path.join(__dirname, 'user-agent-blacklist.json')))
        var blacklisted = false
@@ -86,7 +99,7 @@ app.use(function(req, res, next){

        if (blacklisted) {
            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 {
            next()
        }
@@ -97,16 +110,8 @@ app.get('/', (req, res) => {
    res.json({'online': true})
})

// Set pages for requests that does not require a token
fs.readdirSync(path.join(__dirname, 'route', 'noToken')).filter(file => file.endsWith('.js')).forEach(function(file) {
    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)
fs.readdirSync(path.join(__dirname, 'route')).filter(file => file.endsWith('.js')).forEach(function(file) {
    require(path.join(__dirname, 'route', file))(app, connection, checkToken, renderError)
});

// catch 404 and forward to error handler
+1 −1
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ const path = require('path'),
 * @param {import('express').Express} app
 * @param {import('mysql').Connection} sql
 */
module.exports = function(app, sql, errorHandler) {
module.exports = function(app, sql, token, errorHandler) {
    app.get('/'+scriptName, function(req, res) {
        const mapId = req.query.map;
        if (!mapId) {
+2 −2
Original line number Diff line number Diff line
const path = require('path'),
    scriptName = path.basename(__filename).replace(/\.js$/i,'');

module.exports = function(router) {
    router.get('/'+scriptName, function(req, res) {
module.exports = function(app) {
    app.get('/'+scriptName, function(req, res) {
        res.json({status: "Test valid!"});
    });
};
 No newline at end of file