implement session/auth token login

This commit is contained in:
2025-05-15 14:48:52 +01:00
parent 37cdf30159
commit f048dee6e2
5 changed files with 140 additions and 41 deletions

View File

@@ -1,14 +1,20 @@
import { useNavigate } from "@tanstack/react-router"
import { useState } from "react"
import { useEffect, useState } from "react"
import { createFileRoute } from "@tanstack/react-router"
import { FormField } from "~/components/form-field"
import { Button } from "~/components/button"
import { useLogin } from "~/auth"
import { useCookieLogin, useLogin } from "~/auth"
import { LoadingSpinner } from "~/components/loading-spinner"
function Page() {
const [error, setError] = useState("")
const navigate = useNavigate()
const loginMutation = useLogin()
const cookieLoginMutation = useCookieLogin()
useEffect(() => {
cookieLoginMutation.mutate()
}, [])
async function submitLoginForm(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
@@ -57,19 +63,27 @@ function Page() {
</h1>
</div>
<div className="container max-w-2xl">
<h2 className="font-bold">LOG IN TO YOUR ACCOUNT</h2>
{error ? (
<div className="border border-red-500 text-red-500 p-3 my-4">
<p className="text-red-500 font-bold">{error}</p>
</div>
) : null}
<form onSubmit={submitLoginForm}>
<FormField type="text" name="username" label="USERNAME" className="mb-2" />
<FormField type="password" name="password" label="PASSWORD" className="mb-8" />
<Button className="w-full py-2 md:py-2" type="submit">
Log in
</Button>
</form>
{cookieLoginMutation.status === "pending" ? (
<p>
Checking existing login <LoadingSpinner />
</p>
) : (
<>
<h2 className="font-bold">LOG IN TO YOUR ACCOUNT</h2>
{error ? (
<div className="border border-red-500 text-red-500 p-3 my-4">
<p className="text-red-500 font-bold">{error}</p>
</div>
) : null}
<form onSubmit={submitLoginForm}>
<FormField type="text" name="username" label="USERNAME" className="mb-2" />
<FormField type="password" name="password" label="PASSWORD" className="mb-8" />
<Button className="w-full py-2 md:py-2" type="submit">
Log in
</Button>
</form>
</>
)}
</div>
</main>
)

View File

@@ -1,5 +1,18 @@
import { useMutation } from "@tanstack/react-query"
import { fetchApi } from "./api"
import { useNavigate } from "@tanstack/react-router"
function useCookieLogin() {
const navigate = useNavigate()
return useMutation({
mutationFn: async () => fetchApi("/login", { method: "POST" }),
onSuccess: () => {
navigate({ to: "/bookmarks", replace: true })
},
retry: false,
})
}
function useLogin() {
return useMutation({
@@ -33,4 +46,4 @@ function useSignUp() {
})
}
export { useLogin, useLogOut, useSignUp }
export { useCookieLogin, useLogin, useLogOut, useSignUp }