-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
109 lines (94 loc) · 3.17 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
const express = require('express');
const cors = require('cors');
const basicAuth = require('express-basic-auth');
const dotenv = require('dotenv');
// Authentication
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
dotenv.config();
const app = express();
// User CORS and BodyParser
const allowedOrigins = ['http://roubekas.com', 'http://www.roubekas.com', 'https://roubekas.com', 'https://www.roubekas.com', 'http://localhost:3000', 'http://localhost:3001', 'http://localhost:3002'];
app.use(cors({
origin: function(origin, callback){
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
return callback(new Error('CORS policy violation'), false);
}
return callback(null, true);
}
}));
// Middleware to remove unnecessary Permissions-Policy headers
app.use((req, res, next) => {
res.removeHeader('Permissions-Policy');
next();
});
// Export JWT middleware
module.exports.jwtMiddleware = function (req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader) return res.status(401).send('No token provided');
// Extract the token from the Authorization header
const tokenParts = authHeader.split(' ');
if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
return res.status(401).send('Malformed token');
}
const token = tokenParts[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
console.log("Token:", token);
if (err) {
console.log("JWT Error:", err);
return res.status(401).send('Unauthorized');
}
// User is authenticated
req.user = decoded;
next();
});
};
app.use(express.json());
// Connect to DB
const db = require("./app/models/");
db.sequelize.sync();
// An endpoint to authenticate users
app.post('/api/auth', async (req, res) => {
const { username, password } = req.body;
// Fetch hashed password and userID from database
const query = "SELECT password, userID FROM Users WHERE username = ?";
let [rows] = await db.sequelize.query(query, {
replacements: [username]
});
const hashedPassword = rows[0]?.password;
const userID = rows[0]?.userID;
// Verify password
const validCredentials = bcrypt.compareSync(password, hashedPassword);
if (validCredentials) {
const token = jwt.sign({ username, userID }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.status(200).json({ token });
} else {
res.status(401).send('Unauthorized');
}
});
// Routing for trades
require("./app/routes/Journal.routes")(app);
// Routing for Users
require("./app/routes/User.routes")(app);
// Routing for Transactions
require("./app/routes/Transactions.routes")(app);
// Routing for Accounts
require("./app/routes/Accounts.routes")(app);
const PORT = process.env.PORT || 3001;
const server = app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// For graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received. Shutting down gracefully');
server.close(() => {
console.log('Process terminated');
});
});
process.on('SIGINT', () => {
console.log('SIGINT received. Shutting down gracefully');
server.close(() => {
console.log('Process terminated');
});
});