-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoose.js
88 lines (69 loc) · 1.82 KB
/
mongoose.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
const express = require("express");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const jwtPassword = "123456";
mongoose.connect("your_mongo_url");
const User = mongoose.model("User", {
name: String,
username: String,
pasword: String,
});
const app = express();
app.use(express.json());
function userExists(username, password) {
// should check in the database
}
app.post("/signin", async function (req, res) {
const username = req.body.username;
const password = req.body.password;
if (!userExists(username, password)) {
return res.status(403).json({
msg: "User doesnt exist in our in memory db",
});
}
var token = jwt.sign({ username: username }, "shhhhh");
return res.json({
token,
});
});
app.get("/users", function (req, res) {
const token = req.headers.authorization;
try {
const decoded = jwt.verify(token, jwtPassword);
const username = decoded.username;
// return a list of users other than this username from the database
} catch (err) {
return res.status(403).json({
msg: "Invalid token",
});
}
});
app.listen(3000);
//------mongoDB-----//
const mongoose = require("mongoose");
mongoose.connect = "URL";
const User = mongoose.model("Users", {
name: String,
email: String,
password: String,
});
app.post("/signup", function (req, res) {
const username = req.body.username;
const password = req.body.password;
const mail = req.body.mail;
//checking if user exists or not
const existingUser = User.findOne({ email: username });
if (existingUser) {
return res.status(400).send("Username already exists");
} else {
const user = new User({
name: "Dev Sanghvi",
email: "[email protected]",
password: "dev11",
});
}
User.save();
res.json({
"msg":"user created successfully ! "
})
});