63 lines
1.6 KiB
JavaScript
63 lines
1.6 KiB
JavaScript
const path = require('path');
|
|
const fs = require('fs');
|
|
const db = require('./database');
|
|
|
|
module.exports = app => {
|
|
const methodsPath = path.resolve(__dirname, '../methods');
|
|
const methodsDir = fs.readdirSync(methodsPath);
|
|
const methods = [];
|
|
|
|
// Get all methods
|
|
methodsDir.forEach(method => {
|
|
methods.push(method.replace('.js', ''));
|
|
});
|
|
|
|
// Auth middleware
|
|
const paths = [];
|
|
for (let method of methods)
|
|
paths.push(`/api/${method}/*`);
|
|
|
|
app.use(paths, async function(request, response, next) {
|
|
const authorization = getToken(request);
|
|
const query = `SELECT userId, ttl, created
|
|
FROM salix.AccessToken WHERE id = ?`;
|
|
|
|
try {
|
|
const authToken = await db.findOne(query, [authorization]);
|
|
|
|
if (!authToken || isTokenExpired(authToken.created, authToken.ttl))
|
|
throw new Error('Invalid authorization token');
|
|
|
|
next();
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
function getToken(request) {
|
|
const headers = request.headers;
|
|
const params = request.query;
|
|
|
|
if (headers.authorization)
|
|
params.authorization = headers.authorization;
|
|
|
|
return headers.authorization || params.authorization;
|
|
}
|
|
|
|
function isTokenExpired(created, ttl) {
|
|
const date = new Date(created);
|
|
const currentDate = new Date();
|
|
|
|
date.setSeconds(date.getSeconds() + ttl);
|
|
|
|
if (currentDate > date)
|
|
return true;
|
|
|
|
return false;
|
|
}
|
|
|
|
// Mount methods
|
|
for (let method of methods)
|
|
require(`../methods/${method}`)(app);
|
|
};
|