-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
81 lines (66 loc) · 2.47 KB
/
index.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
import { PrismaClient } from '@prisma/client';
import express from 'express';
import cors from 'cors';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.config();
import { userRouter } from './routes/userRouter.js';
import { reservationRouter } from './routes/reservationRouter.js';
import { tripRouter } from './routes/tripRouter.js';
// import { profileRouter } from './routes/profileRouter.js';
const app = express();
export const prisma = new PrismaClient();
app.use(cors());
app.use(express.json());
// Default route
app.get('/', async (req, res) => {
res.send({ success: true, post: 'Welcome to the Astro Planner Server' });
});
app.use(async (req, res, next) => {
// check if there's an auth token in the header and console it
try {
// Check if the request has an "Authorization" header
if (!req.headers.authorization) {
return next(); // If not, continue to the next middleware
}
// Split the "Authorization" header to get the token (assuming it's in the format "Bearer <token>")
const token = req.headers.authorization.split(' ')[1];
// Verify the token using a JWT (JSON Web Token) library with a secret key
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
// Use the userId from the decoded token to find the corresponding user in the database
const user = await prisma.user.findUnique({
where: {
id: userId,
},
});
// If no user is found with the given userId, continue to the next middleware
if (!user) {
return next();
}
// Remove the "password" property from the user object for security (assuming it's sensitive)
delete user.password;
// Attach the user object to the request object for later use in route handlers
req.user = user;
// Continue to the next middleware or route handler
next();
} catch (error) {
// Handle any errors that occur during authentication
res.send({ success: false, error: error.message });
}
});
app.use('/users', userRouter);
app.use('/reservations', reservationRouter);
app.use('/trips', tripRouter);
// app.use("/profile", profileRouter);
// 404 Route Not Found
app.use((req, res, next) => {
res.status(404).send({ success: false, error: 'Route does not exist' });
});
// Error Handling Middleware
app.use((error, req, res, next) => {
res.send({ success: false, error: error.message });
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});