-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
95 lines (80 loc) · 3.38 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
// This is the main file for the CCL2 backend. All requests are handled here.
// This backend provides an API for the CCL2 frontend, which can access the API via HTTP requests. I use axios for this.
// Many routes in this file are protected with JWT, so that only logged-in users can access them.
// However, some routes are not protected, as they are used to display items to the user, but the user can not really do anything with them.
// Importing necessary libraries and modules
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { expressjwt: expressJwt } = require('express-jwt'); // JWT middleware for Express
const cookieParser = require('cookie-parser');
require('dotenv').config() // Loads environment variables from a .env file
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET; // Secret for JWT
// Instantiate Express app
const app = express();
// Configuration for CORS middleware
let corsOptions = {
// origin: 'https://cc221012-10141.node.fhstp.io',
origin: 'http://localhost:8081',
credentials: true,
};
// Use cors middleware with the specified options
app.use(cors(corsOptions));
// Parse JSON bodies for the app
app.use(bodyParser.json());
// Parse URL-encoded bodies
app.use(bodyParser.urlencoded({extended: true}));
// Parse Cookie header and populate req.cookies
app.use(cookieParser());
// Use express-jwt middleware
app.use(expressJwt({
secret: ACCESS_TOKEN_SECRET, // Secret for JWT
algorithms: ['HS256'], // Algorithms for JWT
credentialsRequired: true, // Specifies whether credentials are required
getToken: function fromHeaderOrQuerystring (req) { // Function to get token from header or query string
// If a cookie named "token" exists in the request, return it
if (req.cookies && req.cookies.token) {
console.log("req.cookies.token: " + req.cookies.token);
return req.cookies.token;
}
console.log('req.cookies: '+JSON.stringify(req.cookies));
return null; // Return null if no token cookie found
}
}).unless({
// Specifies paths that do not require an access token
path: [
'/',
'/register',
'/login',
'/listings',
{ url: /^\/listings\/item\/.*/, methods: ['GET'] }, // Regex for all paths that start with '/listings/item/'
'/listings/T',
'/listings/CT',
{ url: /^\/inventory\/user\/.*/, methods: ['GET'] }, // same thing for inventory
]
}));
// Default route
app.get('/', (req, res) => {
res.json({message: 'Welcome to the CCL2 Backend.'});
});
// The port the server will listen on
const PORT = process.env.PORT || 8080;
// Import routers
const indexRouter = require('./app/routes/indexRouter.js');
const userRouter = require('./app/routes/userRouter.js');
const listingRouter = require('./app/routes/listingRouter.js');
const inventoryRouter = require('./app/routes/inventoryRouter.js');
// Use the imported routers
app.use('/', indexRouter);
app.use('/users', userRouter);
app.use('/listings', listingRouter);
app.use('/inventory', inventoryRouter);
// Middleware to handle errors
app.use((err, req, res, next) => {
console.error(err.stack); // Log error stack
res.status(500).send('Server error!'); // Send server error response
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}.`);
});