summaryrefslogtreecommitdiff
path: root/components/login/reset-password.tsx
blob: 3846de79c3745308ef1dc6ce39e2cdcaad220c1d (plain)
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
'use client';

import { useState, useEffect } from 'react';
import { useFormState } from 'react-dom';
import { useToast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Ship, Eye, EyeOff, CheckCircle, XCircle, AlertCircle, Shield } from 'lucide-react';
import Link from 'next/link';
import SuccessPage from './SuccessPage';
import { PasswordPolicy } from '@/lib/users/auth/passwordUtil';
import { PasswordValidationResult, resetPasswordAction, validatePasswordAction } from '@/lib/users/auth/partners-auth';
import { useTranslation } from '@/i18n/client';
import { useParams } from 'next/navigation';

interface PasswordRequirement {
  text: string;
  met: boolean;
  type: 'length' | 'uppercase' | 'lowercase' | 'number' | 'symbol' | 'pattern';
}

interface Props {
  token: string;
  userId: number;
  passwordPolicy: PasswordPolicy;
}

export default function ResetPasswordForm({ token, userId, passwordPolicy }: Props) {
  const params = useParams() || {};
  const lng = params.lng as string;
  
  const { toast } = useToast();
  const { t } = useTranslation(lng, 'login');
  
  // 상태 관리
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordValidation, setPasswordValidation] = useState<PasswordValidationResult | null>(null);
  const [isValidatingPassword, setIsValidatingPassword] = useState(false);
  
  // 서버 액션 상태
  const [resetState, resetAction] = useFormState(resetPasswordAction, {
    success: false,
    error: undefined,
    message: undefined,
  });

  // 패스워드 검증 (디바운싱 적용)
  useEffect(() => {
    const validatePassword = async () => {
      if (!newPassword) {
        setPasswordValidation(null);
        return;
      }

      setIsValidatingPassword(true);
      
      try {
        // 사용자 ID를 포함한 검증 (히스토리 체크 포함)
        const validation = await validatePasswordAction(newPassword, userId);
        setPasswordValidation(validation);
      } catch (error) {
        console.error('Password validation error:', error);
        setPasswordValidation(null);
      } finally {
        setIsValidatingPassword(false);
      }
    };

    // 디바운싱: 500ms 후에 검증 실행
    const timeoutId = setTimeout(validatePassword, 500);
    return () => clearTimeout(timeoutId);
  }, [newPassword, userId]);

  // 서버 액션 결과 처리
  useEffect(() => {
    if (resetState.error) {
      toast({
        title: t('error'),
        description: resetState.error,
        variant: 'destructive',
      });
    }
  }, [resetState, toast, t]);

  // 패스워드 요구사항 생성
  const getPasswordRequirements = (): PasswordRequirement[] => {
    if (!passwordValidation) return [];

    const { strength } = passwordValidation;
    const requirements: PasswordRequirement[] = [
      {
        text: `${passwordPolicy.minLength}${t('passwordRequirementLength')}`,
        met: strength.length >= passwordPolicy.minLength,
        type: 'length'
      }
    ];

    if (passwordPolicy.requireUppercase) {
      requirements.push({
        text: t('passwordRequirementUppercase'),
        met: strength.hasUppercase,
        type: 'uppercase'
      });
    }

    if (passwordPolicy.requireLowercase) {
      requirements.push({
        text: t('passwordRequirementLowercase'),
        met: strength.hasLowercase,
        type: 'lowercase'
      });
    }

    if (passwordPolicy.requireNumbers) {
      requirements.push({
        text: t('passwordRequirementNumbers'),
        met: strength.hasNumbers,
        type: 'number'
      });
    }

    if (passwordPolicy.requireSymbols) {
      requirements.push({
        text: t('passwordRequirementSymbols'),
        met: strength.hasSymbols,
        type: 'symbol'
      });
    }

    return requirements;
  };

  // 패스워드 강도 색상
  const getStrengthColor = (score: number) => {
    switch (score) {
      case 1: return 'text-red-600';
      case 2: return 'text-orange-600';
      case 3: return 'text-yellow-600';
      case 4: return 'text-blue-600';
      case 5: return 'text-green-600';
      default: return 'text-gray-600';
    }
  };

  const getStrengthText = (score: number) => {
    switch (score) {
      case 1: return t('passwordStrengthVeryWeak');
      case 2: return t('passwordStrengthWeak');
      case 3: return t('passwordStrengthMedium');
      case 4: return t('passwordStrengthStrong');
      case 5: return t('passwordStrengthVeryStrong');
      default: return '';
    }
  };

  const passwordRequirements = getPasswordRequirements();
  const allRequirementsMet = passwordValidation?.policyValid && passwordValidation?.historyValid !== false;
  const passwordsMatch = newPassword === confirmPassword && confirmPassword.length > 0;
  const canSubmit = allRequirementsMet && passwordsMatch && !isValidatingPassword;

  // 성공 화면
  if (resetState.success) {
    return <SuccessPage message={resetState.message} />;
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader className="text-center">
        <div className="mx-auto flex items-center justify-center space-x-2 mb-4">
          <Ship className="w-6 h-6 text-blue-600" />
          <span className="text-xl font-bold">eVCP</span>
        </div>
        <CardTitle className="text-2xl">{t('resetPasswordTitle')}</CardTitle>
        <CardDescription>
          {t('resetPasswordDescription')}
        </CardDescription>
      </CardHeader>
      
      <CardContent>
        <form action={resetAction} className="space-y-6">
          <input type="hidden" name="token" value={token} />
          
          {/* 새 비밀번호 */}
          <div className="space-y-2">
            <label htmlFor="newPassword" className="text-sm font-medium text-gray-700">
              {t('newPassword')}
            </label>
            <div className="relative">
              <Input
                id="newPassword"
                name="newPassword"
                type={showPassword ? "text" : "password"}
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder={t('newPasswordPlaceholder')}
                required
              />
              <button
                type="button"
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            
            {/* 패스워드 강도 표시 */}
            {passwordValidation && (
              <div className="mt-2 space-y-2">
                <div className="flex items-center space-x-2">
                  <Shield className="h-4 w-4 text-gray-500" />
                  <span className="text-xs text-gray-600">{t('passwordStrength')}:</span>
                  <span className={`text-xs font-medium ${getStrengthColor(passwordValidation.strength.score)}`}>
                    {getStrengthText(passwordValidation.strength.score)}
                  </span>
                  {isValidatingPassword && (
                    <div className="ml-2 animate-spin rounded-full h-3 w-3 border-b border-blue-600"></div>
                  )}
                </div>
                
                {/* 강도 진행바 */}
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className={`h-2 rounded-full transition-all duration-300 ${
                      passwordValidation.strength.score === 1 ? 'bg-red-500' :
                      passwordValidation.strength.score === 2 ? 'bg-orange-500' :
                      passwordValidation.strength.score === 3 ? 'bg-yellow-500' :
                      passwordValidation.strength.score === 4 ? 'bg-blue-500' :
                      'bg-green-500'
                    }`}
                    style={{ width: `${(passwordValidation.strength.score / 5) * 100}%` }}
                  />
                </div>
              </div>
            )}
            
            {/* 패스워드 요구사항 */}
            {passwordRequirements.length > 0 && (
              <div className="mt-2 space-y-1">
                {passwordRequirements.map((req, index) => (
                  <div key={index} className="flex items-center space-x-2 text-xs">
                    {req.met ? (
                      <CheckCircle className="h-3 w-3 text-green-500" />
                    ) : (
                      <XCircle className="h-3 w-3 text-red-500" />
                    )}
                    <span className={req.met ? 'text-green-700' : 'text-red-700'}>
                      {req.text}
                    </span>
                  </div>
                ))}
              </div>
            )}
            
            {/* 히스토리 검증 결과 */}
            {passwordValidation?.historyValid === false && (
              <div className="mt-2">
                <div className="flex items-center space-x-2 text-xs">
                  <XCircle className="h-3 w-3 text-red-500" />
                  <span className="text-red-700">
                    {t('passwordHistoryError', { count: passwordPolicy.historyCount })}
                  </span>
                </div>
              </div>
            )}
            
            {/* 추가 피드백 */}
            {passwordValidation?.strength.feedback && passwordValidation.strength.feedback.length > 0 && (
              <div className="mt-2 space-y-1">
                {passwordValidation.strength.feedback.map((feedback, index) => (
                  <div key={index} className="flex items-center space-x-2 text-xs">
                    <AlertCircle className="h-3 w-3 text-orange-500" />
                    <span className="text-orange-700">{feedback}</span>
                  </div>
                ))}
              </div>
            )}
            
            {/* 정책 오류 */}
            {passwordValidation && !passwordValidation.policyValid && passwordValidation.policyErrors.length > 0 && (
              <div className="mt-2 space-y-1">
                {passwordValidation.policyErrors.map((error, index) => (
                  <div key={index} className="flex items-center space-x-2 text-xs">
                    <XCircle className="h-3 w-3 text-red-500" />
                    <span className="text-red-700">{error}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 비밀번호 확인 */}
          <div className="space-y-2">
            <label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700">
              {t('confirmPassword')}
            </label>
            <div className="relative">
              <Input
                id="confirmPassword"
                name="confirmPassword"
                type={showConfirmPassword ? "text" : "password"}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder={t('confirmPasswordPlaceholder')}
                required
              />
              <button
                type="button"
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              >
                {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            
            {/* 비밀번호 일치 확인 */}
            {confirmPassword && (
              <div className="flex items-center space-x-2 text-xs">
                {passwordsMatch ? (
                  <>
                    <CheckCircle className="h-3 w-3 text-green-500" />
                    <span className="text-green-700">{t('passwordsMatch')}</span>
                  </>
                ) : (
                  <>
                    <XCircle className="h-3 w-3 text-red-500" />
                    <span className="text-red-700">{t('passwordsNotMatch')}</span>
                  </>
                )}
              </div>
            )}
          </div>

          <Button 
            type="submit" 
            className="w-full"
            disabled={!canSubmit}
          >
            {isValidatingPassword ? t('validating') : t('changePassword')}
          </Button>
        </form>

        <div className="mt-6 text-center">
          <Link href="/partners" className="text-sm text-blue-600 hover:text-blue-500">
            {t('backToLogin')}
          </Link>
        </div>
      </CardContent>
    </Card>
  );
}