|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { type KeyboardEvent, useEffect, useState } from 'react' |
| 4 | +import { useRouter } from 'next/navigation' |
| 5 | +import { Button } from '@/components/ui/button' |
| 6 | +import { Input } from '@/components/ui/input' |
| 7 | +import { Label } from '@/components/ui/label' |
| 8 | +import { quickValidateEmail } from '@/lib/email/validation' |
| 9 | +import { createLogger } from '@/lib/logs/console/logger' |
| 10 | +import { cn } from '@/lib/utils' |
| 11 | +import Nav from '@/app/(landing)/components/nav/nav' |
| 12 | +import { inter } from '@/app/fonts/inter' |
| 13 | +import { soehne } from '@/app/fonts/soehne/soehne' |
| 14 | + |
| 15 | +const logger = createLogger('SSOAuth') |
| 16 | + |
| 17 | +interface SSOAuthProps { |
| 18 | + identifier: string |
| 19 | + onAuthSuccess: () => void |
| 20 | + title?: string |
| 21 | + primaryColor?: string |
| 22 | +} |
| 23 | + |
| 24 | +const validateEmailField = (emailValue: string): string[] => { |
| 25 | + const errors: string[] = [] |
| 26 | + |
| 27 | + if (!emailValue || !emailValue.trim()) { |
| 28 | + errors.push('Email is required.') |
| 29 | + return errors |
| 30 | + } |
| 31 | + |
| 32 | + const validation = quickValidateEmail(emailValue.trim().toLowerCase()) |
| 33 | + if (!validation.isValid) { |
| 34 | + errors.push(validation.reason || 'Please enter a valid email address.') |
| 35 | + } |
| 36 | + |
| 37 | + return errors |
| 38 | +} |
| 39 | + |
| 40 | +export default function SSOAuth({ |
| 41 | + identifier, |
| 42 | + onAuthSuccess, |
| 43 | + title = 'chat', |
| 44 | + primaryColor = 'var(--brand-primary-hover-hex)', |
| 45 | +}: SSOAuthProps) { |
| 46 | + const router = useRouter() |
| 47 | + const [email, setEmail] = useState('') |
| 48 | + const [emailErrors, setEmailErrors] = useState<string[]>([]) |
| 49 | + const [showEmailValidationError, setShowEmailValidationError] = useState(false) |
| 50 | + const [buttonClass, setButtonClass] = useState('auth-button-gradient') |
| 51 | + const [isLoading, setIsLoading] = useState(false) |
| 52 | + |
| 53 | + useEffect(() => { |
| 54 | + const checkCustomBrand = () => { |
| 55 | + const computedStyle = getComputedStyle(document.documentElement) |
| 56 | + const brandAccent = computedStyle.getPropertyValue('--brand-accent-hex').trim() |
| 57 | + |
| 58 | + if (brandAccent && brandAccent !== '#6f3dfa') { |
| 59 | + setButtonClass('auth-button-custom') |
| 60 | + } else { |
| 61 | + setButtonClass('auth-button-gradient') |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + checkCustomBrand() |
| 66 | + |
| 67 | + window.addEventListener('resize', checkCustomBrand) |
| 68 | + const observer = new MutationObserver(checkCustomBrand) |
| 69 | + observer.observe(document.documentElement, { |
| 70 | + attributes: true, |
| 71 | + attributeFilter: ['style', 'class'], |
| 72 | + }) |
| 73 | + |
| 74 | + return () => { |
| 75 | + window.removeEventListener('resize', checkCustomBrand) |
| 76 | + observer.disconnect() |
| 77 | + } |
| 78 | + }, []) |
| 79 | + |
| 80 | + const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => { |
| 81 | + if (e.key === 'Enter') { |
| 82 | + e.preventDefault() |
| 83 | + handleAuthenticate() |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 88 | + const newEmail = e.target.value |
| 89 | + setEmail(newEmail) |
| 90 | + setShowEmailValidationError(false) |
| 91 | + setEmailErrors([]) |
| 92 | + } |
| 93 | + |
| 94 | + const handleAuthenticate = async () => { |
| 95 | + const emailValidationErrors = validateEmailField(email) |
| 96 | + setEmailErrors(emailValidationErrors) |
| 97 | + setShowEmailValidationError(emailValidationErrors.length > 0) |
| 98 | + |
| 99 | + if (emailValidationErrors.length > 0) { |
| 100 | + return |
| 101 | + } |
| 102 | + |
| 103 | + setIsLoading(true) |
| 104 | + |
| 105 | + try { |
| 106 | + const checkResponse = await fetch(`/api/chat/${identifier}`, { |
| 107 | + method: 'POST', |
| 108 | + credentials: 'same-origin', |
| 109 | + headers: { |
| 110 | + 'Content-Type': 'application/json', |
| 111 | + 'X-Requested-With': 'XMLHttpRequest', |
| 112 | + }, |
| 113 | + body: JSON.stringify({ email, checkSSOAccess: true }), |
| 114 | + }) |
| 115 | + |
| 116 | + if (!checkResponse.ok) { |
| 117 | + const errorData = await checkResponse.json() |
| 118 | + setEmailErrors([errorData.error || 'Email not authorized for this chat']) |
| 119 | + setShowEmailValidationError(true) |
| 120 | + setIsLoading(false) |
| 121 | + return |
| 122 | + } |
| 123 | + |
| 124 | + const callbackUrl = `/chat/${identifier}` |
| 125 | + const ssoUrl = `/sso?email=${encodeURIComponent(email)}&callbackUrl=${encodeURIComponent(callbackUrl)}` |
| 126 | + router.push(ssoUrl) |
| 127 | + } catch (error) { |
| 128 | + logger.error('SSO authentication error:', error) |
| 129 | + setEmailErrors(['An error occurred during authentication']) |
| 130 | + setShowEmailValidationError(true) |
| 131 | + setIsLoading(false) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + return ( |
| 136 | + <div className='bg-white'> |
| 137 | + <Nav variant='auth' /> |
| 138 | + <div className='flex min-h-[calc(100vh-120px)] items-center justify-center px-4'> |
| 139 | + <div className='w-full max-w-[410px]'> |
| 140 | + <div className='flex flex-col items-center justify-center'> |
| 141 | + {/* Header */} |
| 142 | + <div className='space-y-1 text-center'> |
| 143 | + <h1 |
| 144 | + className={`${soehne.className} font-medium text-[32px] text-black tracking-tight`} |
| 145 | + > |
| 146 | + SSO Authentication |
| 147 | + </h1> |
| 148 | + <p className={`${inter.className} font-[380] text-[16px] text-muted-foreground`}> |
| 149 | + This chat requires SSO authentication |
| 150 | + </p> |
| 151 | + </div> |
| 152 | + |
| 153 | + {/* Form */} |
| 154 | + <form |
| 155 | + onSubmit={(e) => { |
| 156 | + e.preventDefault() |
| 157 | + handleAuthenticate() |
| 158 | + }} |
| 159 | + className={`${inter.className} mt-8 w-full space-y-8`} |
| 160 | + > |
| 161 | + <div className='space-y-6'> |
| 162 | + <div className='space-y-2'> |
| 163 | + <div className='flex items-center justify-between'> |
| 164 | + <Label htmlFor='email'>Work Email</Label> |
| 165 | + </div> |
| 166 | + <Input |
| 167 | + id='email' |
| 168 | + name='email' |
| 169 | + required |
| 170 | + type='email' |
| 171 | + autoCapitalize='none' |
| 172 | + autoComplete='email' |
| 173 | + autoCorrect='off' |
| 174 | + placeholder='Enter your work email' |
| 175 | + value={email} |
| 176 | + onChange={handleEmailChange} |
| 177 | + onKeyDown={handleKeyDown} |
| 178 | + className={cn( |
| 179 | + 'rounded-[10px] shadow-sm transition-colors focus:border-gray-400 focus:ring-2 focus:ring-gray-100', |
| 180 | + showEmailValidationError && |
| 181 | + emailErrors.length > 0 && |
| 182 | + 'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500' |
| 183 | + )} |
| 184 | + autoFocus |
| 185 | + /> |
| 186 | + {showEmailValidationError && emailErrors.length > 0 && ( |
| 187 | + <div className='mt-1 space-y-1 text-red-400 text-xs'> |
| 188 | + {emailErrors.map((error, index) => ( |
| 189 | + <p key={index}>{error}</p> |
| 190 | + ))} |
| 191 | + </div> |
| 192 | + )} |
| 193 | + </div> |
| 194 | + </div> |
| 195 | + |
| 196 | + <Button |
| 197 | + type='submit' |
| 198 | + className={`${buttonClass} flex w-full items-center justify-center gap-2 rounded-[10px] border font-medium text-[15px] text-white transition-all duration-200`} |
| 199 | + disabled={isLoading} |
| 200 | + > |
| 201 | + {isLoading ? 'Redirecting to SSO...' : 'Continue with SSO'} |
| 202 | + </Button> |
| 203 | + </form> |
| 204 | + </div> |
| 205 | + </div> |
| 206 | + </div> |
| 207 | + </div> |
| 208 | + ) |
| 209 | +} |
0 commit comments