-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleAuthJSONWebToken.js
More file actions
75 lines (67 loc) · 1.51 KB
/
SimpleAuthJSONWebToken.js
File metadata and controls
75 lines (67 loc) · 1.51 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
const express = require("express");
const jwt = require("jsonwebtoken");
const jwtPassword = "Gagan@2004";
const app = express();
app.use(express.json());
const ALLUSERS = [
{
username: "gagansshemdi@gmail.com",
password: "123",
name: "Gagan Shemdi",
},
{
username: "rohitsingh@gail.com",
password: "1234",
name: "Rohit Singh",
},
{
username: "utkarshjai@gmail.com",
password: "12345",
name: "Utkarsh Bharadwaj",
},
];
function userExists(username, password) {
let userfound = false;
for (let i = 0; i < ALLUSERS.length; i++) {
if (
ALLUSERS[i].username === username &&
ALLUSERS[i].password === password
) {
userfound = true;
}
}
return userfound;
}
app.post("/signin", function (req, res) {
const username = req.body.username;
const password = req.body.password;
if (!userExists(username, password)) {
return res.status(403).json({
msg: "User does not exist",
});
}
var token = jwt.sign({ username: username }, jwtPassword);
return res.json({
token,
});
});
app.get("/users",function(req,res){
const token = req.headers.authorization;
try{
const decoded = jwt.verify(token,jwtPassword);
const username =decoded.username;
for(let i=0;i<ALLUSERS.length;i++){
if(ALLUSERS[i].username===username){
return res.json({
name:ALLUSERS[i].name
})
}
}
}
catch(err){
return res.status(403).json({
msg:"There is an error"
});
}
});
app.listen(3000);