2022-05-14 22:35:51 +00:00
|
|
|
import { type LoaderFunction, redirect } from "@remix-run/node";
|
|
|
|
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
|
|
|
|
import db from "~/utils/db.server";
|
|
|
|
import { commitSession } from "~/utils/session.server";
|
2022-05-14 23:29:51 +00:00
|
|
|
import twilio from "twilio";
|
|
|
|
import serverConfig from "~/config/config.server";
|
2022-05-14 22:35:51 +00:00
|
|
|
|
|
|
|
export const loader: LoaderFunction = async ({ request }) => {
|
|
|
|
const user = await requireLoggedIn(request);
|
|
|
|
const url = new URL(request.url);
|
2022-05-14 23:29:51 +00:00
|
|
|
const twilioSubAccountSid = url.searchParams.get("AccountSid");
|
|
|
|
if (!twilioSubAccountSid) {
|
2022-05-14 22:35:51 +00:00
|
|
|
throw new Error("unreachable");
|
|
|
|
}
|
|
|
|
|
2022-05-14 23:29:51 +00:00
|
|
|
const twilioClient = twilio(twilioSubAccountSid, serverConfig.twilio.authToken);
|
|
|
|
const twilioSubAccount = await twilioClient.api.accounts(twilioSubAccountSid).fetch();
|
|
|
|
const twilioAccountSid = twilioSubAccount.ownerAccountSid;
|
2022-05-14 22:35:51 +00:00
|
|
|
await db.organization.update({
|
|
|
|
where: { id: user.organizations[0].id },
|
2022-05-14 23:29:51 +00:00
|
|
|
data: { twilioSubAccountSid, twilioAccountSid },
|
2022-05-14 22:35:51 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const { session } = await refreshSessionData(request);
|
|
|
|
return redirect("/settings/phone", {
|
|
|
|
headers: {
|
|
|
|
"Set-Cookie": await commitSession(session),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
};
|