-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (67 loc) · 2.76 KB
/
index.js
File metadata and controls
84 lines (67 loc) · 2.76 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
const express = require('express');
const cors = require('cors');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const { signUp, login, getProfile, getUsers, updateProfile } = require('./controller/userController');
const profileRoute = require('./routes/profileRoute');
const port = process.env.PORT || 4000;
const JWT_SECRET = process.env.SECRETKEY || '1A2B3C4D5E6F';
app.use(cors({
origin: ['http://localhost:5173', 'https://francify-online-store.vercel.app'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
optionsSuccessStatus: 200 // For legacy browser support
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('MongoDB connected...'))
.catch(err => console.error('MongoDB connection error:', err));
// Removed inline user schema and model definition
const User = require('./model/user');
app.options('/signup', (req, res) => {
res.sendStatus(200);
});
app.post('/signup',signUp);
app.post('/login', login);
// Modified /profile route to use authentication middleware and pass user id to getProfile
const authenticateUser = require('./middleware/auth');
app.get('/profile', authenticateUser, getProfile);
app.put('/profile', authenticateUser, updateProfile); // replace updateProfile with your actual handler
app.get('/users', getUsers);
app.use('/', profileRoute);
// Admin page route - accessible only to realadmin@gmail.com
// Middleware to authenticate and authorize admin by email
const authenticateAdmin = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).json({ message: 'Authorization header missing' });
const token = authHeader.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Token missing' });
try {
const decoded = jwt.verify(token, JWT_SECRET);
// Check for admin email or isAdmin property
if (decoded.email !== 'chikamsofavoured@gmail.com' && !decoded.isAdmin) {
return res.status(403).json({ message: 'Access forbidden: Admins only' });
}
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid or expired token' });
}
};
// Admin route
app.get('/admin', authenticateAdmin, (req, res) => {
res.status(200).json({ message: 'Welcome to the admin page' });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
res.status(500).json({ message: 'Internal Server Error' });
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});