add: user registration API

This commit is contained in:
alikia2x (寒寒) 2025-03-31 20:07:58 +08:00
parent cfd4fc3d21
commit fba56106cc
Signed by: alikia2x
GPG Key ID: 56209E0CCD8420C6
4 changed files with 44 additions and 3 deletions

View File

@ -1,10 +1,12 @@
import { type Client, Pool } from "https://deno.land/x/postgres@v0.19.3/mod.ts";
import { postgresConfig } from "@core/db/pgConfig.ts";
import { postgresConfig, postgresConfigCred } from "@core/db/pgConfig.ts";
import { createMiddleware } from "hono/factory";
const pool = new Pool(postgresConfig, 4);
const poolCred = new Pool(postgresConfigCred, 2);
export const db = pool;
export const dbCred = poolCred;
export const dbMiddleware = createMiddleware(async (c, next) => {
const connection = await pool.connect();
@ -13,8 +15,16 @@ export const dbMiddleware = createMiddleware(async (c, next) => {
connection.release();
});
export const dbCredMiddleware = createMiddleware(async (c, next) => {
const connection = await poolCred.connect();
c.set("dbCred", connection);
await next();
connection.release();
})
declare module "hono" {
interface ContextVariableMap {
db: Client;
dbCred: Client;
}
}

View File

@ -1,6 +1,7 @@
{
"name": "@cvsa/backend",
"imports": {
"@rabbit-company/argon2id": "jsr:@rabbit-company/argon2id@^2.1.0",
"hono": "jsr:@hono/hono@^4.7.5",
"zod": "npm:zod",
"yup": "npm:yup"

View File

@ -1,15 +1,18 @@
import { Hono } from "hono";
import { dbMiddleware } from "./database.ts";
import { dbCredMiddleware, dbMiddleware } from "./database.ts";
import { rootHandler } from "./root.ts";
import { getSnapshotsHanlder } from "./snapshots.ts";
import { registerHandler } from "./register.ts";
export const app = new Hono();
app.use('/video/*', dbMiddleware);
app.use('/user', dbCredMiddleware);
app.get("/", ...rootHandler);
app.get('/video/:id/snapshots', ...getSnapshotsHanlder);
app.post('/user', ...registerHandler);
const fetch = app.fetch;
@ -17,4 +20,4 @@ export default {
fetch,
} satisfies Deno.ServeDefaultExport;
export const VERSION = "0.2.4";
export const VERSION = "0.3.0";

View File

@ -0,0 +1,27 @@
import { createHandlers } from "./utils.ts";
import Argon2id from "@rabbit-company/argon2id";
export const registerHandler = createHandlers(async (c) => {
try {
const client = c.get("dbCred");
const body = await c.req.json();
const username = body.username;
const password = body.password;
const hash = await Argon2id.hashEncoded(password);
const query = `
INSERT INTO users (username, password) VALUES ($1, $2)
`;
await client.queryObject(query, [username, hash]);
return c.json({
success: true,
message: "Registered",
});
} catch (e) {
if (e instanceof SyntaxError) {
return c.json({ error: "Invalid JSON" }, 400);
}
else {
return c.json({ error: (e as Error).message }, 500);
}
}
});