refactor admin api auth

This commit is contained in:
AlecM33
2022-12-10 23:27:23 -05:00
parent 9ef9141513
commit fe84db12fb
2 changed files with 25 additions and 27 deletions

View File

@@ -7,20 +7,8 @@ const gameManager = new (require('../modules/GameManager.js'))().getInstance();
const globals = require('../config/globals.js');
const cors = require('cors');
const KEY = process.env.NODE_ENV.trim() === 'development'
? globals.MOCK_AUTH
: process.env.ADMIN_KEY;
router.use(cors(globals.CORS));
router.use((req, res, next) => {
if (isAuthorized(req)) {
next();
} else {
res.status(401).send('You are not authorized to make this request.');
}
});
router.post('/sockets/broadcast', (req, res, next) => {
globals.CONTENT_TYPE_VALIDATOR(req, res, next);
});
@@ -40,16 +28,4 @@ router.get('/games/state', function (req, res) {
res.status(200).send(gamesArray);
});
/* validates Bearer Auth */
function isAuthorized (req) {
const header = req.headers.authorization;
if (header) {
const token = header.split(/\s+/).pop() || '';
const decodedToken = Buffer.from(token, 'base64').toString();
return decodedToken.trim() === KEY.trim();
}
return false;
}
module.exports = router;

View File

@@ -6,6 +6,7 @@ const fs = require('fs');
const crypto = require('crypto');
const SocketManager = require('./SocketManager.js');
const GameManager = require('./GameManager.js');
const globals = require('../config/globals.js');
const { ENVIRONMENT } = require('../config/globals.js');
const rateLimit = require('express-rate-limit').default;
@@ -107,9 +108,15 @@ const ServerBootstrapper = {
app.use('/api/games', games);
app.use('/api/admin', admin);
if (process.env.NODE_ENV.trim() === 'production') {
app.use('/api/', standardRateLimit);
app.use('/api/admin', (req, res, next) => {
if (isAuthorized(req)) {
next();
} else {
res.status(401).send('You are not authorized to make this request.');
}
});
/* serve all the app's pages */
app.use('/manifest.json', standardRateLimit, (req, res) => {
@@ -143,4 +150,19 @@ const ServerBootstrapper = {
}
};
/* validates Bearer Auth */
function isAuthorized (req) {
const KEY = process.env.NODE_ENV.trim() === 'development'
? globals.MOCK_AUTH
: process.env.ADMIN_KEY;
const header = req.headers.authorization;
if (header) {
const token = header.split(/\s+/).pop() || '';
const decodedToken = Buffer.from(token, 'base64').toString();
return decodedToken.trim() === KEY.trim();
}
return false;
}
module.exports = ServerBootstrapper;