-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
171 lines (141 loc) · 5.66 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import express from 'express';
import bodyParser from 'body-parser';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import db from './db.js';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import cookieParser from 'cookie-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
const PORT = process.env.PORT || 3000;
const SECRET_KEY = 'your_secret_key';
// Get __dirname equivalent in ES6
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Middleware to verify token
const verifyToken = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(403).json({ error: 'No token provided' });
}
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.userId = decoded.id;
next();
});
};
// Register user
app.post('/api/register', (req, res) => {
const { hidden_email, hidden_username, hidden_password } = req.body;
const hashedPassword = bcrypt.hashSync(hidden_password, 8);
console.log('Hashed password:', hashedPassword);
const sql = 'INSERT INTO users (email, username, password) VALUES (?, ?, ?)';
const params = [hidden_email, hidden_username, hashedPassword];
db.run(sql, params, function (err) {
if (err) {
console.error('Error during registration:', err.message);
return res.redirect('/register?error=Registration failed');
}
console.log('User registered with ID:', this.lastID);
const token = jwt.sign({ id: this.lastID }, SECRET_KEY, { expiresIn: 86400 }); // 24 hours
res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });
return res.redirect('/login');
});
});
// Login user
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const sql = 'SELECT * FROM users WHERE username = ?';
const params = [username];
db.get(sql, params, (err, user) => {
if (err) {
console.error('Error during login:', err.message);
return res.redirect('/login?error=Login failed');
}
if (!user) {
return res.redirect('/login?error=User not found');
}
const passwordIsValid = bcrypt.compareSync(password, user.password);
if (!passwordIsValid) {
return res.redirect('/login?error=Invalid password');
}
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: 86400 }); // 24 hours
res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });
res.cookie('username', username, { httpOnly: false, secure: false, sameSite: 'Strict' });
return res.redirect('/home');
});
});
// Fetch tasks for a user
app.get('/api/tasks', verifyToken, (req, res) => {
const { category } = req.query;
const sql = 'SELECT * FROM tasks WHERE user_id = ? AND category = ?';
const params = [req.userId, category];
console.log(`Fetching tasks for user_id: ${req.userId} and category: ${category}`); // Log the query parameters
db.all(sql, params, (err, rows) => {
if (err) {
console.error('Error loading tasks:', err.message);
return res.status(400).json({ error: 'Failed to load tasks', details: err.message });
}
console.log('Tasks fetched:', rows); // Log the fetched tasks
res.status(200).json({ tasks: rows });
});
});
// Add a new task
app.post('/api/tasks', verifyToken, (req, res) => {
const { category, content } = req.body;
const sql = 'INSERT INTO tasks (user_id, category, content) VALUES (?, ?, ?)';
const params = [req.userId, category, content];
db.run(sql, params, function (err) {
if (err) {
console.error('Error adding task:', err.message);
return res.status(400).json({ error: 'Failed to add task', details: err.message });
}
res.status(201).json({ message: 'Task added successfully', taskId: this.lastID });
});
});
// Update an existing task
app.put('/api/tasks/:id', verifyToken, (req, res) => {
const { id } = req.params;
const { content } = req.body;
const sql = 'UPDATE tasks SET content = ? WHERE id = ? AND user_id = ?';
const params = [content, id, req.userId];
db.run(sql, params, function (err) {
if (err) {
console.error('Error updating task:', err.message);
return res.status(400).json({ error: 'Failed to update task', details: err.message });
}
res.status(200).json({ message: 'Task updated successfully' });
});
});
// Delete an existing task
app.delete('/api/tasks/:id', verifyToken, (req, res) => {
const { id } = req.params;
const sql = 'DELETE FROM tasks WHERE id = ? AND user_id = ?';
const params = [id, req.userId];
db.run(sql, params, function (err) {
if (err) {
console.error('Error deleting task:', err.message);
return res.status(400).json({ error: 'Failed to delete task', details: err.message });
}
res.status(200).json({ message: 'Task deleted successfully' });
});
});
// Serve HTML files
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'login.html'));
});
app.get('/home', verifyToken, (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'home.html'));
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});