-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
47 lines (39 loc) · 1.22 KB
/
api.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
import { once } from "node:events";
import { createServer } from "node:http";
import JWT from "jsonwebtoken";
const DEFAULT_USER = {
user: "erickwendel",
password: "123",
};
const JWT_KEY = "abc123";
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 invalid!" }));
return;
}
const token = JWT.sign({ user, message: "hey duuude!" }, 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(400);
return response.end(JSON.stringify({ error: "invalid token!" }));
}
response.end(JSON.stringify({ result: "Hey welcome!" }));
}
const app = createServer(handler);
export { app, handler };