|
| 1 | +import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node"; |
| 2 | +import { json } from "@remix-run/node"; |
| 3 | +import { Form, Link, useActionData } from "@remix-run/react"; |
| 4 | +import { ClientResponseError } from "pocketbase"; |
| 5 | + |
| 6 | +import { createSession, getPocketbase, getUser } from "~/pb.server"; |
| 7 | + |
| 8 | +interface ForgotPasswordRequestData { |
| 9 | + email: string; |
| 10 | +} |
| 11 | + |
| 12 | +export async function action({ request }: ActionFunctionArgs) { |
| 13 | + const pb = getPocketbase(request); |
| 14 | + |
| 15 | + const result = (await request.formData()) as unknown as Iterable< |
| 16 | + [ForgotPasswordRequestData, FormDataEntryValue] |
| 17 | + >; |
| 18 | + const data: ForgotPasswordRequestData = Object.fromEntries(result); |
| 19 | + |
| 20 | + try { |
| 21 | + await pb.collection("users").requestPasswordReset(data.email); |
| 22 | + |
| 23 | + return json({ |
| 24 | + success: true, |
| 25 | + error: false, |
| 26 | + message: "An email has been sent to reset your password!", |
| 27 | + }); |
| 28 | + } catch (error) { |
| 29 | + if (error instanceof ClientResponseError) { |
| 30 | + return json({ success: false, error: true, message: error.message }); |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export async function loader({ request }: LoaderFunctionArgs) { |
| 36 | + const pb = getPocketbase(request); |
| 37 | + const user = getUser(pb); |
| 38 | + |
| 39 | + const redirectUrl = "/admin"; |
| 40 | + |
| 41 | + if (user) return createSession(redirectUrl, pb); |
| 42 | + |
| 43 | + return json({ redirectUrl, user }); |
| 44 | +} |
| 45 | + |
| 46 | +export default function Login() { |
| 47 | + const actionData = useActionData<typeof action>(); |
| 48 | + |
| 49 | + return ( |
| 50 | + <Form method="post"> |
| 51 | + {actionData?.error ? <div>{actionData.message}</div> : null} |
| 52 | + {actionData?.success ? ( |
| 53 | + <div style={{ color: "green" }}>{actionData.message}</div> |
| 54 | + ) : null} |
| 55 | + <div> |
| 56 | + <label htmlFor="email">Email</label> |
| 57 | + <input |
| 58 | + type="email" |
| 59 | + name="email" |
| 60 | + id="email" |
| 61 | + defaultValue="pocketbase@remix.example" |
| 62 | + /> |
| 63 | + </div> |
| 64 | + |
| 65 | + <button>Forgot Password</button> |
| 66 | + |
| 67 | + <Link to="/login">Login</Link> |
| 68 | + </Form> |
| 69 | + ); |
| 70 | +} |
0 commit comments