-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
93 lines (62 loc) · 1.99 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
require("dotenv").config();
require("./config/database").connect();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const express = require("express");
const User = require("./model/user");
const auth = require("./middleware/auth");
const app = express();
app.use(express.json());
app.post("/welcome", auth, (req, res) => {
res.status(200).send("Welcome 🙌 ");
});
// Register
app.post("/register", async (req, res) => {
try {
const {firstName, lastName, email, password} = req.body;
if(!(email && password && lastName && firstName)){
return res.status(400).send("enter all inputs");
}
const existingUser = await User.findOne({email});
if(existingUser){
return res.status(409).send("User already exists");
}
encryptedPassword = await bcrypt.hash(password, 10);
const user = await User.create({
firstName,
lastName,
email: email.toLowerCase(),
password: encryptedPassword,
});
const token = jwt.sign(
{user_id: user._id, email},
process.env.TOKEN_KEY
);
user.token = token;
return res.status(200).json(user);
} catch (error) {
console.log(error);
}
});
// Login
app.post("/login", async (req, res) => {
try {
const {email, password} = req.body;
if(!(email && password)){
return res.status(400).send("enter all inputs");
}
const user = await User.findOne({email});
if(user && (await bcrypt.compare(password, user.password))){
const token = jwt.sign(
{user_id : user._id, email },
process.env.TOKEN_KEY
)
user.token = token;
return res.status(200).json(user);
}
return res.status(400).send("Invalid crediantials");
} catch (error) {
console.log(error);
}
});
module.exports = app;