Files
LuHost/middleware/auth.js
Nathan Schneider 3aed09b60f Initial commit: LuHost - Luanti Server Management Web Interface
A modern web interface for Luanti (Minetest) server management with ContentDB integration.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-23 17:32:37 -06:00

61 lines
1.9 KiB
JavaScript

// Authentication middleware
const AuthManager = require('../utils/auth');
const authManager = new AuthManager();
// Initialize auth manager
authManager.initialize().catch(console.error);
async function requireAuth(req, res, next) {
if (req.session && req.session.user) {
// User is authenticated
return next();
} else {
// User is not authenticated - check if this is first user setup
try {
const isFirstUser = await authManager.isFirstUser();
if (isFirstUser) {
// No users exist yet - redirect to registration
if (req.headers.accept && req.headers.accept.includes('application/json')) {
return res.status(401).json({ error: 'No users configured. Please complete setup.' });
} else {
return res.redirect('/register');
}
} else {
// Users exist but this person isn't authenticated
if (req.headers.accept && req.headers.accept.includes('application/json')) {
return res.status(401).json({ error: 'Authentication required' });
} else {
return res.redirect('/login?redirect=' + encodeURIComponent(req.originalUrl));
}
}
} catch (error) {
console.error('Error checking first user in auth middleware:', error);
// Fallback to login on error
return res.redirect('/login?redirect=' + encodeURIComponent(req.originalUrl));
}
}
}
function redirectIfAuthenticated(req, res, next) {
if (req.session && req.session.user) {
// User is already authenticated, redirect to dashboard
return res.redirect('/');
} else {
// User is not authenticated, continue to login/register
return next();
}
}
function attachUser(req, res, next) {
// Make user available to templates
res.locals.user = req.session ? req.session.user : null;
res.locals.isAuthenticated = !!(req.session && req.session.user);
next();
}
module.exports = {
requireAuth,
redirectIfAuthenticated,
attachUser
};