// type LoginActionResponse =
// | { ok: true; data: Pick<LoginResponse, "username" | "image" | "verified"> }
// | {
// ok: false;
// code:
// | "InvalidCredential"
// | "InvalidLogin"
// | "Unknown"
// | "MissingTOTP"
// | "WrongTOTP";
// };
// Create a custom refinement for validating a phone number
const phoneNumberSchema = z
.string()
.refine((value) => true, { message: "Invalid phone number" });
// Create a schema for validating an email
const emailSchema = z.string().email({ message: "Invalid email address" });
// Combine the phone and email schemas into one using z.union
const credentialSchema = z.union([phoneNumberSchema, emailSchema]);
// Create the full login schema
const loginSchema = z.object({
credential: credentialSchema,
password: z.string(),
isrememberme: z.boolean(),
});
export const login = createServerFn({ method: "POST" })
.validator(loginSchema)
.handler(async ({ data }) => {
const res = await fetch(
`${baseUrl}login`,
postJson({
credential: data.credential,
password: data.password,
}),
);
try {
const userData = (await handleJsonWithCodeIfOk(
res,
"login",
)) as LoginResponse;
await setAuthCookies(userData);
return {
ok: true,
data: {
username: userData.username,
image: userData.image,
verified: userData.verified,
},
};
} catch (e) {
if (e instanceof Error) {
return {
ok: false,
code: e.message as any,
};
}
return {
ok: false,
code: "Unknown",
};
}
});
// type LoginActionResponse =
// | { ok: true; data: Pick<LoginResponse, "username" | "image" | "verified"> }
// | {
// ok: false;
// code:
// | "InvalidCredential"
// | "InvalidLogin"
// | "Unknown"
// | "MissingTOTP"
// | "WrongTOTP";
// };
// Create a custom refinement for validating a phone number
const phoneNumberSchema = z
.string()
.refine((value) => true, { message: "Invalid phone number" });
// Create a schema for validating an email
const emailSchema = z.string().email({ message: "Invalid email address" });
// Combine the phone and email schemas into one using z.union
const credentialSchema = z.union([phoneNumberSchema, emailSchema]);
// Create the full login schema
const loginSchema = z.object({
credential: credentialSchema,
password: z.string(),
isrememberme: z.boolean(),
});
export const login = createServerFn({ method: "POST" })
.validator(loginSchema)
.handler(async ({ data }) => {
const res = await fetch(
`${baseUrl}login`,
postJson({
credential: data.credential,
password: data.password,
}),
);
try {
const userData = (await handleJsonWithCodeIfOk(
res,
"login",
)) as LoginResponse;
await setAuthCookies(userData);
return {
ok: true,
data: {
username: userData.username,
image: userData.image,
verified: userData.verified,
},
};
} catch (e) {
if (e instanceof Error) {
return {
ok: false,
code: e.message as any,
};
}
return {
ok: false,
code: "Unknown",
};
}
});