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

signup.tsx

100 lines2.4 KB

1import { createFileRoute, redirect } from '@tanstack/solid-router'
2import { createServerFn, useServerFn } from '@tanstack/solid-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 any 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 class="text-red-400">{signupMutation.data()?.message}</div>
95 </>
96 ) : null
97 }
98 />
99 )