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

signup.tsx

94 lines2.4 KB

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 { getAppSession } 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 if (found) {
24 if (found.password !== password) {
25 return {
26 error: true,
27 userExists: true,
28 message: 'User already exists',
29 }
30 }
31​
32 // Store the user's email in the session
33 const session = await getAppSession()
34 session.userEmail = found.email
35 await session.save()
36​
37 // Redirect to the prev page stored in the "redirect" search param
38 throw redirect({
39 href: data.redirectUrl || '/',
40 })
41 }
42​
43 // Create the user
44 const user = await prismaClient.user.create({
45 data: {
46 email: data.email,
47 password,
48 },
49 })
50​
51 // Store the user's email in the session
52 const session = await getAppSession()
53 session.userEmail = user.email
54 await session.save()
55​
56 // Redirect to the prev page stored in the "redirect" search param
57 throw redirect({
58 href: data.redirectUrl || '/',
59 })
60 })
61​
62export const Route = createFileRoute('/signup')({
63 component: SignupComp,
64})
65​
66function SignupComp() {
67 const signupMutation = useMutation({
68 fn: useServerFn(signupFn),
69 })
70​
71 return (
72 <Auth
73 actionText="Sign Up"
74 status={signupMutation.status}
75 onSubmit={(e) => {
76 const formData = new FormData(e.target as HTMLFormElement)
77​
78 signupMutation.mutate({
79 data: {
80 email: formData.get('email') as string,
81 password: formData.get('password') as string,
82 },
83 })
84 }}
85 afterSubmit={
86 signupMutation.data?.error ? (
87 <>
88 <div className="text-red-400">{signupMutation.data.message}</div>
89 </>
90 ) : null
91 }
92 />
93 )