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

_authed.tsx

58 lines1.4 KB

1import { createFileRoute } from '@tanstack/solid-router'
2import { createServerFn } from '@tanstack/solid-start'
3import { hashPassword, prismaClient } from '~/utils/prisma'
4import { Login } from '~/components/Login'
5import { useAppSession } 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 // Create a session
37 const session = await useAppSession()
38​
39 // Store the user's email in the session
40 await session.update({
41 userEmail: user.email,
42 })
43 })
44​
45export const Route = createFileRoute('/_authed')({
46 beforeLoad: ({ context }) => {
47 if (!context.user) {
48 throw new Error('Not authenticated')
49 }
50 },
51 errorComponent: ({ error }) => {
52 if (error.message === 'Not authenticated') {
53 return <Login />
54 }
55​
56 throw error
57 },
58})