SignIn.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { useIntl } from "react-intl";
  2. import { ProForm, ProFormText } from "@ant-design/pro-components";
  3. import { message } from "antd";
  4. import { useNavigate } from "react-router-dom";
  5. import { useAppDispatch } from "../../../hooks";
  6. import { IUser, signIn, TO_HOME } from "../../../reducers/current-user";
  7. import { get, post } from "../../../request";
  8. interface IFormData {
  9. email: string;
  10. password: string;
  11. }
  12. interface ISignInResponse {
  13. ok: boolean;
  14. message: string;
  15. data: string;
  16. }
  17. interface IUserResponse {
  18. ok: boolean;
  19. message: string;
  20. data: IUser;
  21. }
  22. interface ISignInRequest {
  23. username: string;
  24. password: string;
  25. }
  26. const Widget = () => {
  27. const intl = useIntl();
  28. const dispatch = useAppDispatch();
  29. const navigate = useNavigate();
  30. return (
  31. <ProForm<IFormData>
  32. onFinish={async (values: IFormData) => {
  33. // TODO
  34. console.log(values);
  35. const user = {
  36. username: values.email,
  37. password: values.password,
  38. };
  39. const signin = await post<ISignInRequest, ISignInResponse>(
  40. "/v2/auth/signin",
  41. user
  42. );
  43. if (signin.ok) {
  44. console.log("token", signin.data);
  45. localStorage.setItem("token", signin.data);
  46. get<IUserResponse>("/v2/auth/current").then((json) => {
  47. if (json.ok) {
  48. dispatch(signIn([json.data, signin.data]));
  49. navigate(TO_HOME);
  50. } else {
  51. console.error(json.message);
  52. }
  53. });
  54. message.success(intl.formatMessage({ id: "flashes.success" }));
  55. } else {
  56. message.error(signin.message);
  57. }
  58. }}
  59. >
  60. <ProForm.Group>
  61. <ProFormText
  62. width="md"
  63. name="email"
  64. required
  65. label={intl.formatMessage({
  66. id: "forms.fields.email.label",
  67. })}
  68. rules={[{ required: true, max: 255, min: 6 }]}
  69. />
  70. </ProForm.Group>
  71. <ProForm.Group>
  72. <ProFormText
  73. width="md"
  74. name="password"
  75. required
  76. label={intl.formatMessage({
  77. id: "forms.fields.password.label",
  78. })}
  79. rules={[{ required: true, max: 32, min: 4 }]}
  80. />
  81. </ProForm.Group>
  82. </ProForm>
  83. );
  84. };
  85. export default Widget;