-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
46 lines (42 loc) · 1.3 KB
/
api.js
File metadata and controls
46 lines (42 loc) · 1.3 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
import JWT from "jsonwebtoken";
import { once } from "node:events";
import { createServer } from "node:http";
const DEFAULT_USER = {
user: "leonardojaques",
password: "123",
};
const JWT_KEY = "123secret";
async function loginRoute(request, response) {
const { user, password } = JSON.parse(await once(request, "data"));
if (user !== DEFAULT_USER.user || password !== DEFAULT_USER.password) {
response.writeHead(401);
response.end(JSON.stringify({ error: "user or password invalid" }));
return;
}
const token = JWT.sign({ user, message: "hey you" }, JWT_KEY);
response.end(JSON.stringify({ token }));
}
function isHeadersValid(headers) {
try {
const auth = headers.authorization.replace(/bearer\s/gi, "");
JWT.verify(auth, JWT_KEY);
return true;
} catch (error) {
return false;
}
}
async function handler(request, response) {
if (request.url === "/login" && request.method === "POST") {
return loginRoute(request, response);
}
if (!isHeadersValid(request.headers)) {
response.writeHead(401);
return response.end(JSON.stringify({ error: "invalid token!" }));
}
response.end(JSON.stringify({ result: "Hey welcome" }));
}
const port = 3000;
const app = createServer(handler).listen(port, () =>
console.log(`Server is running in port: ${port}`)
);
export { app };