All files / src/pages TenantLoginPage.tsx

100% Statements 42/42
94.73% Branches 18/19
100% Functions 9/9
100% Lines 42/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                        1x 376x 376x 376x 376x 376x   376x 376x     376x   377x       376x 22x 22x 22x 21x         22x     376x 12x 12x   12x       6x 1x         1x 1x     5x 5x 5x 5x   5x 5x     5x 1x 1x       4x 1x 1x     3x     3x           376x   376x                                                                                                                                                           177x                                                     137x                                                                                                                                                            
/**
 * Tenant Login Page
 * A distinct login page for business subdomains with tenant branding
 */
 
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useLogin } from '../hooks/useAuth';
import { useNavigate, Link } from 'react-router-dom';
import OAuthButtons from '../components/OAuthButtons';
import LanguageSelector from '../components/LanguageSelector';
import { DevQuickLogin } from '../components/DevQuickLogin';
import { AlertCircle, Loader2, Mail, Lock, ArrowRight, Building2, Calendar, Users, Clock } from 'lucide-react';
import apiClient from '../api/client';
import { Business } from '../types';
 
interface TenantLoginPageProps {
  subdomain: string;
}
 
const TenantLoginPage: React.FC<TenantLoginPageProps> = ({ subdomain }) => {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [business, setBusiness] = useState<Business | null>(null);
 
  const navigate = useNavigate();
  const loginMutation = useLogin();
 
  // Format subdomain for display
  const displayName = subdomain
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
 
  // Fetch business info for branding
  useEffect(() => {
    const fetchBusiness = async () => {
      try {
        const response = await apiClient.get('/business/public-info/');
        setBusiness(response.data);
      } catch (err) {
        // Business info not available, use subdomain display name
      }
    };
    fetchBusiness();
  }, [subdomain]);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
 
    loginMutation.mutate(
      { email, password },
      {
        onSuccess: (data) => {
          if (data.mfa_required) {
            sessionStorage.setItem('mfa_challenge', JSON.stringify({
              user_id: data.user_id,
              mfa_methods: data.mfa_methods,
              phone_last_4: data.phone_last_4,
            }));
            navigate('/mfa-verify');
            return;
          }
 
          const user = data.user!;
          const currentHostname = window.location.hostname;
          const hostnameParts = currentHostname.split('.');
          const currentSubdomain = hostnameParts[0];
 
          const isBusinessUser = ['owner', 'manager', 'staff', 'resource'].includes(user.role);
          const isCustomer = user.role === 'customer';
 
          // Validate that users belong to this business
          if ((isBusinessUser || isCustomer) && user.business_subdomain !== currentSubdomain) {
            setError(t('auth.invalidCredentials'));
            return;
          }
 
          // Platform users cannot login on tenant subdomains
          if (['superuser', 'platform_manager', 'platform_support'].includes(user.role)) {
            setError(t('auth.invalidCredentials'));
            return;
          }
 
          navigate('/');
        },
        onError: (err: any) => {
          setError(err.response?.data?.error || t('auth.invalidCredentials'));
        },
      }
    );
  };
 
  const businessName = business?.name || displayName;
 
  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-indigo-900">
      {/* Background Pattern */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-0 right-0 w-[600px] h-[600px] bg-indigo-500/10 rounded-full blur-3xl translate-x-1/3 -translate-y-1/3" />
        <div className="absolute bottom-0 left-0 w-[500px] h-[500px] bg-purple-500/10 rounded-full blur-3xl -translate-x-1/3 translate-y-1/3" />
      </div>
 
      <div className="relative min-h-screen flex flex-col">
        {/* Header */}
        <header className="py-6 px-4 sm:px-6 lg:px-8">
          <div className="max-w-7xl mx-auto flex items-center justify-between">
            <div className="flex items-center gap-3">
              {business?.logo_url ? (
                <img src={business.logo_url} alt={businessName} className="w-10 h-10 rounded-lg object-contain" />
              ) : (
                <div className="w-10 h-10 bg-indigo-600 rounded-lg flex items-center justify-center">
                  <Building2 className="w-6 h-6 text-white" />
                </div>
              )}
              <span className="text-xl font-bold text-gray-900 dark:text-white">
                {businessName}
              </span>
            </div>
            <LanguageSelector />
          </div>
        </header>
 
        {/* Main Content */}
        <main className="flex-1 flex items-center justify-center px-4 py-12">
          <div className="w-full max-w-md">
            {/* Card */}
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-100 dark:border-gray-700 overflow-hidden">
              {/* Card Header */}
              <div className="bg-gradient-to-r from-indigo-600 to-purple-600 px-6 py-8 text-center">
                <div className="inline-flex items-center justify-center w-16 h-16 bg-white/20 backdrop-blur-sm rounded-full mb-4">
                  <Calendar className="w-8 h-8 text-white" />
                </div>
                <h1 className="text-2xl font-bold text-white mb-2">
                  {t('auth.tenantLogin.welcome', { business: businessName })}
                </h1>
                <p className="text-indigo-100">
                  {t('auth.tenantLogin.subtitle')}
                </p>
              </div>
 
              {/* Card Body */}
              <div className="p-6 sm:p-8">
                {error && (
                  <div className="mb-6 rounded-xl bg-red-50 dark:bg-red-900/20 p-4 border border-red-100 dark:border-red-800/50 animate-in fade-in slide-in-from-top-2">
                    <div className="flex gap-3">
                      <AlertCircle className="h-5 w-5 text-red-500 dark:text-red-400 flex-shrink-0 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-red-800 dark:text-red-200">{t('auth.authError')}</p>
                        <p className="text-sm text-red-700 dark:text-red-300 mt-1">{error}</p>
                      </div>
                    </div>
                  </div>
                )}
 
                <form onSubmit={handleSubmit} className="space-y-5">
                  <div>
                    <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {t('auth.email')}
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                        <Mail className="h-5 w-5 text-gray-400" />
                      </div>
                      <input
                        id="email"
                        name="email"
                        type="email"
                        autoComplete="email"
                        required
                        className="block w-full pl-12 pr-4 py-3 border border-gray-200 dark:border-gray-600 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-transparent focus:bg-white dark:focus:bg-gray-600 transition-all"
                        placeholder={t('auth.enterEmail')}
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                      />
                    </div>
                  </div>
 
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                        {t('auth.password')}
                      </label>
                      <Link to="/forgot-password" className="text-sm text-indigo-600 dark:text-indigo-400 hover:underline">
                        {t('auth.forgotPassword')}
                      </Link>
                    </div>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                        <Lock className="h-5 w-5 text-gray-400" />
                      </div>
                      <input
                        id="password"
                        name="password"
                        type="password"
                        autoComplete="current-password"
                        required
                        className="block w-full pl-12 pr-4 py-3 border border-gray-200 dark:border-gray-600 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-transparent focus:bg-white dark:focus:bg-gray-600 transition-all"
                        placeholder="••••••••"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                      />
                    </div>
                  </div>
 
                  <button
                    type="submit"
                    disabled={loginMutation.isPending}
                    className="w-full flex items-center justify-center gap-2 py-3 px-4 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-xl shadow-lg shadow-indigo-600/25 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-70 disabled:cursor-not-allowed transition-all transform active:scale-[0.98]"
                  >
                    {loginMutation.isPending ? (
                      <>
                        <Loader2 className="animate-spin h-5 w-5" />
                        {t('auth.signingIn')}
                      </>
                    ) : (
                      <>
                        {t('auth.signIn')}
                        <ArrowRight className="h-5 w-5" />
                      </>
                    )}
                  </button>
                </form>
 
                {/* OAuth */}
                <div className="mt-6">
                  <div className="relative">
                    <div className="absolute inset-0 flex items-center">
                      <div className="w-full border-t border-gray-200 dark:border-gray-600" />
                    </div>
                    <div className="relative flex justify-center text-sm">
                      <span className="px-4 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
                        {t('auth.orContinueWith')}
                      </span>
                    </div>
                  </div>
 
                  <div className="mt-6">
                    <OAuthButtons disabled={loginMutation.isPending} />
                  </div>
                </div>
 
                <DevQuickLogin embedded />
              </div>
            </div>
 
            {/* Login Type Indicators */}
            <div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500 dark:text-gray-400">
              <div className="flex items-center gap-2">
                <Users className="w-4 h-4" />
                <span>{t('auth.tenantLogin.staffAccess')}</span>
              </div>
              <div className="flex items-center gap-2">
                <Clock className="w-4 h-4" />
                <span>{t('auth.tenantLogin.customerBooking')}</span>
              </div>
            </div>
 
            {/* Powered By */}
            <p className="mt-8 text-center text-sm text-gray-500 dark:text-gray-400">
              {t('common.poweredBy')}{' '}
              <a
                href="https://smoothschedule.com"
                target="_blank"
                rel="noopener noreferrer"
                className="text-indigo-600 dark:text-indigo-400 hover:underline"
              >
                SmoothSchedule
              </a>
            </p>
          </div>
        </main>
      </div>
    </div>
  );
};
 
export default TenantLoginPage;