File size: 18,543 Bytes
67b1bef 9bb4b11 67b1bef c29f769 67b1bef c29f769 67b1bef c29f769 67b1bef 2ecd1ea 67b1bef 2ecd1ea 67b1bef c29f769 2ecd1ea c29f769 2ecd1ea c29f769 2ecd1ea c29f769 2ecd1ea c29f769 2ecd1ea c29f769 2ecd1ea 9bb4b11 c29f769 2ecd1ea 9bb4b11 2ecd1ea 9bb4b11 2ecd1ea 9bb4b11 2ecd1ea 9bb4b11 67b1bef c29f769 2ecd1ea 67b1bef 2ecd1ea 67b1bef 9bb4b11 67b1bef c29f769 67b1bef 9bb4b11 67b1bef |
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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { clearError } from '../store/reducers/authSlice';
// Import the Supabase client
import { supabase } from '../services/supabaseClient';
const ResetPassword = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { loading, error } = useSelector(state => state.auth);
const [formData, setFormData] = useState({
token: '', // This is likely unused in the v2 flow, but kept for structure
password: '',
confirmPassword: ''
});
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [passwordStrength, setPasswordStrength] = useState(0);
const [isFocused, setIsFocused] = useState({
password: false,
confirmPassword: false
});
const [authState, setAuthState] = useState({ event: null, session: null });
// --- Listen for auth state changes specifically on this page ---
// This helps confirm if PASSWORD_RECOVERY was detected
useEffect(() => {
console.log("ResetPassword component mounted. Setting up auth listener.");
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
console.log('Auth state changed within ResetPassword component:', event, session ? `User: ${session.user?.id || 'N/A'}` : 'No session');
setAuthState({ event, session });
if (event === 'PASSWORD_RECOVERY') {
console.log('*** PASSWORD_RECOVERY event confirmed in ResetPassword component. ***');
// Optional: You could set some state here to indicate the recovery flow is active
}
});
// Cleanup listener on unmount
return () => {
console.log("ResetPassword component unmounting. Removing auth listener.");
authListener?.subscription.unsubscribe();
};
}, []);
// Get token from URL params (old v1 flow, kept for reference but likely not used)
useEffect(() => {
const token = searchParams.get('token');
if (token) {
console.warn("Token found in search params (v1 flow?). This might be unexpected in v2 flow:", token);
setFormData(prev => ({ ...prev, token }));
}
}, [searchParams]);
const calculatePasswordStrength = (password) => {
let strength = 0;
// Length check
if (password.length >= 8) strength += 1;
if (password.length >= 12) strength += 1;
// Character variety checks
if (/[a-z]/.test(password)) strength += 1;
if (/[A-Z]/.test(password)) strength += 1;
if (/[0-9]/.test(password)) strength += 1;
if (/[^A-Za-z0-9]/.test(password)) strength += 1;
setPasswordStrength(Math.min(strength, 6));
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
// Calculate password strength
if (name === 'password') {
calculatePasswordStrength(value);
}
};
const handleFocus = (field) => {
setIsFocused({
...isFocused,
[field]: true
});
};
const handleBlur = (field) => {
setIsFocused({
...isFocused,
[field]: false
});
};
const togglePasswordVisibility = () => {
setShowPassword(!showPassword);
};
const toggleConfirmPasswordVisibility = () => {
setShowConfirmPassword(!showConfirmPassword);
};
const handleSubmit = async (e) => {
e.preventDefault();
// Basic validation
if (formData.password !== formData.confirmPassword) {
alert('Passwords do not match');
return;
}
if (formData.password.length < 8) {
alert('Password must be at least 8 characters long');
return;
}
try {
console.log("Attempting to get current session before password update...");
// --- Check for existing session (recovery session) ---
// It's crucial to verify the session was established by the Supabase client
// when it processed the URL fragments on app load.
const { data: { session: currentSession }, error: sessionError } = await supabase.auth.getSession();
console.log("Current session check result:", currentSession ? `Session for user: ${currentSession.user?.id || 'N/A'}` : 'No session', sessionError);
if (sessionError) {
console.error('Error getting current session:', sessionError);
alert('Failed to get session. Please try resetting your password again.');
return;
}
if (!currentSession || !currentSession.user) {
// This is the likely cause of AuthSessionMissingError
console.warn('No active session found in handleSubmit. The URL might not have been processed correctly or the session expired.');
console.log("Auth state at time of submission:", authState);
alert('Password reset link may be invalid or expired. Please request a new one.');
// Optionally, redirect to /forgot-password
// navigate('/forgot-password');
return;
}
console.log('Resetting password with Supabase client for user:', currentSession.user?.email);
const { data, error } = await supabase.auth.updateUser({
password: formData.password
});
console.log("supabase.auth.updateUser result:", data, error);
if (error) {
console.error('Supabase password reset error:', error);
let message = 'Failed to reset password.';
if (error.message.toLowerCase().includes('password')) {
message = 'Password does not meet requirements. Please use at least 8 characters.';
} else if (error.message.toLowerCase().includes('session') || error.message.includes("Auth session missing")) {
message = 'Password reset session expired. Please request a new reset link.';
} else {
message = error.message;
}
alert(message);
return;
}
console.log('Password updated successfully:', data);
alert('Password reset successfully! You can now log in with your new password.');
// After successful reset, sign the user out of the temporary recovery session.
await supabase.auth.signOut();
navigate('/login');
} catch (err) {
console.error('Unexpected error during password reset:', err);
alert('An unexpected error occurred. Please try again.');
}
};
const handleBackToLogin = () => {
dispatch(clearError());
navigate('/login');
};
return (
<div className="min-h-screen bg-gradient-to-br from-primary-50 via-white to-accent-50 flex items-center justify-center p-3 sm:p-4 animate-fade-in">
<div className="w-full max-w-sm sm:max-w-md">
{/* Logo and Brand */}
<div className="text-center mb-6 sm:mb-8 animate-slide-up">
<div className="inline-flex items-center justify-center w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-primary-600 to-primary-800 rounded-2xl shadow-lg mb-3 sm:mb-4">
<span className="text-xl sm:text-2xl font-bold text-white">Lin</span>
</div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-1 sm:mb-2">Reset Password</h1>
<p className="text-sm sm:text-base text-gray-600">Enter your new password below</p>
</div>
{/* Auth Card */}
<div className="bg-white rounded-2xl shadow-xl p-4 sm:p-8 space-y-4 sm:space-y-6 animate-slide-up animate-delay-100">
{/* --- Debug Info Display (Remove in production) --- */}
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-2 text-xs">
<strong>Debug Info:</strong>
<p>Auth Event: {authState.event || 'None'}</p>
<p>Auth Session User ID: {authState.session?.user?.id || 'None'}</p>
</div>
{/* --- End Debug Info --- */}
{/* Error Message */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-3 sm:p-4 animate-slide-up animate-delay-200">
<div className="flex items-start space-x-2">
<svg className="w-4 h-4 sm:w-5 sm:h-5 text-red-500 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
<span className="text-red-700 text-xs sm:text-sm font-medium">{error}</span>
</div>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
{/* Password Field */}
<div className="space-y-2">
<label htmlFor="password" className="block text-xs sm:text-sm font-semibold text-gray-700">
New Password
</label>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
id="password"
name="password"
value={formData.password}
onChange={handleChange}
onFocus={() => handleFocus('password')}
onBlur={() => handleBlur('password')}
className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-xl border-2 transition-all duration-200 ${
isFocused.password
? 'border-primary-500 shadow-md'
: 'border-gray-200 hover:border-gray-300'
} ${formData.password ? 'text-gray-900' : 'text-gray-500'} focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 touch-manipulation`}
placeholder="Create a new password"
required
aria-required="true"
aria-label="New password"
/>
<button
type="button"
onClick={togglePasswordVisibility}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600 transition-colors touch-manipulation"
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
<path fillRule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clipRule="evenodd" />
</svg>
) : (
<svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.512 1.074l-1.78-1.781zm4.261 4.26l1.514 1.515a2.003 2.003 0 012.45 2.45l1.514 1.514a4 4 0 00-5.478-5.478z" clipRule="evenodd" />
<path d="M12.454 16.697L9.75 13.992a4 4 0 01-3.742-3.741L2.335 6.578A9.98 9.98 0 00.458 10c1.274 4.057 5.065 7 9.542 7 .847 0 1.669-.105 2.454-.303z" />
</svg>
)}
</button>
</div>
{/* Password Strength Indicator */}
{formData.password && (
<div className="space-y-1">
<div className="flex justify-between text-xs">
<span className="text-gray-600">Password strength</span>
<span className={`font-medium ${
passwordStrength <= 2 ? 'text-red-600' :
passwordStrength <= 4 ? 'text-yellow-600' :
'text-green-600'
}`}>
{passwordStrength <= 2 ? 'Weak' :
passwordStrength <= 4 ? 'Fair' :
passwordStrength === 5 ? 'Good' :
'Strong'}
</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-1.5 sm:h-2">
<div
className={`h-1.5 sm:h-2 rounded-full transition-all duration-300 ${
passwordStrength <= 2 ? 'bg-red-500 w-1/3' :
passwordStrength <= 4 ? 'bg-yellow-500 w-2/3' :
passwordStrength === 5 ? 'bg-green-500 w-4/5' :
'bg-green-600 w-full'
}`}
></div>
</div>
<div className="text-xs text-gray-500">
Use 8+ characters with uppercase, lowercase, numbers, and symbols
</div>
</div>
)}
</div>
{/* Confirm Password Field */}
<div className="space-y-2">
<label htmlFor="confirmPassword" className="block text-xs sm:text-sm font-semibold text-gray-700">
Confirm New Password
</label>
<div className="relative">
<input
type={showConfirmPassword ? "text" : "password"}
id="confirmPassword"
name="confirmPassword"
value={formData.confirmPassword}
onChange={handleChange}
onFocus={() => handleFocus('confirmPassword')}
onBlur={() => handleBlur('confirmPassword')}
className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-xl border-2 transition-all duration-200 ${
isFocused.confirmPassword
? 'border-primary-500 shadow-md'
: 'border-gray-200 hover:border-gray-300'
} ${formData.confirmPassword ? 'text-gray-900' : 'text-gray-500'} focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 touch-manipulation`}
placeholder="Confirm your new password"
required
aria-required="true"
aria-label="Confirm new password"
/>
<button
type="button"
onClick={toggleConfirmPasswordVisibility}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600 transition-colors touch-manipulation"
aria-label={showConfirmPassword ? "Hide confirm password" : "Show confirm password"}
>
{showConfirmPassword ? (
<svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
<path fillRule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clipRule="evenodd" />
</svg>
) : (
<svg className="w-4 h-4 sm:w-5 sm:h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.512 1.074l-1.78-1.781zm4.261 4.26l1.514 1.515a2.003 2.003 0 012.45 2.45l1.514 1.514a4 4 0 00-5.478-5.478z" clipRule="evenodd" />
<path d="M12.454 16.697L9.75 13.992a4 4 0 01-3.742-3.741L2.335 6.578A9.98 9.98 0 00.458 10c1.274 4.057 5.065 7 9.542 7 .847 0 1.669-.105 2.454-.303z" />
</svg>
)}
</button>
</div>
{formData.confirmPassword && formData.password !== formData.confirmPassword && (
<p className="text-red-600 text-xs">Passwords do not match</p>
)}
</div>
{/* Submit Button */}
<button
type="submit"
disabled={loading === 'pending'}
className="w-full bg-gradient-to-r from-primary-600 to-primary-800 text-white font-semibold py-2.5 sm:py-3 px-4 rounded-xl hover:from-primary-700 hover:to-primary-900 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none touch-manipulation"
aria-busy={loading === 'pending'}
>
{loading === 'pending' ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-2 sm:mr-3 h-4 w-4 sm:h-5 sm:w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span className="text-xs sm:text-sm">Resetting password...</span>
</div>
) : (
<span className="text-xs sm:text-sm">Reset Password</span>
)}
</button>
</form>
{/* Back to Login Link */}
<div className="text-center">
<button
type="button"
onClick={handleBackToLogin}
className="font-semibold text-primary-600 hover:text-primary-500 transition-colors focus:outline-none focus:underline text-xs sm:text-sm"
aria-label="Back to login"
>
Back to Sign In
</button>
</div>
</div>
{/* Footer */}
<div className="text-center mt-6 sm:mt-8 text-xs text-gray-500">
<p>© 2024 Lin. All rights reserved.</p>
</div>
</div>
</div>
);
};
export default ResetPassword; |