-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
372 lines (321 loc) · 9.93 KB
/
Copy pathserver.js
File metadata and controls
372 lines (321 loc) · 9.93 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
require('dotenv').config();
const app = express();
const PORT = 5000;
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key';
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET || 'session_secret_key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 * 60 }
}));
// In-memory database
let users = [
{
id: 1,
username: 'testuser',
password: '$2a$10$N9qo8uLOickgx2ZMRZoMye', // bcrypt hashed "testpass123"
email: 'test@example.com'
}
];
let books = [
{
ISBN: '978-0-13-110362-7',
author: 'Robert C. Martin',
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
reviews: []
},
{
ISBN: '978-0-201-63361-0',
author: 'Gang of Four',
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
reviews: []
},
{
ISBN: '978-0-201-71088-8',
author: 'Steve McConnell',
title: 'Code Complete: A Practical Handbook of Software Construction',
reviews: []
},
{
ISBN: '978-1-617-29476-5',
author: 'Kyle Simpson',
title: 'You Don\'t Know JS Yet',
reviews: []
},
{
ISBN: '978-0-596-00712-6',
author: 'Douglas Crockford',
title: 'JavaScript: The Good Parts',
reviews: []
}
];
let reviews = [];
let reviewId = 1;
// ============ AUTHENTICATION MIDDLEWARE ============
// JWT Authentication Middleware
const verifyJWT = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(403).json({ message: 'No token provided' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ message: 'Invalid token' });
}
};
// Session Authentication Middleware
const verifySession = (req, res, next) => {
if (!req.session.user) {
return res.status(401).json({ message: 'Not authenticated. Please login first.' });
}
req.user = req.session.user;
next();
};
// ============ USER ENDPOINTS ============
// Register endpoint
app.post('/api/v1/register', async (req, res) => {
try {
const { username, password, email } = req.body;
if (!username || !password || !email) {
return res.status(400).json({ message: 'Username, password, and email are required' });
}
// Check if user already exists
if (users.find(u => u.username === username)) {
return res.status(400).json({ message: 'User already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Create new user
const newUser = {
id: users.length + 1,
username,
password: hashedPassword,
email
};
users.push(newUser);
res.status(201).json({
message: 'User registered successfully',
user: {
id: newUser.id,
username: newUser.username,
email: newUser.email
}
});
} catch (error) {
res.status(500).json({ message: 'Error registering user', error: error.message });
}
});
// Login endpoint (returns JWT + Session)
app.post('/api/v1/login', async (req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: 'Username and password are required' });
}
// Find user
const user = users.find(u => u.username === username);
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// Compare password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// Create JWT token
const token = jwt.sign(
{ id: user.id, username: user.username, email: user.email },
JWT_SECRET,
{ expiresIn: '1h' }
);
// Create session
req.session.user = {
id: user.id,
username: user.username,
email: user.email
};
res.status(200).json({
message: 'Login successful',
token: token,
user: {
id: user.id,
username: user.username,
email: user.email
}
});
} catch (error) {
res.status(500).json({ message: 'Error logging in', error: error.message });
}
});
// Logout endpoint
app.post('/api/v1/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ message: 'Error logging out' });
}
res.status(200).json({ message: 'Logged out successfully' });
});
});
// ============ BOOK ENDPOINTS (PUBLIC) ============
// Task 1: Get all books
app.get('/api/v1/books', (req, res) => {
try {
const bookList = books.map(book => ({
ISBN: book.ISBN,
author: book.author,
title: book.title,
reviews: book.reviews
}));
res.status(200).json(bookList);
} catch (error) {
res.status(500).json({ message: 'Error fetching books', error: error.message });
}
});
// Task 2: Get book by ISBN
app.get('/api/v1/books/isbn/:isbn', (req, res) => {
try {
const { isbn } = req.params;
const book = books.find(b => b.ISBN === isbn);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.status(200).json(book);
} catch (error) {
res.status(500).json({ message: 'Error fetching book', error: error.message });
}
});
// Task 3: Get books by author
app.get('/api/v1/books/author/:author', (req, res) => {
try {
const { author } = req.params;
const authorBooks = books.filter(b => b.author.toLowerCase().includes(author.toLowerCase()));
if (authorBooks.length === 0) {
return res.status(404).json({ message: 'No books found by this author' });
}
res.status(200).json(authorBooks);
} catch (error) {
res.status(500).json({ message: 'Error fetching books by author', error: error.message });
}
});
// Task 4: Get books by title
app.get('/api/v1/books/title/:title', (req, res) => {
try {
const { title } = req.params;
const titleBooks = books.filter(b => b.title.toLowerCase().includes(title.toLowerCase()));
if (titleBooks.length === 0) {
return res.status(404).json({ message: 'No books found with this title' });
}
res.status(200).json(titleBooks);
} catch (error) {
res.status(500).json({ message: 'Error fetching books by title', error: error.message });
}
});
// Task 5: Get book reviews
app.get('/api/v1/reviews/isbn/:isbn', (req, res) => {
try {
const { isbn } = req.params;
const book = books.find(b => b.ISBN === isbn);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.status(200).json({
ISBN: book.ISBN,
title: book.title,
reviews: book.reviews
});
} catch (error) {
res.status(500).json({ message: 'Error fetching reviews', error: error.message });
}
});
// ============ REVIEW ENDPOINTS (AUTHENTICATED) ============
// Task 8: Add or Modify a review (requires authentication)
app.post('/api/v1/reviews/isbn/:isbn', verifySession, (req, res) => {
try {
const { isbn } = req.params;
const { review } = req.body;
if (!review) {
return res.status(400).json({ message: 'Review text is required' });
}
const book = books.find(b => b.ISBN === isbn);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
// Check if user already has a review for this book
const existingReview = book.reviews.find(r => r.username === req.user.username);
if (existingReview) {
// Modify existing review
existingReview.review = review;
existingReview.timestamp = new Date();
res.status(200).json({
message: 'Review updated successfully',
review: existingReview
});
} else {
// Add new review
const newReview = {
username: req.user.username,
review: review,
timestamp: new Date()
};
book.reviews.push(newReview);
res.status(201).json({
message: 'Review added successfully',
review: newReview
});
}
} catch (error) {
res.status(500).json({ message: 'Error adding/updating review', error: error.message });
}
});
// Task 9: Delete a review (requires authentication)
app.delete('/api/v1/reviews/isbn/:isbn', verifySession, (req, res) => {
try {
const { isbn } = req.params;
const book = books.find(b => b.ISBN === isbn);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
const reviewIndex = book.reviews.findIndex(r => r.username === req.user.username);
if (reviewIndex === -1) {
return res.status(404).json({ message: 'Review not found for this user' });
}
const deletedReview = book.reviews.splice(reviewIndex, 1);
res.status(200).json({
message: 'Review deleted successfully',
deletedReview: deletedReview[0]
});
} catch (error) {
res.status(500).json({ message: 'Error deleting review', error: error.message });
}
});
// Health check endpoint
app.get('/api/v1/health', (req, res) => {
res.status(200).json({ message: 'Server is running' });
});
// Start server
app.listen(PORT, () => {
console.log(`Book Review API Server running on http://localhost:${PORT}`);
console.log('Available endpoints:');
console.log(' POST /api/v1/register');
console.log(' POST /api/v1/login');
console.log(' POST /api/v1/logout');
console.log(' GET /api/v1/books');
console.log(' GET /api/v1/books/isbn/:isbn');
console.log(' GET /api/v1/books/author/:author');
console.log(' GET /api/v1/books/title/:title');
console.log(' GET /api/v1/reviews/isbn/:isbn');
console.log(' POST /api/v1/reviews/isbn/:isbn (authenticated)');
console.log(' DELETE /api/v1/reviews/isbn/:isbn (authenticated)');
});
module.exports = app;