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

account.ts

77 lines2.3 KB

1import { getIronSession } from 'iron-session'
2import { createServerFn } from '@tanstack/react-start'
3import {
4 getCookie,
5 setCookie,
6 setResponseStatus,
7 setResponseHeader,
8} from '@tanstack/react-start/server'
9import { redirect } from '@tanstack/react-router'
10async function session() {
11 setResponseHeader('Cache-Control', 'private, no-store')
12 const password = process.env.SESSION_PASSWORD
13 if (!password || password.length < 32) {
14 throw new Error('Set SESSION_PASSWORD to at least 32 characters')
15 }
16 return getIronSession<{ email: string; saved: boolean }>(
17 { read: getCookie, write: setCookie },
18 {
19 cookieName: 'start-migration-session',
20 password,
21 ttl: 7 * 24 * 60 * 60,
22 cookieOptions: {
23 httpOnly: true,
24 secure: process.env.NODE_ENV === 'production',
25 sameSite: 'lax',
26 path: '/',
27 },
28 },
29 )
31export const getAccount = createServerFn({ method: 'GET' }).handler(
32 async () => {
33 const current = await session()
34 return current.email
35 ? { email: current.email, saved: current.saved ?? false }
36 : null
37 },
39export const signIn = createServerFn({ method: 'POST' })
40 .validator((input: { email: string; password: string }) => {
41 if (typeof input.email !== 'string' || typeof input.password !== 'string') {
42 throw new Error('Invalid credentials')
43 }
44 return input
45 })
46 .handler(async ({ data }) => {
47 if (!process.env.DEMO_PASSWORD) {
48 throw new Error('Set DEMO_PASSWORD before running the example')
49 }
50 if (
51 data.email !== 'reader@example.com' ||
52 data.password !== process.env.DEMO_PASSWORD
53 ) {
54 return { error: 'Invalid credentials' }
55 }
56 const current = await session()
57 current.email = data.email
58 current.saved = false
59 await current.save()
60 return { error: '' }
61 })
62export const toggleSaved = createServerFn({ method: 'POST' }).handler(
63 async () => {
64 const current = await session()
65 if (!current.email) {
66 setResponseStatus(401)
67 throw new Error('Unauthorized')
68 }
69 current.saved = !current.saved
70 await current.save()
71 },
73export const signOut = createServerFn({ method: 'POST' }).handler(async () => {
74 const current = await session()
75 current.destroy()
76 throw redirect({ to: '/login' })
77})