Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"react-dom": "^19.2.6",
"react-hook-form": "^7.92.0",
"react-leaflet": "^5.0.0",
"react-query-auth": "^2.4.3",
"recharts": "3.8.0",
"shadcn": "^4.13.0",
"shiki": "^4.6.0",
Expand Down
168 changes: 126 additions & 42 deletions src/features/auth/components/sign-in-form.tsx
Original file line number Diff line number Diff line change
@@ -1,66 +1,150 @@
import { DashRing } from "@/components/loading-ui/dash-ring"
import { Alert, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
InputGroup,
InputGroupAddon,
InputGroupInput,
} from "@/components/ui/input-group"
import { Link } from "@tanstack/react-router"
import type { SessionResponse } from "@/lib/allauth"
import { signInInputSchema, useLogin } from "@/lib/auth"
import { zodResolver } from "@hookform/resolvers/zod"
import { Link, useNavigate } from "@tanstack/react-router"
import { Eye, EyeOff } from "lucide-react"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import type z from "zod"

export function SignInForm() {
const [showPassword, setShowPassword] = useState(false)
const navigate = useNavigate()

const form = useForm<z.infer<typeof signInInputSchema>>({
resolver: zodResolver(signInInputSchema),
defaultValues: { email: "", password: "" },
})

const login = useLogin({
onSuccess: () => navigate({ to: "/" }),
onError: (error) => {
const res = error as unknown as SessionResponse

if (res.status === 400) {
form.setError("root", {
type: "manual",
message: "Invalid email or password",
})
} else if (
res.status === 401 &&
res.data.flows.some((f) => f.id === "verify_email" && f.is_pending)
) {
form.setError("root", {
type: "manual",
message: "Please verify your email before signing in.",
})
} else {
form.setError("root", {
type: "manual",
message: "An unexpected error occurred. Please try again later.",
})
}
},
})

return (
<form>
<form onSubmit={form.handleSubmit((values) => login.mutate(values))}>
<FieldGroup>
{form.formState.errors.root && (
<Alert className="border-red-200 bg-red-50 text-red-900 dark:border-red-900 dark:bg-red-950 dark:text-red-50">
<AlertTitle>{form.formState.errors.root.message}</AlertTitle>
</Alert>
)}

{/* email */}
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
type="email"
placeholder="you@bloca.gov.ph"
required
className="h-12"
/>
</Field>
<Controller
name="email"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="email">
Email <span className="text-destructive">*</span>
</FieldLabel>
<Input
{...field}
aria-invalid={fieldState.invalid}
id="email"
type="email"
placeholder="you@bloca.gov.ph"
className="h-12"
/>

{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</Field>
)}
/>

{/* password */}
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<InputGroup className="h-12">
<InputGroupInput
id="password"
type={showPassword ? "text" : "password"}
placeholder="Enter your password"
required
/>
<InputGroupAddon align="inline-end">
<Button
type="button"
variant="ghost"
size="icon-lg"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff /> : <Eye />}
</Button>
</InputGroupAddon>
</InputGroup>
<Controller
name="password"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="password">
Password <span className="text-destructive">*</span>
</FieldLabel>
<InputGroup className="h-12">
<InputGroupInput
{...field}
aria-invalid={fieldState.invalid}
id="password"
type={showPassword ? "text" : "password"}
placeholder="Enter your password"
/>
<InputGroupAddon align="inline-end">
<Button
type="button"
variant="ghost"
size="icon-lg"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOff /> : <Eye />}
</Button>
</InputGroupAddon>
</InputGroup>

<Link
to="/auth/forgot-password"
className="text-right text-sm font-semibold text-primary hover:underline"
>
Forgot password?
</Link>
</Field>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}

<Link
to="/auth/forgot-password"
className="text-right text-sm font-light text-primary hover:underline"
>
Forgot password?
</Link>
</Field>
)}
/>

<Field orientation="horizontal">
<Button type="submit" className="h-12 w-full">
Sign In
<Button
type="submit"
className="h-12 w-full"
disabled={login.isPending || !form.formState.isDirty}
>
{login.isPending ? (
<>
<DashRing />
Signing in...
</>
) : (
"Sign in"
)}
</Button>
</Field>
</FieldGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export function AddMachineForm({ onSubmit, isPending }: Props) {
</FieldLabel>
<Input
{...field}
id="name"
aria-invalid={fieldState.invalid}
id="name"
placeholder="e.g. BLOCA-machine0"
autoComplete="off"
/>
Expand All @@ -75,8 +75,8 @@ export function AddMachineForm({ onSubmit, isPending }: Props) {
<FieldLabel htmlFor="site">Site</FieldLabel>
<Input
{...field}
id="site"
aria-invalid={fieldState.invalid}
id="site"
placeholder="e.g. Bagong Silang, Caloocan"
autoComplete="off"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ export function UpdateMachineForm({ machine }: Props) {
</FieldLabel>
<Input
{...field}
id="name"
aria-invalid={fieldState.invalid}
id="name"
placeholder="e.g. BLOCA-machine0"
autoComplete="off"
/>
Expand All @@ -95,8 +95,8 @@ export function UpdateMachineForm({ machine }: Props) {
<FieldLabel htmlFor="site">Site</FieldLabel>
<Input
{...field}
id="site"
aria-invalid={fieldState.invalid}
id="site"
placeholder="e.g. Bagong Silang, Caloocan"
autoComplete="off"
/>
Expand Down
43 changes: 43 additions & 0 deletions src/lib/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { configureAuth } from "react-query-auth"
import { getAuth, login, logout, type LoginPayload } from "./allauth"
import { z } from "zod"

export const userKey = ["authenticated-user"]

export async function userFn() {
const res = await getAuth()
if (res.status === 200 && res.meta.is_authenticated) return res.data.user
return null
}

export const signInInputSchema = z.object({
email: z.email("Please enter a valid email address"),
password: z.string().min(1, "Password is required"),
})

async function loginFn(payload: LoginPayload) {
const res = await login(payload)

if (res.status === 200) return res.data.user

throw res
}

async function logoutFn() {
await logout()
}

async function registerFn() {
return null
}

const authConfig = {
userKey,
userFn,
loginFn,
logoutFn,
registerFn,
}

export const { useUser, useLogin, useLogout, AuthLoader } =
configureAuth(authConfig)
4 changes: 2 additions & 2 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
import { routeTree } from "./routeTree.gen"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import "./index.css"
// import { init } from "./init"
import { init } from "./init"

// init()
init()

const queryClient = new QueryClient()

Expand Down
22 changes: 8 additions & 14 deletions src/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,17 @@ import {
import { type QueryClient } from "@tanstack/react-query"
import { Toaster } from "sonner"
import Providers from "./-providers"
// import { getAuth } from "@/lib/allauth"
import { userFn, userKey } from "@/lib/auth"

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()(
{
// beforeLoad: async ({ context }) => {
// const session = await context.queryClient.ensureQueryData({
// queryKey: ["authSession"],
// queryFn: async () => {
// const res = await getAuth()
// return {
// isAuthenticated: res.status === 200 && res.meta.is_authenticated,
// user: res.status === 200 ? res.data.user : null,
// }
// },
// })
// return { session }
// },
beforeLoad: async ({ context }) => {
const session = await context.queryClient.ensureQueryData({
queryKey: userKey,
queryFn: userFn,
})
return { session }
},
component: RootComponent,
notFoundComponent: () => {
return (
Expand Down
11 changes: 6 additions & 5 deletions src/routes/_authenticated/route.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import AdminPanelLayout from "@/components/admin-panel/admin-panel-layout"
import { ContentLayout } from "@/components/admin-panel/content-layout"
import { createFileRoute, Outlet } from "@tanstack/react-router"
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router"

export const Route = createFileRoute("/_authenticated")({
// beforeLoad: ({ context }) => {
// const { isAuthenticated } = context.session
// throw redirect({ to: isAuthenticated ? "/dashboard" : "/auth/sign-in" })
// },
beforeLoad: ({ context }) => {
if (!context.session) {
throw redirect({ to: "/auth/sign-in" })
}
},
staticData: { breadcrumb: "Overview" },
component: OverviewLayout,
})
Expand Down
7 changes: 6 additions & 1 deletion src/routes/_unauthenticated/route.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { cn } from "@/lib/utils"
import { createFileRoute, Outlet } from "@tanstack/react-router"
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router"

export const Route = createFileRoute("/_unauthenticated")({
beforeLoad: ({ context }) => {
if (context.session) {
throw redirect({ to: "/" })
}
},
component: UnauthenticatedLayout,
})

Expand Down