Skip to content

Commit

Permalink
feat:login
Browse files Browse the repository at this point in the history
  • Loading branch information
laoriy committed Apr 29, 2024
1 parent f087eb3 commit eceda78
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 15 deletions.
37 changes: 28 additions & 9 deletions 5.react/8.ecommerce/ecommerce-front/src/components/core/Nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useState } from "react";
import { Menu, MenuProps } from "antd";
import { useNavigate } from "react-router-dom";
import useRoute from "../../hooks/useRoute";
import { isAuth } from "../../helpers/auth";
import { Jwt } from "../../types/auth";

const items: MenuProps["items"] = [
{
Expand All @@ -12,20 +14,37 @@ const items: MenuProps["items"] = [
label: "购物车",
key: "/shop",
},
{
label: "登录",
key: "/signin",
},
{
label: "注册",
key: "/signup",
},
];

function Nav() {
const {
location: { pathname },
} = useRoute();
const auth = isAuth();
const menus = [...items!];

if (auth) {
const {
user: { role },
} = auth as Jwt;
menus.push(
role === 0
? { label: "dashboard", key: "/user/dashboard" }
: { label: "dashboard", key: "/user/dashboard" }
);
} else {
menus.push(
{
label: "登录",
key: "/signin",
},
{
label: "注册",
key: "/signup",
}
);
}

const navigate = useNavigate();
const [current, setCurrent] = useState(pathname);
const onClick: MenuProps["onClick"] = (e) => {
Expand All @@ -37,7 +56,7 @@ function Nav() {
mode="horizontal"
onClick={onClick}
selectedKeys={[current]}
items={items}
items={menus}
></Menu>
);
}
Expand Down
45 changes: 41 additions & 4 deletions 5.react/8.ecommerce/ecommerce-front/src/components/core/SignIn.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,46 @@
import React from "react";
import React, { useEffect } from "react";
import Layout from "./Layout";
import { Button, Form, Input } from "antd";
import { Button, Form, Input, Result } from "antd";
import { SigninPayload, useSigninStore } from "../../store/auth";
import { isAuth } from "../../helpers/auth";
import { Jwt } from "../../types/auth";
import { redirect, useNavigate } from "react-router-dom";

const SignIn = () => {
const onFinish = () => {
const signinState = useSigninStore();
const navigate = useNavigate();
const auth = isAuth();
// 2. 登录失败 显示错误信息
const showError = () => {
if (signinState.loaded && !signinState.success) {
return (
<Result
status="warning"
title="登录失败"
subTitle={signinState.message}
/>
);
}
};

useEffect(() => {
// 3. 登录成功 根据角色跳转到对应的管理页面
if (auth) {
const {
user: { role },
} = auth as Jwt;
if (role === 0) {
// 注册用户
navigate("/user/dashboard");
} else {
// 管理员
navigate("/admin/dashboard");
}
}
});
const onFinish = async (value: SigninPayload) => {
// 发送登录请求
await signinState.signin(value);
};
const signinForm = () => (
<Form onFinish={onFinish}>
Expand All @@ -22,8 +58,9 @@ const SignIn = () => {
</Form>
);

return (
return auth ? null : (
<Layout title="登录" subTitle="嘿, 小伙伴, 立即登录到拉钩电商系统吧">
{showError()}
{signinForm()}
</Layout>
);
Expand Down
7 changes: 7 additions & 0 deletions 5.react/8.ecommerce/ecommerce-front/src/helpers/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Jwt } from "../types/auth";

export function isAuth(): boolean | Jwt {
const jwt = localStorage.getItem("jwt");
if (jwt) return JSON.parse(jwt);
return false;
}
8 changes: 6 additions & 2 deletions 5.react/8.ecommerce/ecommerce-front/src/store/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface SignupPayload {
}

interface SignupState extends AuthState {
signup: (payload: SigninPayload) => Promise<boolean>;
signup: (payload: SignupPayload) => Promise<boolean>;
signupSuccess: () => void;
signupFail: (message: string) => void;
resetSignup: () => void;
Expand All @@ -41,7 +41,7 @@ export interface SigninPayload {
}

interface SigninState extends AuthState {
signin: (payload: SigninPayload) => void;
signin: (payload: SigninPayload) => Promise<boolean>;
signinSuccess: () => void;
signinFail: (message: string) => void;
}
Expand Down Expand Up @@ -76,16 +76,20 @@ const useSigninStore = create<SigninState>((set, get) => ({
signin: async (payload) => {
set({ loaded: false, success: false, message: "" });

let isSuccess = false;
// 请求接口
console.log(payload);

try {
let response = await axios.post(`${API}/signin`, payload);
localStorage.setItem("jwt", JSON.stringify(response.data));
get().signinSuccess();
isSuccess = true;
} catch (error: any) {
get().signinFail(error?.response.data.error);
isSuccess = false;
}
return isSuccess;
},
signinSuccess: () => set({ loaded: true, success: true, message: "" }),
signinFail: (message) => set({ loaded: true, success: false, message }),
Expand Down
10 changes: 10 additions & 0 deletions 5.react/8.ecommerce/ecommerce-front/src/types/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export interface User {
_id: string;
name: string;
email: string;
role: number;
}
export interface Jwt {
token: string;
user: User;
}

0 comments on commit eceda78

Please sign in to comment.