UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

54 lines (52 loc) • 2.41 kB
import { assert, panic } from "../../assertions.js"; import { writeCookies } from "../../cookies.js"; import { sessionConfig } from "../config.js"; import { makePlatform } from "../platform.js"; import { assertCanChange, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js"; import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js"; //#region src/auth/methods/magicLink.ts /** * Signs a visitor in with the token from a magic link they followed. * * The token keeps working after it is used, so anyone holding the link can sign * in as that visitor. Never log it, and redirect away from the URL that carried * it. * */ async function signInWithMagicLink(credentials) { assertCanChange("auth.signInWithMagicLink"); const result = await makePlatform(sessionConfig().applicationId).signInWithMagicLink(credentials); if (!result.ok) { if (isUserLimitReached(result)) return authError("userLimitReached", result.message); if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message); if (isNotInPlan(result)) return authError("notEnabled", result.message); if (result.status === 429) return authError("tooManyAttempts", result.message); if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message); if (result.status >= 500) panic(`Expected magic-link sign-in to succeed, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app signs people in with a magic link.`); } if (result.data.status === "MFA_REQUIRED") { const { mfa } = result.data; assert(mfa, "Expected a challenge from magic-link sign-in, but got none"); writeCookies([makePendingAuthCookie(mfa.challengeToken)]); return { success: true, data: { status: "authenticatorRequired", step: mfa.action === "VERIFICATION_REQUIRED" ? "verify" : mfa.action === "SETUP_REQUIRED" ? "setup" : "setupOptional" } }; } const { session } = result.data; assert(session, "Expected a session from magic-link sign-in, but got none"); writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]); return { success: true, data: { status: "signedIn", user: session.user } }; } //#endregion export { signInWithMagicLink };