-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
157 lines (138 loc) · 4.73 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
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const bcrypt = require('bcrypt');
const { createAccount, makeTransaction, getAccountInformation } = require('./services/bankingService');
const PORT = process.env.PORT || 3000;
const sequelize = require('./sequelize');
const User = require('./models/user');
const app = express();
// Middleware setup
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
// Synchronize models with the database
sequelize.sync()
.then(() => {
console.log('Database synced successfully.');
})
.catch(err => {
console.error('Error syncing database:', err);
});
// Routes
app.get('/', (req, res) => {
res.render('index');
});
app.get('/login', (req, res) => {
res.render('login/index');
});
// Render the registration page
app.get('/register', (req, res) => {
res.render('register/register');
});
// Handle registration form submission
app.post('/register/process', async (req, res) => {
const { first_name, last_name, birthday, gender, email, phone, password, subject } = req.body;
if (!email || !password) {
// Handle empty email or password
res.status(400).send('Email and password are required');
return;
}
try {
const existingUser = await User.findOne({ where: { email } });
if (existingUser) {
res.status(400).send('User already exists');
return;
}
// Hash the password
const passwordHash = bcrypt.hashSync(password, 10);
// Create the user in the database
await User.create({ first_name, last_name, birthday, gender, email, phone, password: passwordHash, subject });
res.redirect('/login'); // Redirect to the login page after successful registration
} catch (err) {
console.error('Error creating user:', err);
res.status(500).send('Error creating user');
}
});
// Login route
app.post('/login', async (req, res) => {
const { email, pass } = req.body;
try {
// Find the user by email
const user = await User.findOne({ where: { email } });
if (user) {
// Compare the password hash
if (bcrypt.compareSync(pass, user.password)) {
// Passwords match, set session user and redirect
req.session.user = user;
res.redirect('/dashboard');
return;
}
}
// Either user doesn't exist or passwords don't match
res.redirect('/login');
} catch (err) {
console.error('Error logging in:', err);
res.status(500).send('Error logging in');
}
});
// Dashboard route
app.get('/dashboard', async (req, res) => {
// Check if the user is logged in (authenticated)
if (!req.session.user) {
// If not logged in, redirect to the login page
res.redirect('/login');
return;
}
// Assuming you have a session variable containing the user ID
const userId = req.session.user.id;
try {
// Fetch account information for the logged-in user
const accountInfo = await getAccountInformation(userId);
// Render the dashboard template from the dashboard directory
res.render('dashboard/dashboard', { user: accountInfo });
} catch (error) {
// Handle errors
console.error('Error fetching account information:', error);
res.status(500).render('error', { error: 'An error occurred while fetching account information' });
}
});
// Create account route
app.post('/accounts', async (req, res) => {
const { userId, accountNumber } = req.body;
try {
const account = await createAccount(userId, accountNumber);
res.json(account);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Make transaction route
app.post('/transactions', async (req, res) => {
const { userId, accountId, amount, description, type } = req.body;
try {
const transaction = await makeTransaction(userId, accountId, amount, description, type);
res.json(transaction);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get account information route
app.get('/accounts/:userId', async (req, res) => {
const userId = req.params.userId;
try {
const accountInfo = await getAccountInformation(userId);
res.json(accountInfo);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});