summaryrefslogtreecommitdiff
path: root/graphs/js/logMeIn/logMeIn.js
blob: 25910714bff6498cd55469279f877ddb9b4a0ea5 (plain)
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
const express = require("express");
const jsonwebtoken = require("jsonwebtoken");

function logMeIn(host, port) {
    const secretKey = process.env.JWT_SECRET_KEY;
    const app = express();

    app.use(express.json());

    app.get("/", (req, res) => {
        res.status(200).send({ message: "Hello World!" });
    });
    app.post("/login", (req, res) => {
        const login = req.body.username;
        const passwd = req.body.password;

        if (login !== "xavier.login" || passwd != "1234") {
            res.status(401).send({ error: "Invalid username or password" });
        } else {
            const jwt = jsonwebtoken.sign(req.body, secretKey);

            res.status(200).send({ jwt: jwt });
        }
    });
    app.get("/secret", (req, res) => {
        if (req.headers == null || req.headers == undefined) {
            res.status(401).send({ error: "Unauthorized" });
            return;
        }

        try {
            const decoded = jsonwebtoken.verify(
                req.headers.authorization.split(" ")[1],
                secretKey,
            );

            if (
                decoded.username !== "xavier.login" ||
                decoded.password !== "1234"
            ) {
                res.status(401).send({ error: "Unauthorized" });
            }

            res.status(200).send({ message: "Access granted" });
        } catch {
            res.status(401).send({ error: "Unauthorized" });
        }
    });

    return app.listen(port, () => {
        console.log("Server running at http://" + host + ":" + port + "/");
    });
}

module.exports = {
    logMeIn,
};

//logMeIn("127.0.0.1", 3000);