import { Hono } from "hono";
import { client } from "../index.js";
import authenticateUser from "./auth.js";
import { setCookie } from "hono/cookie";
const loginRoute = new Hono();
loginRoute.post("", async (c) => {
const body = await c.req.formData();
const email = body.get("login-email") as string;
const password = body.get("login-password") as string;
try {
const user_id = await checkCredentials(email, password);
// Attach cookie
setCookie(c, "user_id", user_id);
c.status(201);
return c.json({ message: "User has been successfully login !" });
} catch (e) {
if (e instanceof Error) {
console.error(
`An error occured while trying to login for the user: ${e.message}`
);
console.error(e.stack);
}
c.status(401);
return c.json({ message: "Login unsuccessful !" });
}
});
async function checkCredentials(email: string, password: string) {
let res = await client.query(`SELECT * FROM users WHERE email = $1`, [email]);
// check if email exist
if (res.rows.length === 0) throw new Error("Email doesn't exist");
const db_password = res.rows[0].password;
// password matching
if (password !== db_password) throw new Error("Password doesn't exist");
const user_id = res.rows[0].user_id;
// authenticate user
await authenticateUser(user_id);
return user_id;
}
export default loginRoute;
import { Hono } from "hono";
import { client } from "../index.js";
import authenticateUser from "./auth.js";
import { setCookie } from "hono/cookie";
const loginRoute = new Hono();
loginRoute.post("", async (c) => {
const body = await c.req.formData();
const email = body.get("login-email") as string;
const password = body.get("login-password") as string;
try {
const user_id = await checkCredentials(email, password);
// Attach cookie
setCookie(c, "user_id", user_id);
c.status(201);
return c.json({ message: "User has been successfully login !" });
} catch (e) {
if (e instanceof Error) {
console.error(
`An error occured while trying to login for the user: ${e.message}`
);
console.error(e.stack);
}
c.status(401);
return c.json({ message: "Login unsuccessful !" });
}
});
async function checkCredentials(email: string, password: string) {
let res = await client.query(`SELECT * FROM users WHERE email = $1`, [email]);
// check if email exist
if (res.rows.length === 0) throw new Error("Email doesn't exist");
const db_password = res.rows[0].password;
// password matching
if (password !== db_password) throw new Error("Password doesn't exist");
const user_id = res.rows[0].user_id;
// authenticate user
await authenticateUser(user_id);
return user_id;
}
export default loginRoute;