-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
112 lines (89 loc) · 2.62 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
require("dotenv").config();
require("./config/database").connect();
const express = require("express");
const User = require("./model/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const auth = require("./middleware/auth");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.get("/", (req, res) => {
res.send("<h1>Hello from Au th system -LCO</h1>");
});
app.post("/register", async (req, res) => {
try {
const { firstname, lastname, email, password } = req.body;
if (!(email && password && firstname && lastname)) {
res.status(400).send("All feilds are required");
}
const existingUser = await User.findOne({ email });
if (existingUser) {
res.status(401).send("User Already exists");
}
const myEncPassword = await bcrypt.hash(password, 10);
const user = await User.create({
firstname,
lastname,
email: email.toLowerCase(),
password: myEncPassword,
});
//token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.SECRET_KEY,
{
expiresIn: "2h",
}
);
user.token = token;
//update or not in db
//handle password situation
user.password = undefined;
//send token or send just sucess yes and redirect - choice
res.status(201).json(user);
} catch (error) {
console.log(error);
}
});
app.post("/login", async (req, res) => {
//use try catch block or u can go with promisess
try {
const { email, password } = req.body;
if (!(email && password)) {
res.status(400).send("Feild is Required");
}
const user = await User.findOne({ email });
// if (!user) {
// res.status(400).send("you are not registerd");
// }
if (user && (await bcrypt.compare(password, user.password))) {
const token = jwt.sign(
{ user_id: user._id, email },
process.env.SECRET_KEY,
{ expiresIn: "2h" }
);
user.token = token;
user.password = undefined;
// res.status(200).json(user);
//if you want to use cookies
const options = {
expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // (days) - (day)-(minutes)-(sec)-(1000)
httpOnly: true,
};
res.status(200).cookie("token", token, options).json({
sucess: true,
token,
user,
});
}
res.status(400).send("email or password is incorrect");
} catch (error) {
console.log(error);
}
});
app.get("/dashboard", auth, (req, res) => {
res.send("welcome to secret info");
});
module.exports = app;