Open History to see the last commit
1import { redirect, createFileRoute } from '@tanstack/react-router'
2import { createServerFn, useServerFn } from '@tanstack/react-start'
3import { hashPassword, prismaClient } from '~/utils/prisma'
4import { useMutation } from '~/hooks/useMutation'
5import { Auth } from '~/components/Auth'
6import { useAppSession } from '~/utils/session'
7β
8export const signupFn = createServerFn({ method: 'POST' })
9 .validator(
10 (d: { email: string; password: string; redirectUrl?: string }) => d,
11 )
12 .handler(async ({ data }) => {
13 // Check if the user already exists
14 const found = await prismaClient.user.findUnique({
15 where: {
16 email: data.email,
17 },
18 })
19β
20 // Encrypt the password using Sha256 into plaintext
21 const password = await hashPassword(data.password)
22β
23 // Create a session
24 const session = await useAppSession()
25β
26 if (found) {
27 if (found.password !== password) {
28 return {
29 error: true,
30 userExists: true,
31 message: 'User already exists',
32 }
33 }
34β
35 // Store the user's email in the session
36 await session.update({
37 userEmail: found.email,
38 })
39β
40 // Redirect to the prev page stored in the "redirect" search param
41 throw redirect({
42 href: data.redirectUrl || '/',
43 })
44 }
45β
46 // Create the user
47 const user = await prismaClient.user.create({
48 data: {
49 email: data.email,
50 password,
51 },
52 })
53β
54 // Store the user's email in the session
55 await session.update({
56 userEmail: user.email,
57 })
58β
59 // Redirect to the prev page stored in the "redirect" search param
60 throw redirect({
61 href: data.redirectUrl || '/',
62 })
63 })
64β
65export const Route = createFileRoute('/signup')({
66 component: SignupComp,
67})
68β
69function SignupComp() {
70 const signupMutation = useMutation({
71 fn: useServerFn(signupFn),
72 })
73β
74 return (
75 <Auth
76 actionText="Sign Up"
77 status={signupMutation.status}
78 onSubmit={(e) => {
79 const formData = new FormData(e.target as HTMLFormElement)
80β
81 signupMutation.mutate({
82 data: {
83 email: formData.get('email') as string,
84 password: formData.get('password') as string,
85 },
86 })
87 }}
88 afterSubmit={
89 signupMutation.data?.error ? (
90 <>
91 <div className="text-red-400">{signupMutation.data.message}</div>
92 </>
93 ) : null
94 }
95 />
96 )
97}