-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
278 lines (240 loc) · 9.02 KB
/
app.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
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
const express = require('express')
const morgan = require('morgan');
require("dotenv").config();
require("./config/database").connect()
const bcrypt = require("bcryptjs")
const jwt = require('jsonwebtoken')
const userDb=require("./model/user")
const carDb=require("./model/car")
const authMiddelware = require("./middleware/auth")
const app = express()
const path=require('path')
const mongoose = require('mongoose')
var bodyParser = require('body-parser')
// swagger for api documentation
const swaggerUi = require('swagger-ui-express')
const swaggerFile = require('./swagger_output.json')
app.use('/doc', swaggerUi.serve, swaggerUi.setup(swaggerFile))
//midellware
app.use(express.json())
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, 'public')));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//authentification
app.post('/login',authMiddelware.loggedIn,async (req,res)=>{
console.log(req.body.phoneNumber,req.body.password)
let reqPhoneNumber= req.body.phoneNumber
let reqPassword = req.body.password
if(!reqPassword|| !reqPhoneNumber ){
res.status(400).json({"status":"error","message":"no credential found"})
}else{
userDb.findOne({phoneNumber:reqPhoneNumber})
.then((user)=>{
if(!user){
console.log(`user with phone number ${reqPhoneNumber} not found`)
res.status(404).json({"status":"error","message":"user not found"})
}else{
bcrypt.compare(reqPassword, user.password)
.then((result)=>{
if(result){
const userToken = jwt.sign(
{user_id: user._id , reqPhoneNumber},
process.env.TOKEN_KEY,
{
expiresIn: "30d",
}
)
user.token = userToken
res.status(200).json({"status":"success","token":userToken})
}
})
.catch((err)=>{
res.status(200).json({"status":"error","message":"error"})
})
}
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
}
})
app.post('/register',async (req,res)=>{
let reqPhoneNumber= req.body.phoneNumber
let reqCreditCardNumber=req.body.creditCardNumber
let reqCreditCardExpiration=req.body.creditCardExpiration
let reqDrivingLicense=req.body.drivingLicense
if(!reqPhoneNumber || !reqCreditCardNumber || !reqCreditCardExpiration || !reqDrivingLicense){
res.status(400).json({"status":"error","message":"information not complete"})
}else{
try{
const user = await userDb.findOne({phoneNumber:reqPhoneNumber})
if(user){
res.status(400).json({"status":"error","message":"phone number existe"})
}
else{
let pass = Math.floor(Math.random() * (99999999 - 10000000) + 10000000);
let encryptedPassword = await bcrypt.hash(pass.toString(), 10);
const newUser = await userDb.create({
phoneNumber: reqPhoneNumber,
password: encryptedPassword,
creditCardNumber: reqCreditCardNumber,
creditCardExpiration: reqCreditCardExpiration,
drivingLicense: reqDrivingLicense
});
const jwtToken = jwt.sign(
{User_id: newUser._id,reqPhoneNumber},
process.env.TOKEN_KEY,
{
expiresIn: "30d",
}
)
newUser.token=jwtToken
res.status(201).json({"user":newUser,"password":pass.toString()})
}
}catch(err){
if(err.code=11000){
//console.log(err);
console.log(`Duplication Error ${Object.keys(err.keyValue)[0]} already exists.`)
res.status(500).json({"status":"error","message":Object.keys(err.keyValue)[0] + " already exists."})
//res.status(500).json({"status":"error","message":"information already exists."})
}else{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
}
}
}
})
//routes
app.get("/api/users",(req,res)=>{
console.log(req.user)
userDb.find({})
.then((users)=>{
res.status(200).json(users)
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.get("/api/cars",(req,res)=>{
carDb.aggregate([{ $project: { PIN:0 } }])
.then((cars)=>{
res.status(200).json(cars)
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.get("/api/cars/:idCar",(req,res)=>{
carDb.aggregate([ { $match: { $expr : { $eq: [ '$_id' , { $toObjectId: req.params.idCar } ] } } } , { $project: { PIN:0 } }])
.then((car)=>{
if(car){
console.log(car[0])
res.status(200).json(car[0])
}else{
res.status(404).json({"status":"error","message":"Not Found"})
}
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.get("/api/user/carsRented/:phone",(req,res)=>{
console.log(req.params.phone)
userDb.findOne({ phoneNumber: req.params.phone})
.then(async (user)=>{
console.log(user)
let cars = await carDb.find({
_id: { $in:
user.carsRented
}
});
res.status(200).json(cars)
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.post("/api/reserve/:phone/:idCar",async (req,res)=>{
console.log(req.params.phone)
carDb.findById(req.params.idCar)
.then(async (car)=>{
if(car){
if(car.availability){
let user = await userDb.findOne({ phoneNumber: req.params.phone});
user.carsRented.push(req.params.idCar)
user.save()
car.availability = false
car.PIN = Math.floor(Math.random() * (9999 - 1111) + 1111);
car.save()
res.status(200).json(user.carsRented)
}else{
res.status(302).json({"status":"error","message":"Already Rented"});
}
}else{
res.status(404).json({"status":"error","message":"Not Found"})
}
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.post("/api/endreserve/:phone/:idCar",async (req,res)=>{
//userDb.findById(req.user.user_id)
console.log(req.params.phone)
userDb.findOne({ phoneNumber: req.params.phone})
.then(async (user)=>{
if(user){
let car = carDb.findById(req.params.idCar)
if(car){
user.carsRented.remove(req.params.idCar)
user.save()
const filter = {_id: req.params.idCar}
const update = {availability: true, PIN:0}
let doc = await carDb.findOneAndUpdate(filter,update);
res.status(404).json({"status":"success","message":"End reservation successfully"})
}else{
res.status(404).json({"status":"error","message":"Car Not Found"})
}
}else{
res.status(404).json({"status":"error","message":"User Not Found"})
}
})
.catch((err)=>{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
})
})
app.post("/api/editinfo/:phone",(req,res)=>{
//userDb.findById(req.user.user_id)
console.log(req.body.phoneNumber,req.body.password,req.body.creditCardNumber)
userDb.findOne({ phoneNumber: req.params.phone})
.then(async (user)=>{
if (user){
const filter = {phoneNumber:req.params.phone}
const update = req.body
let doc = await userDb.findOneAndUpdate(filter,update, {new: true});
res.status(200).json({"status":"success","message":doc})
}else{
res.status(404).json({"status":"error","message":"Not Found"})
}
})
.catch((err)=>{
if(err.code=11000){
console.log(`Duplication Error when update ${Object.keys(err.keyValue)[0]} already exists.`)
res.status(500).json({"status":"error","message":Object.keys(err.keyValue)[0] + " already exists."})
}else{
console.log(err)
res.status(500).json({"status":"error","message":"server error"})
}
})
})
module.exports = app;