forked from jinx-vi-0/BlogLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (74 loc) · 2.67 KB
/
app.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
require("dotenv").config();
const express = require("express");
const expressLayout = require("express-ejs-layouts");
const methodOverride = require("method-override");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const rfs = require("rotating-file-stream");
const passport = require('passport'); // Added passport for authentication
const flash = require('connect-flash'); // Added flash for storing flash messages
const connectDB = require("./server/config/db");
const { isActiveRoute } = require("./server/helpers/routeHelpers");
const morgan = require("morgan");
// Passport configuration
require('./server/config/passport')(passport); // Passport config to be created separately
const app = express();
const PORT = process.env.PORT || 5000;
const accessLogStream = rfs.createStream("application.log", {
interval: "1d",
path: "./logs",
});
app.use(morgan("combined", { stream: accessLogStream }));
// Connect to DB
app.use(session({
secret: 'your_secret_key', // Change this to your secret key
resave: false,
saveUninitialized: true,
}));
app.use(flash());
// Connect to MongoDB
connectDB();
// Middleware setup
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(morgan("dev"));
app.use(methodOverride("_method"));
// Session setup for storing user session data
app.use(
session({
secret: process.env.SESSION_SECRET || "keyboard cat", // Use SESSION_SECRET from .env
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI, // Use MongoDB Atlas URI from .env
}),
// cookie: { maxAge: new Date(Date.now() + 3600000) }// Uncomment if you want custom cookie expiry time
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session()); // Persist user sessions
// Global variables for flash messages
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error'); // Error messages from Passport
next();
});
// Static files
app.use(express.static("public"));
// Templating Engine
app.use(expressLayout);
app.set('layout', './layouts/main');
app.set('view engine', 'ejs');
// Helper for active route
app.locals.isActiveRoute = isActiveRoute;
// Routes
app.use('/', require('./server/routes/main'));
app.use('/', require('./server/routes/admin'));
// Start the server
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});