|
| 1 | +import { redirect } from '@sveltejs/kit'; |
| 2 | + |
| 3 | +import { superValidate } from 'sveltekit-superforms/server'; |
| 4 | +import { zod } from 'sveltekit-superforms/adapters'; |
| 5 | + |
| 6 | +import type { |
| 7 | + AuthForm, |
| 8 | + AuthFormCreationStrategies, |
| 9 | + AuthFormValidationStrategies, |
| 10 | +} from '$lib/types/auth_forms'; |
| 11 | + |
| 12 | +import { authSchema } from '$lib/zod/schema'; |
| 13 | +import { SEE_OTHER } from '$lib/constants/http-response-status-codes'; |
| 14 | +import { HOME_PAGE } from '$lib/constants/navbar-links'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Initialize authentication form pages (login/signup) |
| 18 | + * Redirects to home page if already logged in, |
| 19 | + * otherwise initializes the authentication form for unauthenticated users |
| 20 | + * @param locals - The application locals containing authentication state |
| 21 | + * @returns { form: AuthForm } - The initialized authentication form |
| 22 | + */ |
| 23 | +export const initializeAuthForm = async (locals: App.Locals): Promise<{ form: AuthForm }> => { |
| 24 | + const session = await locals.auth.validate(); |
| 25 | + |
| 26 | + if (session) { |
| 27 | + redirect(SEE_OTHER, HOME_PAGE); |
| 28 | + } |
| 29 | + |
| 30 | + return await createAuthFormWithFallback(); |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * Create authentication form with comprehensive fallback handling |
| 35 | + * Tries multiple strategies until one succeeds |
| 36 | + */ |
| 37 | +export const createAuthFormWithFallback = async (): Promise<{ form: AuthForm }> => { |
| 38 | + for (const strategy of formCreationStrategies) { |
| 39 | + try { |
| 40 | + const result = await strategy.run(); |
| 41 | + |
| 42 | + return result; |
| 43 | + } catch (error) { |
| 44 | + if (isDevelopmentMode()) { |
| 45 | + console.warn(`Create authForm strategy: Failed to ${strategy.name}`); |
| 46 | + console.warn(error instanceof Error ? (error.stack ?? error.message) : error); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // This should never be reached due to manual creation strategy |
| 52 | + throw new Error('Failed to create form for authentication.'); |
| 53 | +}; |
| 54 | + |
| 55 | +/** |
| 56 | + * Form creation strategies in order of preference |
| 57 | + * Each strategy attempts a different approach to create a valid form |
| 58 | + * |
| 59 | + * See: |
| 60 | + * https://superforms.rocks/migration-v2#supervalidate |
| 61 | + * https://superforms.rocks/concepts/client-validation |
| 62 | + * https://superforms.rocks/api#supervalidate-options |
| 63 | + */ |
| 64 | +const formCreationStrategies: AuthFormCreationStrategies = [ |
| 65 | + { |
| 66 | + name: '(Basic case) Use standard superValidate', |
| 67 | + async run() { |
| 68 | + const form = await superValidate(zod(authSchema)); |
| 69 | + return { form: { ...form, message: '' } }; |
| 70 | + }, |
| 71 | + }, |
| 72 | + { |
| 73 | + name: 'Create form by manually defining structure', |
| 74 | + async run() { |
| 75 | + const defaultForm = { |
| 76 | + valid: false, |
| 77 | + posted: false, |
| 78 | + errors: {}, |
| 79 | + message: '', |
| 80 | + ...createBaseAuthForm(), |
| 81 | + }; |
| 82 | + |
| 83 | + return { form: { ...defaultForm, message: '' } }; |
| 84 | + }, |
| 85 | + }, |
| 86 | +]; |
| 87 | + |
| 88 | +/** |
| 89 | + * Validate authentication form data with comprehensive fallback handling |
| 90 | + * Tries multiple strategies until one succeeds |
| 91 | + * |
| 92 | + * @param request - The incoming request containing form data |
| 93 | + * @returns The validated form object (bare form, suitable for actions: fail(..., { form })) |
| 94 | + */ |
| 95 | +export const validateAuthFormWithFallback = async (request: Request): Promise<AuthForm> => { |
| 96 | + for (const strategy of formValidationStrategies) { |
| 97 | + try { |
| 98 | + const result = await strategy.run(request); |
| 99 | + |
| 100 | + return result.form; |
| 101 | + } catch (error) { |
| 102 | + if (isDevelopmentMode()) { |
| 103 | + console.warn(`Validate authForm strategy: Failed to ${strategy.name}`); |
| 104 | + console.warn(error instanceof Error ? (error.stack ?? error.message) : error); |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + // This should never be reached due to fallback strategy |
| 110 | + throw new Error('Failed to validate form for authentication.'); |
| 111 | +}; |
| 112 | + |
| 113 | +/** |
| 114 | + * Form validation strategies for action handlers |
| 115 | + * Each strategy attempts a different approach to validate form data from requests |
| 116 | + */ |
| 117 | +const formValidationStrategies: AuthFormValidationStrategies = [ |
| 118 | + { |
| 119 | + name: '(Basic Case) Use standard superValidate with request', |
| 120 | + async run(request: Request) { |
| 121 | + const form = await superValidate(request, zod(authSchema)); |
| 122 | + return { form: { ...form, message: '' } }; |
| 123 | + }, |
| 124 | + }, |
| 125 | + { |
| 126 | + name: 'Create fallback form manually', |
| 127 | + async run(_request: Request) { |
| 128 | + // Create a fallback form with error state |
| 129 | + // This maintains consistency with other strategies by returning { form } |
| 130 | + const fallbackForm = { |
| 131 | + valid: false, |
| 132 | + posted: true, |
| 133 | + errors: { _form: ['ログインできませんでした。'] }, |
| 134 | + message: 'サーバでエラーが発生しました。本サービスの開発・運営チームまでご連絡ください。', |
| 135 | + ...createBaseAuthForm(), |
| 136 | + }; |
| 137 | + |
| 138 | + return { form: fallbackForm }; |
| 139 | + }, |
| 140 | + }, |
| 141 | +]; |
| 142 | + |
| 143 | +/** |
| 144 | + * Helper function to validate if we're in development mode |
| 145 | + * This can be mocked in tests to control logging behavior |
| 146 | + */ |
| 147 | +export const isDevelopmentMode = (): boolean => { |
| 148 | + return import.meta.env.DEV; |
| 149 | +}; |
| 150 | + |
| 151 | +/** |
| 152 | + * Common form structure for authentication forms |
| 153 | + * Contains constraints and shape definitions used across different form strategies |
| 154 | + */ |
| 155 | +const createBaseAuthForm = () => ({ |
| 156 | + id: getBaseAuthFormId(), |
| 157 | + data: { username: '', password: '' }, |
| 158 | + constraints: { |
| 159 | + username: { minlength: 3, maxlength: 24, required: true, pattern: '[\\w]*' }, |
| 160 | + password: { |
| 161 | + minlength: 8, |
| 162 | + maxlength: 128, |
| 163 | + required: true, |
| 164 | + pattern: '(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)[a-zA-Z\\d]{8,128}', |
| 165 | + }, |
| 166 | + }, |
| 167 | + shape: { |
| 168 | + username: { type: 'string' }, |
| 169 | + password: { type: 'string' }, |
| 170 | + }, |
| 171 | +}); |
| 172 | + |
| 173 | +/** |
| 174 | + * Generates a unique identifier for authentication form elements. |
| 175 | + * |
| 176 | + * Uses Web Crypto API's randomUUID() when available, falling back to a |
| 177 | + * timestamp-based random string for environments where crypto is unavailable. |
| 178 | + * |
| 179 | + * @returns A unique string identifier prefixed with 'error-fallback-form-' |
| 180 | + * |
| 181 | + * @example |
| 182 | + * ```typescript |
| 183 | + * const formId = getBaseAuthFormId(); |
| 184 | + * // Returns: "error-fallback-form-550e8400-e29b-41d4-a716-446655440000" |
| 185 | + * // or: "error-fallback-form-1703875200000-abc123def" |
| 186 | + * ``` |
| 187 | + */ |
| 188 | +const getBaseAuthFormId = () => { |
| 189 | + return ( |
| 190 | + 'error-fallback-form-' + |
| 191 | + (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`) |
| 192 | + ); // Fallback when Web Crypto is unavailable |
| 193 | +}; |
0 commit comments