Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

_authed.tsx

55 lines1.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createServerFn } from '@tanstack/react-start'
3import { hashPassword, prismaClient } from '~/utils/prisma'
4import { Login } from '~/components/Login'
5import { getAppSession } from '~/utils/session'
6​
7export const loginFn = createServerFn({ method: 'POST' })
8 .validator((d: { email: string; password: string }) => d)
9 .handler(async ({ data }) => {
10 // Find the user
11 const user = await prismaClient.user.findUnique({
12 where: {
13 email: data.email,
14 },
15 })
16​
17 // Check if the user exists
18 if (!user) {
19 return {
20 error: true,
21 userNotFound: true,
22 message: 'User not found',
23 }
24 }
25​
26 // Check if the password is correct
27 const hashedPassword = await hashPassword(data.password)
28​
29 if (user.password !== hashedPassword) {
30 return {
31 error: true,
32 message: 'Incorrect password',
33 }
34 }
35​
36 // Store the user's email in the session
37 const session = await getAppSession()
38 session.userEmail = user.email
39 await session.save()
40 })
41​
42export const Route = createFileRoute('/_authed')({
43 beforeLoad: ({ context }) => {
44 if (!context.user) {
45 throw new Error('Not authenticated')
46 }
47 },
48 errorComponent: ({ error }) => {
49 if (error instanceof Error && error.message === 'Not authenticated') {
50 return <Login />
51 }
52​
53 throw error
54 },
55})