forked from pierce403/dracoria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
165 lines (140 loc) · 4.93 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Load environment variables
require("dotenv").config();
const mongoose = require("mongoose");
const express = require("express");
const session = require("express-session");
const MongoStore = require('connect-mongo');
const authRoutes = require("./routes/authRoutes");
const walletAuthRoutes = require('./routes/walletAuthRoutes'); // Added for Ethereum wallet authentication
const apiRoutes = require('./routes/apiRoutes'); // Added for AJAX API routes
const adminRoutes = require('./routes/adminRoutes'); // Added for Admin panel
const http = require('http');
const { Server } = require("socket.io");
const { isAuthenticated } = require('./routes/middleware/authMiddleware'); // Import isAuthenticated middleware
const isAdmin = require('./routes/middleware/adminMiddleware'); // Import isAdmin middleware
const Dragon = require('./models/Dragon'); // Import Dragon model
const { checkAndGrowFruits } = require('./services/gardenService'); // Import checkAndGrowFruits function
if (!process.env.DATABASE_URL || !process.env.SESSION_SECRET) {
console.error("Error: config environment variables not set. Please create/edit .env configuration file.");
process.exit(-1);
}
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const port = process.env.PORT || 3000;
// Middleware to parse request bodies
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Setting the templating engine to EJS
app.set("view engine", "ejs");
// Serve static files
app.use(express.static("public"));
// Database connection
mongoose
.connect(process.env.DATABASE_URL)
.then(() => {
console.log("Database connected successfully");
})
.catch((err) => {
console.error(`Database connection error: ${err.message}`);
console.error(err.stack);
process.exit(1);
});
// Session configuration with connect-mongo
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.DATABASE_URL }),
}),
);
// Request logging middleware
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
// Logging session creation and destruction
app.use((req, res, next) => {
const sess = req.session;
// Make session available to all views
res.locals.session = sess;
if (!sess.views) {
sess.views = 1;
console.log("Session created at: ", new Date().toISOString());
} else {
sess.views++;
console.log(
`Session accessed again at: ${new Date().toISOString()}, Views: ${sess.views}, User ID: ${sess.userId || '(unauthenticated)'}`,
);
}
next();
});
// Authentication Routes
app.use(authRoutes);
// Wallet Authentication Routes - Added for Ethereum wallet authentication
app.use(walletAuthRoutes);
// API Routes for AJAX requests - Added for dashboard updates
app.use('/api', apiRoutes);
// Admin Routes - Added for Admin panel
app.use('/admin', adminRoutes);
// Socket.io event handling
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
// Example event handlers
socket.on('feedDragon', (data) => {
// Handle dragon feeding here and emit updates
io.emit('dragonUpdate', { hunger: data.newHungerLevel, happiness: data.newHappinessLevel });
});
socket.on('harvestFruit', (data) => {
// Handle fruit harvesting here and emit updates
io.emit('gardenUpdate', { fruitCount: data.newFruitCount });
});
});
// Root path response
app.get("/", (req, res) => {
if (req.session.userId) {
Dragon.findOne({ userId: req.session.userId }).then(dragon => {
res.render("index", { dragon: dragon || null });
}).catch(err => {
console.error(`Error fetching dragon for user ${req.session.userId}:`, err);
res.status(500).send("There was an error serving your request.");
});
} else {
res.render("index", { dragon: null });
}
});
// Dashboard route
app.get("/dashboard", isAuthenticated, (req, res) => {
res.render("dashboard");
});
// Schedule fruit growth check every hour
setInterval(() => {
checkAndGrowFruits().catch(err => {
console.error('Error in scheduled fruit growth check:', err.message);
console.error(err.stack);
});
}, 3600000); // 3600000 milliseconds = 1 hour
// If no routes handled the request, it's a 404
app.use((req, res, next) => {
res.status(404).send("Page not found.");
});
// Error handling
app.use((err, req, res, next) => {
console.error(`Unhandled application error: ${err.message}`);
console.error(err.stack);
res.status(500).send("There was an error serving your request.");
});
// Function to get the io instance
function getIo() {
return io;
}
// Exporting getIo to be used in other parts of the application
module.exports = { getIo };
// Replace app.listen with server.listen
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});