-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
256 lines (183 loc) · 6.19 KB
/
server.js
File metadata and controls
256 lines (183 loc) · 6.19 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
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
app.use(bodyParser.json());
// اتصال MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB mydatabase');
}).catch(err => {
console.error('Error connecting to MongoDB', err);
});
// تعريف مودل المستخدم باستخدام Mongoose
const UserSchema = new mongoose.Schema({
username: String,
password: String
});
const ProductSchema = new mongoose.Schema({
name: String,
price: Number
});
// Create Account schema and model
const accountSchema = new mongoose.Schema({
username: String,
password: String
});
const User = mongoose.model('User', UserSchema);
const Product = mongoose.model('Product', ProductSchema);
const Account = mongoose.model('Account', accountSchema);
// Middleware للتحقق من صحة JWT
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
jwt.verify(token, 'secret-key', (err, user) => {
if (err) {
return res.status(403).json({ error: 'Forbidden' });
}
req.user = user;
next();
});
}
// API to login and issue JWT
app.post('/api/login', cors(), async (req, res) => {
const { username, password } = req.body;
try {
// Validate username and password
const user = await User.findOne({ username, password });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Issue JWT
const token = jwt.sign({ username }, 'secret-key');
console.log(token);
// Return token
return res.json({ token });
} catch (error) {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
});
// API to create a new user
app.post('/api/users', (req, res) => {
const { username, password } = req.body;
// Create a new user
const user = new User({ username, password });
// Save the user to the database
user.save()
.then(() => {
return res.json({ message: 'User created successfully' });
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API to add accounts
app.post('/api/accounts', authenticateToken, (req, res) => {
const {username , password} = req.body;
// Create a new account
const account = new Account({ username , password });
// Save the Account to the database
account.save()
.then(() => {
return res.json({ message: 'Account added successfully' });
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API محمية يمكن الوصول إليها بواسطة JWT
app.get('/api/protected', authenticateToken, (req, res) => {
return res.json({ message: 'Protected API endpoint' });
});
// API to add product
app.post('/api/products', authenticateToken, (req, res) => {
const { name, price } = req.body;
// Create a new product
const product = new Product({ name, price });
// Save the product to the database
product.save()
.then(() => {
return res.json({ message: 'Product added successfully' });
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API to get all products
app.get('/api/products', authenticateToken, (req, res) => {
Product.find()
.then(products => {
return res.json(products);
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API to get a specific product by ID
app.get('/api/products/:id', authenticateToken, (req, res) => {
const productId = req.params.id;
Product.findById(productId)
.then(product => {
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
return res.json(product);
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API to update a product by ID
app.put('/api/products/:id', authenticateToken, (req, res) => {
const productId = req.params.id;
const { name, price } = req.body;
Product.findByIdAndUpdate(productId, { name, price }, { new: true })
.then(product => {
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
console.log(req.body);
console.log({ name, price });
return res.json({ message: 'Product updatedddddddddddddd successfully' });
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// API to delete a product by ID
app.delete('/api/products/:id', authenticateToken, (req, res) => {
const productId = req.params.id;
Product.findByIdAndDelete(productId)
.then(product => {
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
return res.json({ message: 'Product deleted successfully' });
})
.catch(error => {
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
});
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});