Skip to content

Commit

Permalink
Reorganize project files and directories
Browse files Browse the repository at this point in the history
  • Loading branch information
Ernest Paśnik committed Dec 11, 2023
1 parent b462e11 commit 08eb58e
Show file tree
Hide file tree
Showing 26 changed files with 765 additions and 550 deletions.
105 changes: 80 additions & 25 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
require('dotenv').config();

const fs = require('fs');
const express = require('express');
const session = require('express-session');
const minifyHTML = require('express-minify-html-2');
const bodyParser = require('body-parser');
const settings = require(__dirname + '/src/admin/settings');
const passport = require('passport');
const passportSteam = require('passport-steam');
const SteamStrategy = passportSteam.Strategy;
const SteamStrategy = require('passport-steam').Strategy;

const github = 'https://github.com/TeamHypersomnia';
const pressKit = `${github}/PressKit/blob/main/README.md#intro`;
const app = express();
const port = 3000;

passport.serializeUser(function (user, done) {
// Passport
passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser(function (obj, done) {
passport.deserializeUser((obj, done) => {
done(null, obj);
});

passport.use(new SteamStrategy({
returnURL: process.env.URL + 'auth/steam/return',
realm: process.env.URL,
apiKey: process.env.STEAM_APIKEY
},
function (identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
returnURL: process.env.URL + 'auth/steam/return',
realm: process.env.URL,
apiKey: process.env.STEAM_APIKEY
}, (identifier, profile, done) => {
process.nextTick(() => {
profile.identifier = identifier;
return done(null, profile);
});
}));

// Configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

Expand All @@ -39,11 +42,13 @@ app.use(session({
resave: true,
saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(minifyHTML({
override: true,
exceptionUrls: false,
Expand All @@ -56,14 +61,64 @@ app.use(minifyHTML({
}
}));

app.locals = {
arena: false,
version: 3
};
const obj = settings.load();
app.locals.alert = obj.alert;
// Settings
const ts = Math.floor(Date.now() / 1000);
app.locals.version = ts;
app.locals.alert = '';
try {
const content = fs.readFileSync(`./private/settings.json`, 'utf8');
const obj = JSON.parse(content);
app.locals.version = obj.version ? obj.version : ts;
app.locals.alert = obj.alert ? obj.alert : '';
} catch (error) {
console.error(error.message);
}

// Middleware
function usr(req, res, next) {
if (!req.isAuthenticated()) {
return res.redirect('/auth/steam');
}
return next();
}

function adm(req, res, next) {
if (!req.isAuthenticated()) {
return res.redirect('/auth/steam');
}
const admins = process.env.ADMINS.split(',');
if (!admins.includes(req.user.id)) {
return res.redirect('/');
}
return next();
}

require(__dirname + '/src/routes')(app, passport);
// Routes
app.use('/', require('./src/index'));
app.use('/guide', require('./src/guide'));
app.use('/arenas', require('./src/arenas'));
app.use('/weapons', require('./src/weapons'));
app.use('/servers', require('./src/servers'));
app.use('/profile', usr, require('./src/profile'));
app.use('/logout', require('./src/logout'));
app.use('/auth', require('./src/auth')(passport));
app.use('/disclaimer', require('./src/disclaimer'));
app.use('/cookie-policy', require('./src/cookie_policy'));
app.use('/contact', require('./src/contact'));
app.get('/press', (req, res) => res.redirect(pressKit));
app.use('/upload', require('./src/upload'));
app.get('/admin', adm, (req, res) => res.redirect('/admin/system'));
app.use('/admin/system', adm, require('./src/admin/system'));
app.use('/admin/visitors', adm, require('./src/admin/visitors'));
app.use('/admin/users', adm, require('./src/admin/users'));
app.use('/admin/creators', adm, require('./src/admin/creators'));
app.use('/admin/settings', adm, require('./src/admin/settings')(app.locals));
app.use((req, res) => res.status(404).render('404', {
page: 'Not Found',
user: req.user
}));

// Start
app.listen(port, () => {
console.log(`App listening on port ${port}`)
})
console.log(`App listening on port ${port}`);
});
85 changes: 85 additions & 0 deletions src/admin/creators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = `${__dirname}/../../private/authorized_mappers.json`;

function loadCreators() {
try {
const d = fs.readFileSync(path, 'utf8');
const obj = JSON.parse(d);
return obj;
} catch (error) {
console.error(error.message);
return {};
}
}

function saveCreators(obj) {
try {
const json = JSON.stringify(obj, null, 2);
fs.writeFileSync(path, json, 'utf8');
} catch (error) {
console.error(error.message);
}
}

function randomString(len) {
const c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < len; i++) {
const randomIndex = Math.floor(Math.random() * c.length);
result += c.charAt(randomIndex);
}
return result;
}

router.get('/', (req, res) => {
res.render('admin/creators', {
page: 'Creators',
user: req.user,
creators: loadCreators()
});
});

router.post('/', (req, res) => {
const obj = loadCreators();
obj[randomString(50)] = {
shorthand: req.body.shorthand,
allow_creating_new: false,
maps: []
};
saveCreators(obj);
res.redirect('/admin/creators');
});

router.get('/:shorthand', (req, res) => {
const obj = loadCreators();
const c = Object.values(obj).find((obj) => obj.shorthand === req.params.shorthand);
if (!c) {
return res.redirect('/admin/creators');
}
res.render('admin/creator', {
page: 'Creators',
user: req.user,
c: c
});
});

router.post('/:shorthand', (req, res) => {
const obj = loadCreators();
const k = Object.keys(obj).find((k) => obj[k].shorthand === req.params.shorthand);
if (!k) {
return res.redirect('/admin/creators');
}
if (req.body.delete === 'on') {
delete obj[k];
} else {
obj[k].shorthand = req.body.shorthand;
obj[k].allow_creating_new = req.body.allow_creating_new === 'yes';
obj[k].maps = req.body.arenas.split('\n').map((line) => line.trim());
}
saveCreators(obj);
res.redirect('/admin/creators');
});

module.exports = router;
58 changes: 38 additions & 20 deletions src/admin/settings.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,43 @@
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = __dirname + '/../../private/settings.json';
const path = `${__dirname}/../../private/settings.json`;

module.exports = {
load: function () {
try {
const fileContent = fs.readFileSync(path, 'utf8');
const obj = JSON.parse(fileContent);
return obj;
} catch (error) {
console.error(`Error reading settings: ${error.message}`);
return null;
}
},
function loadSettings() {
try {
const d = fs.readFileSync(path, 'utf8');
const obj = JSON.parse(d);
return obj;
} catch (error) {
console.error(error.message);
return {};
}
}

save: function (obj) {
try {
const json = JSON.stringify(obj, null, 2);
fs.writeFileSync(path, json, 'utf8');
} catch (error) {
console.error(`Error writing settings ${error.message}`);
return null;
}
function saveSettings(obj) {
try {
const json = JSON.stringify(obj, null, 2);
fs.writeFileSync(path, json, 'utf8');
} catch (error) {
console.error(error.message);
}
}

module.exports = function(locals) {
router.get('/', (req, res) => {
res.render('admin/settings', {
page: 'Settings',
user: req.user
});
});

router.post('/', (req, res) => {
const obj = loadSettings();
obj.alert = req.body.alert;
locals.alert = req.body.alert;
saveSettings(obj);
res.redirect('/admin/settings');
});

return router;
};
34 changes: 19 additions & 15 deletions src/admin/system.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const express = require('express');
const router = express.Router();
const os = require('os');

function formatUptime(uptime) {
Expand All @@ -11,18 +13,20 @@ function formatUptime(uptime) {
return `${h}:${m}:${s}`;
}

module.exports = {
getData: function () {
return {
hostname: os.hostname(),
loadavg: os.loadavg(),
machine: os.machine(),
type: os.type(),
release: os.release(),
uptime: formatUptime(os.uptime()),
usedmem: os.totalmem() - os.freemem(),
totalmem: os.totalmem(),
nodever: process.version,
};
}
};
router.get('/', (req, res) => {
res.render('admin/system', {
page: 'System',
user: req.user,
hostname: os.hostname(),
loadavg: os.loadavg(),
machine: os.machine(),
type: os.type(),
release: os.release(),
uptime: formatUptime(os.uptime()),
usedmem: os.totalmem() - os.freemem(),
totalmem: os.totalmem(),
node: process.version
});
});

module.exports = router;
36 changes: 36 additions & 0 deletions src/admin/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const express = require('express');
const router = express.Router();
const moment = require('moment');
const fs = require('fs');
const path = `${__dirname}/../../private/users.json`;

function loadUsers() {
try {
const d = fs.readFileSync(path, 'utf8');
const obj = JSON.parse(d);
return obj;
} catch (error) {
console.error(error.message);
return {};
}
}

router.get('/', (req, res) => {
const users = loadUsers();
const updatedUsers = Object.fromEntries(
Object.entries(users).map(([userId, user]) => [
userId,
{
...user,
lastLogin: moment(user.lastLogin * 1000).fromNow()
}
])
);
res.render('admin/users', {
page: 'Users',
user: req.user,
users: updatedUsers
});
});

module.exports = router;
11 changes: 11 additions & 0 deletions src/admin/visitors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
res.render('admin/visitors', {
page: 'Visitors',
user: req.user
});
});

module.exports = router;
Loading

0 comments on commit 08eb58e

Please sign in to comment.