Blame view

美国版/Food Labeling Management Platform/src/components/auth/LoginView.tsx 9.28 KB
699ea6e8   杨鑫   完善打印逻辑
1
2
3
4
5
6
  import React from "react";
  import { toast } from "sonner";
  
  import { Button } from "../ui/button";
  import { Input } from "../ui/input";
  import { Label } from "../ui/label";
540ac0e3   杨鑫   前端修改bug
7
  import { PasswordInput } from "../ui/password-input";
699ea6e8   杨鑫   完善打印逻辑
8
  import { login } from "../../services/accountService";
ef6b3255   杨鑫   修改BUG
9
  import { confirmPasswordReset, sendPasswordResetCode } from "../../services/passwordResetService";
699ea6e8   杨鑫   完善打印逻辑
10
11
  import { useAuth } from "./AuthProvider";
  
ef6b3255   杨鑫   修改BUG
12
13
14
15
16
17
18
  const brandLogo = new URL("../../assets/773f0c39e1986271e9144596caac519f934a6ae6.png", import.meta.url).href;
  
  const CODE_COOLDOWN_SEC = 60;
  const MIN_PASSWORD_LEN = 6;
  
  type Mode = "signin" | "forgot";
  
699ea6e8   杨鑫   完善打印逻辑
19
20
  export function LoginView() {
    const auth = useAuth();
ef6b3255   杨鑫   修改BUG
21
22
    const [mode, setMode] = React.useState<Mode>("signin");
  
699ea6e8   杨鑫   完善打印逻辑
23
24
25
26
    const [email, setEmail] = React.useState("");
    const [password, setPassword] = React.useState("");
    const [submitting, setSubmitting] = React.useState(false);
  
ef6b3255   杨鑫   修改BUG
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    const [fpEmail, setFpEmail] = React.useState("");
    const [fpCode, setFpCode] = React.useState("");
    const [fpNew, setFpNew] = React.useState("");
    const [fpConfirm, setFpConfirm] = React.useState("");
    const [sendingCode, setSendingCode] = React.useState(false);
    const [resetting, setResetting] = React.useState(false);
    const [cooldown, setCooldown] = React.useState(0);
  
    React.useEffect(() => {
      if (cooldown <= 0) return;
      const id = window.setTimeout(() => setCooldown((c) => Math.max(0, c - 1)), 1000);
      return () => window.clearTimeout(id);
    }, [cooldown]);
  
699ea6e8   杨鑫   完善打印逻辑
41
42
43
44
45
46
47
    const canSubmit = Boolean(email.trim() && password.trim() && !submitting);
  
    const submit = async () => {
      if (!canSubmit) return;
      const emailText = email.trim();
      setSubmitting(true);
      try {
699ea6e8   杨鑫   完善打印逻辑
48
49
50
        await login({ userName: emailText, password: password.trim() });
        await auth.refresh();
        toast.success("Signed in");
ef6b3255   杨鑫   修改BUG
51
      } catch (e: unknown) {
699ea6e8   杨鑫   完善打印逻辑
52
        toast.error("Sign-in failed", {
ef6b3255   杨鑫   修改BUG
53
          description: e instanceof Error ? e.message : "Please check your email/password and try again.",
699ea6e8   杨鑫   完善打印逻辑
54
55
56
57
58
59
        });
      } finally {
        setSubmitting(false);
      }
    };
  
ef6b3255   杨鑫   修改BUG
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
    const goForgot = () => {
      setFpEmail(email.trim());
      setFpCode("");
      setFpNew("");
      setFpConfirm("");
      setCooldown(0);
      setMode("forgot");
    };
  
    const goSignIn = () => {
      setMode("signin");
      setFpCode("");
      setFpNew("");
      setFpConfirm("");
      setCooldown(0);
    };
  
    const sendCode = async () => {
      const em = fpEmail.trim();
      if (!em) {
        toast.error("Email required", { description: "Enter the email address for your account." });
        return;
      }
      if (cooldown > 0 || sendingCode) return;
      setSendingCode(true);
      try {
        await sendPasswordResetCode(em);
        setCooldown(CODE_COOLDOWN_SEC);
        toast.success("Verification code sent", {
          description: "Check your inbox for the code.",
        });
      } catch (e: unknown) {
        toast.error("Could not send code", {
          description: e instanceof Error ? e.message : "Please try again.",
        });
      } finally {
        setSendingCode(false);
      }
    };
  
    const submitReset = async () => {
      const em = fpEmail.trim();
      const code = fpCode.trim();
      const np = fpNew;
      const cf = fpConfirm;
      if (!em || !code) {
        toast.error("Missing fields", { description: "Email and verification code are required." });
        return;
      }
      if (np.length < MIN_PASSWORD_LEN) {
        toast.error("Password too short", {
          description: `Use at least ${MIN_PASSWORD_LEN} characters.`,
        });
        return;
      }
      if (np !== cf) {
        toast.error("Passwords do not match", { description: "Re-enter the new password in both fields." });
        return;
      }
      setResetting(true);
      try {
        await confirmPasswordReset({ email: em, code, newPassword: np });
        toast.success("Password updated", { description: "You can sign in with your new password." });
        setEmail(em);
        setPassword("");
        goSignIn();
      } catch (e: unknown) {
        toast.error("Reset failed", {
          description: e instanceof Error ? e.message : "Please try again.",
        });
      } finally {
        setResetting(false);
      }
    };
  
    const title = mode === "signin" ? "Platform Sign In" : "Reset password";
  
699ea6e8   杨鑫   完善打印逻辑
137
138
    return (
      <div className="w-screen h-screen grid items-center justify-center bg-[#f6f7fb] p-4">
ef6b3255   杨鑫   修改BUG
139
140
141
142
        <div
          className="bg-white border border-gray-200 rounded-2xl shadow-sm p-8"
          style={{ width: "25vw", maxWidth: "100%" }}
        >
699ea6e8   杨鑫   完善打印逻辑
143
          <div className="text-center">
ef6b3255   杨鑫   修改BUG
144
145
146
147
148
149
150
            <img
              src={brandLogo}
              alt="MedVantage"
              className="mx-auto block h-16 w-auto max-w-full object-contain object-center"
              decoding="async"
            />
            <div className="mt-4 text-xl font-semibold text-gray-900">{title}</div>
699ea6e8   杨鑫   完善打印逻辑
151
152
          </div>
  
ef6b3255   杨鑫   修改BUG
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
          {mode === "signin" ? (
            <div className="mt-6 space-y-4">
              <div className="space-y-2">
                <Label>Email</Label>
                <Input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="Enter your email"
                  autoComplete="username"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") submit();
                  }}
                />
              </div>
              <div className="space-y-2">
                <Label>Password</Label>
540ac0e3   杨鑫   前端修改bug
170
                <PasswordInput
ef6b3255   杨鑫   修改BUG
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter your password"
                  autoComplete="current-password"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") submit();
                  }}
                />
              </div>
  
              <div className="flex justify-end">
                <button
                  type="button"
                  className="text-sm font-medium text-blue-600 hover:text-blue-800 hover:underline"
                  onClick={goForgot}
                >
                  Forgot password?
                </button>
              </div>
  
              <Button className="w-full bg-blue-600 text-white hover:bg-blue-700" disabled={!canSubmit} onClick={submit}>
                {submitting ? "Signing in..." : "Sign In"}
              </Button>
699ea6e8   杨鑫   完善打印逻辑
194
            </div>
ef6b3255   杨鑫   修改BUG
195
196
197
198
199
200
201
202
203
204
205
206
          ) : (
            <div className="mt-6 space-y-4">
              <div className="space-y-2">
                <Label>Email</Label>
                <Input
                  type="email"
                  value={fpEmail}
                  onChange={(e) => setFpEmail(e.target.value)}
                  placeholder="Enter your email"
                  autoComplete="email"
                />
              </div>
699ea6e8   杨鑫   完善打印逻辑
207
  
ef6b3255   杨鑫   修改BUG
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
              <div className="space-y-2">
                <Label>Verification code</Label>
                <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                  <Input
                    className="min-w-0 sm:flex-1"
                    type="text"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    value={fpCode}
                    onChange={(e) => setFpCode(e.target.value)}
                    placeholder="Enter the code from email"
                    onKeyDown={(e) => {
                      if (e.key === "Enter") submitReset();
                    }}
                  />
                  <Button
                    type="button"
                    variant="outline"
                    className="h-9 w-full shrink-0 border-gray-300 sm:w-auto"
                    disabled={sendingCode || cooldown > 0 || !fpEmail.trim()}
                    onClick={() => void sendCode()}
                  >
                    {sendingCode ? "Sending…" : cooldown > 0 ? `Resend (${cooldown}s)` : "Send code"}
                  </Button>
                </div>
              </div>
  
              <div className="space-y-2">
                <Label>New password</Label>
540ac0e3   杨鑫   前端修改bug
237
                <PasswordInput
ef6b3255   杨鑫   修改BUG
238
239
240
241
242
243
244
245
                  value={fpNew}
                  onChange={(e) => setFpNew(e.target.value)}
                  placeholder={`At least ${MIN_PASSWORD_LEN} characters`}
                  autoComplete="new-password"
                />
              </div>
              <div className="space-y-2">
                <Label>Confirm new password</Label>
540ac0e3   杨鑫   前端修改bug
246
                <PasswordInput
ef6b3255   杨鑫   修改BUG
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
                  value={fpConfirm}
                  onChange={(e) => setFpConfirm(e.target.value)}
                  placeholder="Re-enter new password"
                  autoComplete="new-password"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") submitReset();
                  }}
                />
              </div>
  
              <Button
                className="w-full bg-blue-600 text-white hover:bg-blue-700"
                disabled={
                  resetting ||
                  !fpEmail.trim() ||
                  !fpCode.trim() ||
                  !fpNew ||
                  !fpConfirm ||
                  fpNew.length < MIN_PASSWORD_LEN
                }
                onClick={() => void submitReset()}
              >
                {resetting ? "Updating…" : "Update password"}
              </Button>
  
              <div className="text-center">
                <button
                  type="button"
                  className="text-sm font-medium text-gray-600 hover:text-gray-900 hover:underline"
                  onClick={goSignIn}
                >
                  Back to sign in
                </button>
              </div>
            </div>
          )}
699ea6e8   杨鑫   完善打印逻辑
283
284
285
286
        </div>
      </div>
    );
  }