-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
324 lines (271 loc) · 8.58 KB
/
server.js
File metadata and controls
324 lines (271 loc) · 8.58 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
const PORT = process.env.PORT || 5000;
var express = require("express");
var bodyParser = require('body-parser');
var cors = require("cors");
var morgan = require("morgan");
const mongoose = require("mongoose");
var bcrypt = require("bcrypt-inzi");
var jwt = require('jsonwebtoken');
var cookieParser = require('cookie-parser');
var postmark = require("postmark");
const path = require("path");
const axios = require('axios')
// var client = new postmark.Client("03d41ca2-fd57-4edd-9e9e-506ac1aaf894");
var SERVER_SECRET = process.env.SECRET || "1234"
// var userModel = mongoose.model("users", userSchema);
let dbURI = "mongodb+srv://duetstudents:duetstudents@studentsdata.jr39q.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', function () {
console.log("Mongoose is connected");
});
mongoose.connection.on('disconnected', function () {
console.log("Mongoose is disconnected");
process.exit(1);
});
mongoose.connection.on('error', function (err) {
console.log('Mongoose connection error: ', err);
process.exit(1);
});
process.on('SIGINT', function () {
console.log("app is terminating");
mongoose.connection.close(function () {
console.log('Mongoose default connection closed');
process.exit(0);
});
});
var userSchema = new mongoose.Schema({
name: String,
dept: String,
batch: String,
email: String,
password: String,
phone: String,
createdOn: {
type: Date,
'default': Date.now
}
});
var userModel = mongoose.model("users", userSchema);
var otpSchema = new mongoose.Schema({
"email": String,
"otpCode": String,
"createdOn": {
"type": Date,
"default": Date.now
},
});
var otpModel = mongoose.model("otps", otpSchema);
module.exports = {
userModel: userModel,
otpModel: otpModel
}
var app = express();
app.use(cookieParser());
app.use("/", express.static(path.resolve(path.join(__dirname, "public"))));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(
cors({
credentials: true,
origin: ['http://127.0.0.1:5501', 'https://duet-lms.vercel.app/', 'https://duet-lms.vercel.app']
})
);
// app.use(function (req, res, next) {
// //Enabling CORS
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
// next();
// });
//******* SIGNUP ********//
app.post("/signup", (req, res, next) => {
if (!req.body.userName ||
!req.body.userDept ||
!req.body.userBatch ||
!req.body.userEmail ||
!req.body.userPassword ||
!req.body.userPhone
) {
res.status(403).send(`
please send name, email, password, phone in json body.
e.g:
{
"name": "farooqi",
"email": "farooqi@gmail.com",
"password": "12345",
"phone": "03332765421",
}`)
return;
}
userModel.findOne({ email: req.body.userEmail }, function (err, doc) {
if (!err && !doc) {
bcrypt.stringToHash(req.body.userPassword).then(function (hash) {
var newUser = new userModel({
"name": req.body.userName,
"dept": req.body.userDept,
"batch": req.body.userBatch,
"email": req.body.userEmail,
"password": hash,
"phone": req.body.userPhone,
})
newUser.save((err, data) => {
if (!err) {
res.send({
message: "user created"
})
} else {
console.log(err);
res.status(500).send({
message: "user create error, " + err
})
}
});
})
} else if (err) {
res.status(500).send({
message: "db error"
})
} else {
res.send({
message: "User already exist ",
status: 409
})
}
})
})
//LOGIN
app.post("/login", (req, res, next) => {
console.log('body', req.body)
if (!req.body.email || !req.body.password) {
res.status(403).send(`
please send email and password in json body.
e.g:
{
"email": "farooqi@gmail.com",
"password": "abc",
}`)
return;
}
userModel.findOne({
email: req.body.email
},
function (err, user) {
if (err) {
res.status(500).send({
message: "an error occurred: " + JSON.stringify(err)
});
} else if (user) {
bcrypt.varifyHash(req.body.password, user.password).then(isMatched => {
if (isMatched) {
console.log("matched");
var token =
jwt.sign({
id: user._id,
name: user.name,
email: user.email,
}, SERVER_SECRET);
res.cookie('jToken', token, {
maxAge: 86_400_000,
httpOnly: true
});
res.send({
message: "login success",
user: {
name: user.name,
email: user.email,
phone: user.phone,
gender: user.gender,
},
token: token
});
} else {
console.log("not matched");
res.status(401).send({
message: "incorrect password"
})
}
}).catch(e => {
console.log("error: ", e)
})
} else {
res.status(403).send({
message: "user not found"
});
}
});
})
//Token
app.use(function (req, res, next) {
const authHeader = req.get("Authorization");
if (!authHeader) {
const error = new Error("Not Authenticated");
error.statusCode = 401;
throw error;
}
const token = req.get("Authorization").split(" ")[1];
let decodedToken = "";
try {
decodedToken = jwt.verify(token, SERVER_SECRET);
// console.log(decodedToken);
if (!decodedToken) {
const error = new Error("Not Authenticated");
error.statusCode = 401;
throw error;
} else {
// console.log("else");
// console.log(decodedToken)
userModel.findById(decodedToken.id)
.then((user) => {
console.log(user)
req.userId = user._id;
next();
})
.catch(() => {
const error = new Error("No Admin Found");
error.statusCode = 401;
throw error;
});
}
} catch (err) {
err.statusCode = 500;
throw err;
}
});
app.get("/profile", (req, res, next) => {
console.log('289', req.userId);
userModel.findById(
// req.body.jToken.id,
req.userId,
"name dept batch phone ",
function (err, data) {
if (!err) {
res.send({
userData: data,
});
} else {
res.status(500).send({
message: "server error",
});
}
}
);
});
//LOGOUT
app.post("/logout", (req, res, next) => {
console.log(req.cookies)
res.cookie('jToken', "", {
maxAge: 86_400_000,
httpOnly: true
});
res.send("logout success");
})
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
//Server
app.listen(PORT, () => {
console.log("server is running on: ", PORT);
})