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