-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
89 lines (77 loc) · 2.71 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
const express = require('express');
const path = require('path');
const session = require('express-session');
const passport = require('passport');
const MySQLStore = require('express-mysql-session')(session);
const bodyParser = require('body-parser');
const cors = require('cors');
const pool = require('./databaseConnection/database'); // Database pool connection
const cookieParser = require('cookie-parser');
require('dotenv').config();
const app = express();
const port = 3000// || process.env.PORT ;
// Session store options
const options = {
schema: {
tableName: 'sessions',
columnNames: {
session_id: 'sessionID',
expires: 'expires',
data: 'data'
}
}
};
// Create a session store using MySQL
const sessionStore = new MySQLStore(options, pool.promise());
// Middleware to parse cookies and JSON bodies
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Enable CORS with credentials to allow cookie usage across origins
app.use(cors({
origin: 'http://localhost:8080', // Your frontend origin
credentials: true, // Allow cookies and credentials to be shared
}));
// Session middleware configuration
app.use(session({
key: process.env.key, // Unique session key
secret: process.env.secret, // Secret used to sign the session cookie
store: sessionStore, // Store session in MySQL
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 30, // Set cookie lifespan (30 minutes)
httpOnly: true,
secure: false, // Set true if using HTTPS (adjust for production)
sameSite: 'lax',
},
}));
// Initialize Passport for authentication
app.use(passport.initialize());
app.use(passport.session());
// Authentication middleware
const isAuthenticated = (req, res, next) => req.isAuthenticated() ? next() : res.status(401).json({
message: 'Unauthorized access, please login.'
});
// Define authentication routes that should not require `isAuthenticated`
const authRoutes = ['/logout', '/auth'];
// Apply `isAuthenticated` to all `/api` routes except specified authentication routes
app.use('/api', (req, res, next) => {
console.log(req.path);
if (authRoutes.some(route => req.path.startsWith(route))) {
console.log('skipping');
// If the path starts with an authentication route, skip `isAuthenticated`
return next();
} else {
// Apply `isAuthenticated` to all other `/api` routes
console.log('authenticating');
return isAuthenticated(req, res, next);
}
});
// Import and use routes
const routes = require('./routes/index');
app.use('/api', routes); // Apply isAuthenticated globally to `/api` routes
// Start server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});