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

_authed.tsx

61 lines1.4 KB

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