Files

15 lines
981 B
TypeScript

import { createHash } from "node:crypto";
import { db } from "@/lib/db";
export function acceptSourceInvite(userId: number, token: string) {
const hash = createHash("sha256").update(token).digest("hex");
return db.transaction(() => {
const invite = db.prepare("SELECT id,source_id,role FROM source_invites WHERE token_hash=? AND used_at IS NULL AND expires_at>CURRENT_TIMESTAMP").get(hash) as { id: number; source_id: number; role: string } | undefined;
if (!invite) throw new Error("邀請不存在、已使用或已過期");
const consumed = db.prepare("UPDATE source_invites SET used_at=CURRENT_TIMESTAMP WHERE id=? AND used_at IS NULL").run(invite.id);
if (!consumed.changes) throw new Error("邀請不存在、已使用或已過期");
db.prepare("INSERT INTO source_members(source_id,user_id,role) VALUES(?,?,?) ON CONFLICT(source_id,user_id) DO UPDATE SET role=excluded.role").run(invite.source_id, userId, invite.role);
return invite;
})();
}