56 lines
1.5 KiB
JavaScript
56 lines
1.5 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 = ?`;
|
|
console.log('auth');
|
|
|
|
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) {
|
|
return request.headers.authorization || request.query.authorization;
|
|
}
|
|
|
|
function isTokenExpired(created, ttl) {
|
|
let date = new Date(created);
|
|
let currentDate = new Date();
|
|
|
|
date.setSeconds(date.getSeconds() + ttl);
|
|
|
|
if (currentDate > date)
|
|
return true;
|
|
}
|
|
|
|
// Mount methods
|
|
for (let method of methods)
|
|
require(`../methods/${method}`)(app);
|
|
};
|