-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
106 lines (89 loc) · 2.01 KB
/
index.js
File metadata and controls
106 lines (89 loc) · 2.01 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
const express=require("express")
const jwt=require("jsonwebtoken")
const cors = require('cors')
const app=express()
const JWT_SECRET="tridib11"
const PORT=3000
app.use(express.json())
const users=[]
function auth(req, res, next) {
const token = req.headers.token || req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({
message: "Token is missing. You are not logged in."
});
}
try {
const decodedData = jwt.verify(token, JWT_SECRET);
if (decodedData.username) {
req.username = decodedData.username;
next();
} else {
res.status(401).json({
message: "Invalid token. You are not logged in."
});
}
} catch (error) {
res.status(401).json({
message: "Invalid token. You are not logged in."
});
}
}
function logger(req,res,next){
console.log(req.method+" request came")
next()
}
app.use(cors())
app.get("/",(req,res)=>{
res.json({
msg:"Server is running"
})
})
app.post("/signup",(req,res)=>{
const username=req.body.username
const password=req.body.password
if(users.find(user => user.username === username)){
return res.status(400).json({
msg:"User already exists"
})
}
users.push({
username:username,
password:password
})
res.json({
msg:"You are signed in successfully"
})
})
app.post("/signin",(req,res)=>{
const username=req.body.username
const password=req.body.password
if(users.find(user=>user.username===username)){
const token=jwt.sign({
username
},JWT_SECRET)
res.json({
token:token
})
}else{
res.json({
msg:"Sorry user doesnot exists!"
})
}
})
app.get("/me",auth,logger,(req,res)=>{
const user = users.find(user=>user.username===req.username)
if (user) {
return res.json({
username:user.username,
password: user.password
})
} else {
return res.status(404).json({
msg: "User not found"
})
}
})
app.listen(PORT,()=>{
console.log(`Server started at port ${PORT}`)
})