import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts";
import { email } from "https://esm.town/v/std/email";
import { sqlite } from "https://esm.town/v/std/sqlite";
export default async function(req: Request): Promise<Response> {
const TABLE_NAME = "lab_login_users_with_times";
const body = await req.json();
const { username, password, status, gif = null } = body;
const userQuery = await sqlite.execute({
sql: `SELECT * FROM ${TABLE_NAME} WHERE username = ?`,
args: [username],
});
if (userQuery.rows.length === 0) {
return new Response(JSON.stringify({ error: "user not found" }), { status: 404 });
}
const user = userQuery.rows[0];
const storedPassword = user[2];
const passwordMatch = await bcrypt.compare(password, storedPassword);
if (!passwordMatch) {
return new Response(JSON.stringify({ error: "wrong password" }), { status: 401 });
}
if (user[5] === 1) {
return new Response(JSON.stringify({ error: "user is banned" }), { status: 403 });
}
if (status.length > 9999) {
return new Response(JSON.stringify({ error: "status too long" }), { status: 400 });
}
const updatedUser = await sqlite.execute({
sql: `UPDATE ${TABLE_NAME} SET status = ?, gif = ?, last_updated = CURRENT_TIMESTAMP WHERE username = ?`,
args: [status, gif, username],
});
email({
to: "todepond@gmail.com",
from: "todepond.com@valtown.email",
subject: "New Login status",
text: status,
});
return new Response(JSON.stringify(updatedUser.rows[0]), { status: 200 });
}