Open History to see the last commit
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})