forked from 100xdevs-cohort-3/week-6-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (81 loc) · 2.35 KB
/
index.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
const express = require("express");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "kirat123123";
const app = express();
app.use(express.json());
const users = [];
function logger(req, res, next) {
console.log(req.method + " request came");
next();
}
// localhost:3000
app.get("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
})
app.post("/signup", logger, function(req, res) {
const username = req.body.username
const password = req.body.password
users.push({
username: username,
password: password
})
// we should check if a user with this username already exists
res.json({
message: "You are signed in"
})
})
app.post("/signin", logger, function(req, res) {
const username = req.body.username;
const password = req.body.password;
let foundUser = null;
for (let i = 0; i < users.length; i++) {
if (users[i].username === username && users[i].password === password) {
foundUser = users[i]
}
}
if (!foundUser) {
res.json({
message: "Credentials incorrect"
})
return
} else {
const token = jwt.sign({
username: users[i].username
}, JWT_SECRET);
res.header("jwt", token);
res.header("random", "harkirat");
res.json({
token: token
})
}
})
function auth(req, res, next) {
const token = req.headers.token;
const decodedData = jwt.verify(token, JWT_SECRET);
if (decodedData.username) {
// req = {status, headers...., username, password, userFirstName, random; ":123123"}
req.username = decodedData.username
next()
} else {
res.json({
message: "You are not logged in"
})
}
}
app.get("/me", logger, auth, function(req, res) {
// req = {status, headers...., username, password, userFirstName, random; ":123123"}
const currentUser = req.username;
// const token = req.headers.token;
// const decodedData = jwt.verify(token, JWT_SECRET);
// const currentUser = decodedData.username
for (let i = 0; i < users.length; i++) {
if (users[i].username === currentUser) {
foundUser = users[i]
}
}
res.json({
username: foundUser.username,
password: foundUser.password
})
})
app.listen(3000);