Adds auth guards

This commit is contained in:
2025-05-27 18:07:12 -07:00
parent c42eb650b5
commit b96fe1371e
8 changed files with 135 additions and 82 deletions

View File

@@ -7,3 +7,7 @@ import PocketBase from "pocketbase";
import { POCKETBASE_URL } from "@/config"; import { POCKETBASE_URL } from "@/config";
export const pb = new PocketBase(POCKETBASE_URL); export const pb = new PocketBase(POCKETBASE_URL);
export function isAuthenticated(): boolean {
return pb.authStore.isValid;
}

View File

@@ -13,10 +13,11 @@
import { Route as rootRoute } from './routes/__root' import { Route as rootRoute } from './routes/__root'
import { Route as LoginImport } from './routes/login' import { Route as LoginImport } from './routes/login'
import { Route as AboutImport } from './routes/about' import { Route as AboutImport } from './routes/about'
import { Route as AuthenticatedImport } from './routes/_authenticated'
import { Route as IndexImport } from './routes/index' import { Route as IndexImport } from './routes/index'
import { Route as SessionsIndexImport } from './routes/sessions.index' import { Route as AuthenticatedSessionsIndexImport } from './routes/_authenticated/sessions.index'
import { Route as CampaignsIndexImport } from './routes/campaigns.index' import { Route as AuthenticatedCampaignsIndexImport } from './routes/_authenticated/campaigns.index'
import { Route as CampaignsCampaignIdImport } from './routes/campaigns.$campaignId' import { Route as AuthenticatedCampaignsCampaignIdImport } from './routes/_authenticated/campaigns.$campaignId'
// Create/Update Routes // Create/Update Routes
@@ -32,28 +33,37 @@ const AboutRoute = AboutImport.update({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
} as any) } as any)
const AuthenticatedRoute = AuthenticatedImport.update({
id: '/_authenticated',
getParentRoute: () => rootRoute,
} as any)
const IndexRoute = IndexImport.update({ const IndexRoute = IndexImport.update({
id: '/', id: '/',
path: '/', path: '/',
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
} as any) } as any)
const SessionsIndexRoute = SessionsIndexImport.update({ const AuthenticatedSessionsIndexRoute = AuthenticatedSessionsIndexImport.update(
{
id: '/sessions/', id: '/sessions/',
path: '/sessions/', path: '/sessions/',
getParentRoute: () => rootRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any,
)
const CampaignsIndexRoute = CampaignsIndexImport.update({ const AuthenticatedCampaignsIndexRoute =
AuthenticatedCampaignsIndexImport.update({
id: '/campaigns/', id: '/campaigns/',
path: '/campaigns/', path: '/campaigns/',
getParentRoute: () => rootRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any)
const CampaignsCampaignIdRoute = CampaignsCampaignIdImport.update({ const AuthenticatedCampaignsCampaignIdRoute =
AuthenticatedCampaignsCampaignIdImport.update({
id: '/campaigns/$campaignId', id: '/campaigns/$campaignId',
path: '/campaigns/$campaignId', path: '/campaigns/$campaignId',
getParentRoute: () => rootRoute, getParentRoute: () => AuthenticatedRoute,
} as any) } as any)
// Populate the FileRoutesByPath interface // Populate the FileRoutesByPath interface
@@ -67,6 +77,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexImport preLoaderRoute: typeof IndexImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/_authenticated': {
id: '/_authenticated'
path: ''
fullPath: ''
preLoaderRoute: typeof AuthenticatedImport
parentRoute: typeof rootRoute
}
'/about': { '/about': {
id: '/about' id: '/about'
path: '/about' path: '/about'
@@ -81,64 +98,84 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof LoginImport preLoaderRoute: typeof LoginImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/campaigns/$campaignId': { '/_authenticated/campaigns/$campaignId': {
id: '/campaigns/$campaignId' id: '/_authenticated/campaigns/$campaignId'
path: '/campaigns/$campaignId' path: '/campaigns/$campaignId'
fullPath: '/campaigns/$campaignId' fullPath: '/campaigns/$campaignId'
preLoaderRoute: typeof CampaignsCampaignIdImport preLoaderRoute: typeof AuthenticatedCampaignsCampaignIdImport
parentRoute: typeof rootRoute parentRoute: typeof AuthenticatedImport
} }
'/campaigns/': { '/_authenticated/campaigns/': {
id: '/campaigns/' id: '/_authenticated/campaigns/'
path: '/campaigns' path: '/campaigns'
fullPath: '/campaigns' fullPath: '/campaigns'
preLoaderRoute: typeof CampaignsIndexImport preLoaderRoute: typeof AuthenticatedCampaignsIndexImport
parentRoute: typeof rootRoute parentRoute: typeof AuthenticatedImport
} }
'/sessions/': { '/_authenticated/sessions/': {
id: '/sessions/' id: '/_authenticated/sessions/'
path: '/sessions' path: '/sessions'
fullPath: '/sessions' fullPath: '/sessions'
preLoaderRoute: typeof SessionsIndexImport preLoaderRoute: typeof AuthenticatedSessionsIndexImport
parentRoute: typeof rootRoute parentRoute: typeof AuthenticatedImport
} }
} }
} }
// Create and export the route tree // Create and export the route tree
interface AuthenticatedRouteChildren {
AuthenticatedCampaignsCampaignIdRoute: typeof AuthenticatedCampaignsCampaignIdRoute
AuthenticatedCampaignsIndexRoute: typeof AuthenticatedCampaignsIndexRoute
AuthenticatedSessionsIndexRoute: typeof AuthenticatedSessionsIndexRoute
}
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
AuthenticatedCampaignsCampaignIdRoute: AuthenticatedCampaignsCampaignIdRoute,
AuthenticatedCampaignsIndexRoute: AuthenticatedCampaignsIndexRoute,
AuthenticatedSessionsIndexRoute: AuthenticatedSessionsIndexRoute,
}
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
AuthenticatedRouteChildren,
)
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'': typeof AuthenticatedRouteWithChildren
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/campaigns/$campaignId': typeof CampaignsCampaignIdRoute '/campaigns/$campaignId': typeof AuthenticatedCampaignsCampaignIdRoute
'/campaigns': typeof CampaignsIndexRoute '/campaigns': typeof AuthenticatedCampaignsIndexRoute
'/sessions': typeof SessionsIndexRoute '/sessions': typeof AuthenticatedSessionsIndexRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'': typeof AuthenticatedRouteWithChildren
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/campaigns/$campaignId': typeof CampaignsCampaignIdRoute '/campaigns/$campaignId': typeof AuthenticatedCampaignsCampaignIdRoute
'/campaigns': typeof CampaignsIndexRoute '/campaigns': typeof AuthenticatedCampaignsIndexRoute
'/sessions': typeof SessionsIndexRoute '/sessions': typeof AuthenticatedSessionsIndexRoute
} }
export interface FileRoutesById { export interface FileRoutesById {
__root__: typeof rootRoute __root__: typeof rootRoute
'/': typeof IndexRoute '/': typeof IndexRoute
'/_authenticated': typeof AuthenticatedRouteWithChildren
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/login': typeof LoginRoute '/login': typeof LoginRoute
'/campaigns/$campaignId': typeof CampaignsCampaignIdRoute '/_authenticated/campaigns/$campaignId': typeof AuthenticatedCampaignsCampaignIdRoute
'/campaigns/': typeof CampaignsIndexRoute '/_authenticated/campaigns/': typeof AuthenticatedCampaignsIndexRoute
'/sessions/': typeof SessionsIndexRoute '/_authenticated/sessions/': typeof AuthenticatedSessionsIndexRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: fullPaths:
| '/' | '/'
| ''
| '/about' | '/about'
| '/login' | '/login'
| '/campaigns/$campaignId' | '/campaigns/$campaignId'
@@ -147,6 +184,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: to:
| '/' | '/'
| ''
| '/about' | '/about'
| '/login' | '/login'
| '/campaigns/$campaignId' | '/campaigns/$campaignId'
@@ -155,30 +193,27 @@ export interface FileRouteTypes {
id: id:
| '__root__' | '__root__'
| '/' | '/'
| '/_authenticated'
| '/about' | '/about'
| '/login' | '/login'
| '/campaigns/$campaignId' | '/_authenticated/campaigns/$campaignId'
| '/campaigns/' | '/_authenticated/campaigns/'
| '/sessions/' | '/_authenticated/sessions/'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
AboutRoute: typeof AboutRoute AboutRoute: typeof AboutRoute
LoginRoute: typeof LoginRoute LoginRoute: typeof LoginRoute
CampaignsCampaignIdRoute: typeof CampaignsCampaignIdRoute
CampaignsIndexRoute: typeof CampaignsIndexRoute
SessionsIndexRoute: typeof SessionsIndexRoute
} }
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
AuthenticatedRoute: AuthenticatedRouteWithChildren,
AboutRoute: AboutRoute, AboutRoute: AboutRoute,
LoginRoute: LoginRoute, LoginRoute: LoginRoute,
CampaignsCampaignIdRoute: CampaignsCampaignIdRoute,
CampaignsIndexRoute: CampaignsIndexRoute,
SessionsIndexRoute: SessionsIndexRoute,
} }
export const routeTree = rootRoute export const routeTree = rootRoute
@@ -192,30 +227,39 @@ export const routeTree = rootRoute
"filePath": "__root.tsx", "filePath": "__root.tsx",
"children": [ "children": [
"/", "/",
"/_authenticated",
"/about", "/about",
"/login", "/login"
"/campaigns/$campaignId",
"/campaigns/",
"/sessions/"
] ]
}, },
"/": { "/": {
"filePath": "index.tsx" "filePath": "index.tsx"
}, },
"/_authenticated": {
"filePath": "_authenticated.tsx",
"children": [
"/_authenticated/campaigns/$campaignId",
"/_authenticated/campaigns/",
"/_authenticated/sessions/"
]
},
"/about": { "/about": {
"filePath": "about.tsx" "filePath": "about.tsx"
}, },
"/login": { "/login": {
"filePath": "login.tsx" "filePath": "login.tsx"
}, },
"/campaigns/$campaignId": { "/_authenticated/campaigns/$campaignId": {
"filePath": "campaigns.$campaignId.tsx" "filePath": "_authenticated/campaigns.$campaignId.tsx",
"parent": "/_authenticated"
}, },
"/campaigns/": { "/_authenticated/campaigns/": {
"filePath": "campaigns.index.tsx" "filePath": "_authenticated/campaigns.index.tsx",
"parent": "/_authenticated"
}, },
"/sessions/": { "/_authenticated/sessions/": {
"filePath": "sessions.index.tsx" "filePath": "_authenticated/sessions.index.tsx",
"parent": "/_authenticated"
} }
} }
} }

View File

@@ -0,0 +1,12 @@
import { isAuthenticated } from "@/lib/pocketbase";
import { createFileRoute, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated")({
beforeLoad: () => {
if (!isAuthenticated()) {
throw redirect({
to: "/login",
});
}
},
});

View File

@@ -1,6 +1,6 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/campaigns/$campaignId")({ export const Route = createFileRoute("/_authenticated/campaigns/$campaignId")({
component: RouteComponent, component: RouteComponent,
}); });

View File

@@ -1,6 +1,6 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/campaigns/")({ export const Route = createFileRoute("/_authenticated/campaigns/")({
component: RouteComponent, component: RouteComponent,
}); });

View File

@@ -1,6 +1,6 @@
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/sessions/')({ export const Route = createFileRoute('/_authenticated/sessions/')({
component: RouteComponent, component: RouteComponent,
}) })

View File

@@ -1,4 +1,4 @@
import { createFileRoute, Link } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/")({ export const Route = createFileRoute("/")({
component: App, component: App,
@@ -7,14 +7,7 @@ export const Route = createFileRoute("/")({
function App() { function App() {
return ( return (
<div className="text-center"> <div className="text-center">
<header className="min-h-screen flex flex-col items-center justify-center bg-[#282c34] text-white text-[calc(10px+2vmin)]"> <h1>Welcome to the DM's Companion</h1>
<h1>Hello, Tanstack</h1>
</header>
<div>
<Link to="/campaigns" activeProps={{ className: "weight-bold" }}>
Campaigns
</Link>
</div>
</div> </div>
); );
} }

View File

@@ -1,19 +1,26 @@
import { useState, useEffect } from "react";
import { useAuth } from "@/context/auth/AuthContext"; import { useAuth } from "@/context/auth/AuthContext";
import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { isAuthenticated } from "@/lib/pocketbase";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { ClientResponseError } from "pocketbase"; import { ClientResponseError } from "pocketbase";
import { useState } from "react";
/** /**
* Login and signup page for authentication. * Login and signup page for authentication.
* Allows users to log in or create a new account. * Allows users to log in or create a new account.
*/ */
export const Route = createFileRoute("/login")({ export const Route = createFileRoute("/login")({
beforeLoad: () => {
if (isAuthenticated()) {
throw redirect({
to: "/",
});
}
},
component: LoginPage, component: LoginPage,
}); });
function LoginPage() { function LoginPage() {
const { login, signup, user, isLoading } = useAuth(); const { login, signup, isLoading } = useAuth();
const navigate = useNavigate();
const [mode, setMode] = useState<"login" | "signup">("login"); const [mode, setMode] = useState<"login" | "signup">("login");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -26,12 +33,6 @@ function LoginPage() {
}>({}); }>({});
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (user) {
navigate({ to: "/" });
}
}, [user, navigate]);
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
@@ -55,9 +56,8 @@ function LoginPage() {
password: err.response.data.password?.message, password: err.response.data.password?.message,
passwordConfirm: err.response.data.passwordConfirm?.message, passwordConfirm: err.response.data.passwordConfirm?.message,
}); });
} else {
setError((err as Error)?.message || "Authentication failed");
} }
setError((err as Error)?.message || "Authentication failed");
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }