aboutsummaryrefslogtreecommitdiff
path: root/server.js
blob: bd3975ff9fc133b8a099bf8f61e6dd23514f29c3 (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
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
const express = require("express")
const { v4: uuid } = require('uuid')
const path = require("path")
const mariadb = require("mariadb")
const bcrypt = require('bcrypt');

const app = express()
const port = 80
app.use(express.urlencoded({ extended: true}))

const con = mariadb.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "db1"
})

app.use(express.static("src"));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "src", "/password.html"))
})

app.post("/api/password/register", async (req, res) => {
  try {
    const {email, password} = req.body

    if(!password || !email) {
        return res.status(200).send("Invalid credentials")
    }

    const [existingUsers] = await con.query(
        "SELECT * FROM users WHERE email = ?", [email]
    )
    if(existingUsers != null) {
      return res.status(200).send("User already exists")
    }
    const UUID = uuid()
    const salt = bcrypt.genSaltSync(10);
    const hashedPassword = bcrypt.hashSync(password, salt);

    await con.query(
      "INSERT INTO users (UUID, email, password, salt) VALUES(?,?,?,?)",
      [UUID, email, hashedPassword, salt]
    )
    return res.status(201).send("User registered successfully")
  } catch (error) {
    console.error(error);
    res.status(500).send("Server error");
  }
})

app.post("/api/password/signin", async (req, res) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) {
      return res.status(401).send("Invalid credentials");
    }

    const [users] = await con.query(
      "SELECT * FROM users WHERE email = ?",
      [email]
    );

    if (users == null) {
      return res.status(200).send("User does not exist");
    }
    const passwordMatch = bcrypt.compareSync(password, users.password);

    if (!passwordMatch) {
      return res.status(200).send("Invalid credentials");
    }

    return res.status(200).send("User signed in successfully");
  } catch (error) {
    console.error(error);
    res.status(500).send("Server error");
  }
});

app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`)
})

app.get("/user/:uuid", async (req, res) => {
  try {
  const UUID = req.params.uuid
  const [user] = await con.query(
    "SELECT email FROM users WHERE UUID = ?",
    [UUID]
  )
  res.status(200).send(user)
  } catch (error) {
    console.error(error)
    return res.status(500).send("Server error")
  }
})