-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (60 loc) · 2.14 KB
/
index.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
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const db = mongoose.connection;
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
mongoose.connect('mongodb+srv://ammar:[email protected]/myLoginRegisterDB?retryWrites=true&w=majority')
db.on("error", console.error.bind(console, "Connection failed:"));
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
})
const User = new mongoose.model("User", userSchema)
app.post('/login', (req, res) => {
const { email, password } = req.body
User.findOne({ email: email }).then((result) => {
if (result === null) {
res.send({ message: "User not registered" })
} else {
if (password === result.password) {
res.send({ message: "User Succesfully logged in", user: result })
} else {
res.send({ message: "wrong password" })
}
}
}).catch((err) => {
res.send({ message: "failed to get data from database" })
});
})
app.post('/register', (req, res) => {
const { name, email, password } = req.body
User.findOne({ email: email }).then((result) => {
if (result === null) {
const newUser = new User({
name,
email,
password,
})
newUser.save().then((result) => {
res.send({ message: "User registered Succesfully" })
}).catch((err) => {
res.send({ message: "Failed to save user on database, contact developer at [email protected]" })
});
} else {
res.send({ message: "user already registered" })
}
}).catch((err) => {
res.send({ message: "failed to get data from database" })
});
})
db.once("open", function () {
console.log("Database Connected Succesfully");
app.listen(process.env.PORT, () => {
console.log(`The server is running on port: ${process.env.PORT}`);
})
})