a tool for shared writing and social publishing
1"use server";
2
3import { randomBytes } from "crypto";
4import { drizzle } from "drizzle-orm/node-postgres";
5import postgres from "postgres";
6import { phone_number_auth_tokens } from "drizzle/schema";
7import twilio from "twilio";
8import { pool } from "supabase/pool";
9
10async function sendAuthCode({
11 country_code,
12 phone_number,
13 code,
14}: {
15 country_code: string;
16 phone_number: string;
17 code: string;
18}) {
19 let phoneNumber = `+${country_code}${phone_number}`;
20 const accountSid = process.env.TWILIO_ACCOUNT_SID;
21 const authToken = process.env.TWILIO_AUTH_TOKEN;
22 const client = twilio(accountSid, authToken);
23 if (country_code === "1") {
24 const message = await client.messages.create({
25 body: `${code} is your verification code
26
27@leaflet.pub #${code}`,
28 from: `+18449523391`,
29 to: phoneNumber,
30 });
31 console.log(message);
32 } else {
33 const message = await client.messages.create({
34 contentSid: "HX5ebfae4d2a423808486e773e8a22488d",
35 contentVariables: JSON.stringify({ 1: code }),
36 from: "whatsapp:+18449523391",
37 messagingServiceSid: "MGffbf9a66770350b25caf3b80b9aac481",
38 to: `whatsapp:${phoneNumber}`,
39 });
40 }
41}
42
43export async function createPhoneAuthToken({
44 phone_number,
45 country_code,
46}: {
47 phone_number: string;
48 country_code: string;
49}) {
50 const client = await pool.connect();
51 const db = drizzle(client);
52
53 const code = randomBytes(3).toString("hex").toUpperCase();
54
55 const [token] = await db
56 .insert(phone_number_auth_tokens)
57 .values({
58 phone_number,
59 country_code,
60 confirmation_code: code,
61 confirmed: false,
62 })
63 .returning({
64 id: phone_number_auth_tokens.id,
65 });
66
67 await sendAuthCode({ country_code, phone_number, code });
68
69 client.release();
70 return token.id;
71}