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