import express from "express";
import cors from "cors";
import mysql from "mysql2/promise";
import bcrypt from "bcrypt";
import jwt, { decode } from "jsonwebtoken";
const app = express();
const pool = mysql.createPool({
"host": "localhost",
"database": "games",
"user": "testing", // "root"
"password": "testing" // ""
});
app.use(express.json());
app.use(cors());
app.post("/register", async (req, res) => {
try {
/*
{
"username": "admin",
"email": "******@admin.hu",
"password": "admin"
}
*/
const body = req.body;
// ["username", "email", "password"].length
if (Object.keys(body).length !== 3) {
throw new Error("Invalid body."); // 400
}
if (!body.username || typeof body.username !== "string") {
throw new Error("Invalid username."); // 400
}
if (!body.email || typeof body.email !== "string") {
throw new Error("Invalid email."); // 400
}
if (!body.password || typeof body.password !== "string") {
throw new Error("Invalid password."); // 400
}
const secretPassword = await bcrypt.hash(body.password, 12);
const [insertResult] = await pool.query(
"INSERT INTO users (username, email, password) VALUES (?, ?, ?)",
[body.username, body.email, secretPassword]
);
if (insertResult.affectedRows === 0) {
throw new Error("Failed to insert user."); // 500
}
res.status(201).json({
"message": "User registered."
});
} catch (err) {
console.log(err);
if (err.message.includes("Invalid")) {
res.status(400).json({
"message": err.message
});
return;
}
res.status(500).json({
"message": "Failed to register user."
});
}
});