-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
131 lines (111 loc) · 3.31 KB
/
Copy pathindex.js
File metadata and controls
131 lines (111 loc) · 3.31 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
import express from "express";
import cors from "cors";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { connectdb, getdb } from "./db.js";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(cors());
const port = 3000;
app.use(express.json());
// register
app.post("/register", async (req, res) => {
try {
const { username, password } = req.body;
const db = getdb();
// find user if exist
const finduser = await db.collection("users").findOne({ username });
if (finduser) {
return res.status(400).send("user already exist");
}
// hashing password
const hashpassword = await bcrypt.hash(password, 10);
// adding user to db
await db
.collection("users")
.insertOne({ username, password: hashpassword });
res.status(201).send("user registered successfuly");
} catch (err) {
res.status(500).send({ message: err.message });
}
});
// login
app.post("/login", async (req, res) => {
try {
const { username, password } = req.body;
const db = getdb();
// find user if exist
const finduser = await db.collection("users").findOne({ username });
if (!finduser) {
return res.status(400).send("invalid username or password");
}
// verfiy hashed code
const isMatch = await bcrypt.compare(password, finduser.password);
if (!isMatch) {
return res.status(400).send("invalid username or password");
}
// generate token
const token = jwt.sign(
{ userId: finduser._id, username: finduser.username },
process.env.JWT_SECRET,
{ expiresIn: "1h" },
);
res.status(200).send({ token, username });
} catch (err) {
res.status(500).send({ message: err.message });
}
});
// delete account
app.delete("/users", async (req, res) => {
try {
const { username, password } = req.body;
const db = getdb();
// find user if exist
const finduser = await db.collection("users").findOne({ username });
if (!finduser) {
return res.status(400).send("invalid username or password");
}
// verfiy hashed code
const isMatch = await bcrypt.compare(password, finduser.password);
if (!isMatch) {
return res.status(400).send("invalid username or password");
}
// generate token
const token = jwt.sign(
{ userId: finduser._id, username: finduser.username },
process.env.JWT_SECRET,
{ expiresIn: "1h" },
);
// delete account
await db.collection("users").deleteOne({ username });
res.status(200).send("account deleted");
} catch (err) {
res.status(500).send({ message: err.message });
}
});
// middleware to verify token
const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send("access denied, no token provided");
}
const token = authHeader.split(" ")[1]; // Bearer <token>
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(400).send("invalid token");
}
};
// profile
app.get("/profile", authMiddleware, async (req, res) => {
res.json({ message: "welcome to your profile", user: req.user });
});
// start server
connectdb().then(() => {
app.listen(port, () => {
console.log(`server running in ${port}`);
});
});