This commit is contained in:
Виталий Лавшонок
2025-10-23 14:03:01 +03:00
parent 1552ecd565
commit 8df53a4ed5
10 changed files with 581 additions and 239 deletions

8
src/axios.ts Normal file
View File

@@ -0,0 +1,8 @@
import axios from "axios";
const instance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
withCredentials: true,
});
export default instance;

View File

@@ -5,11 +5,16 @@ import "./styles/index.css";
import "./styles/palette/theme-dark.css";
import "./styles/palette/theme-light.css";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { store } from "./redux/store";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<BrowserRouter>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>
</StrictMode>
);

8
src/redux/hooks.ts Normal file
View File

@@ -0,0 +1,8 @@
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';
// типизированный dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>();
// типизированный selector
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

155
src/redux/slices/auth.ts Normal file
View File

@@ -0,0 +1,155 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "../../axios";
// Типы данных
interface AuthState {
jwt: string | null;
refreshToken: string | null;
username: string | null;
status: "idle" | "loading" | "succeeded" | "failed";
error: string | null;
}
// Инициализация состояния
const initialState: AuthState = {
jwt: null,
refreshToken: null,
username: null,
status: "idle",
error: null,
};
// AsyncThunk: Регистрация
export const registerUser = createAsyncThunk(
"auth/register",
async (
{ username, email, password }: { username: string; email: string; password: string },
{ rejectWithValue }
) => {
try {
const response = await axios.post("/authentication/register", { username, email, password });
return response.data; // { jwt, refreshToken }
} catch (err: any) {
return rejectWithValue(err.response?.data?.message || "Registration failed");
}
}
);
// AsyncThunk: Логин
export const loginUser = createAsyncThunk(
"auth/login",
async (
{ username, password }: { username: string; password: string },
{ rejectWithValue }
) => {
try {
const response = await axios.post("/authentication/login", { username, password });
return response.data; // { jwt, refreshToken }
} catch (err: any) {
return rejectWithValue(err.response?.data?.message || "Login failed");
}
}
);
// AsyncThunk: Обновление токена
export const refreshToken = createAsyncThunk(
"auth/refresh",
async ({ refreshToken }: { refreshToken: string }, { rejectWithValue }) => {
try {
const response = await axios.post("/authentication/refresh", { refreshToken });
return response.data; // { username }
} catch (err: any) {
return rejectWithValue(err.response?.data?.message || "Refresh token failed");
}
}
);
// AsyncThunk: Получение информации о пользователе
export const fetchWhoAmI = createAsyncThunk(
"auth/whoami",
async (_, { rejectWithValue }) => {
try {
const response = await axios.get("/authentication/whoami");
return response.data; // { username }
} catch (err: any) {
return rejectWithValue(err.response?.data?.message || "Failed to fetch user info");
}
}
);
// Slice
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
logout: (state) => {
state.jwt = null;
state.refreshToken = null;
state.username = null;
state.status = "idle";
state.error = null;
},
},
extraReducers: (builder) => {
// Регистрация
builder.addCase(registerUser.pending, (state) => {
state.status = "loading";
state.error = null;
});
builder.addCase(registerUser.fulfilled, (state, action: PayloadAction<{ jwt: string; refreshToken: string }>) => {
state.status = "succeeded";
state.jwt = action.payload.jwt;
state.refreshToken = action.payload.refreshToken;
});
builder.addCase(registerUser.rejected, (state, action: PayloadAction<any>) => {
state.status = "failed";
state.error = action.payload;
});
// Логин
builder.addCase(loginUser.pending, (state) => {
state.status = "loading";
state.error = null;
});
builder.addCase(loginUser.fulfilled, (state, action: PayloadAction<{ jwt: string; refreshToken: string }>) => {
state.status = "succeeded";
state.jwt = action.payload.jwt;
state.refreshToken = action.payload.refreshToken;
});
builder.addCase(loginUser.rejected, (state, action: PayloadAction<any>) => {
state.status = "failed";
state.error = action.payload;
});
// Обновление токена
builder.addCase(refreshToken.pending, (state) => {
state.status = "loading";
state.error = null;
});
builder.addCase(refreshToken.fulfilled, (state, action: PayloadAction<{ username: string }>) => {
state.status = "succeeded";
state.username = action.payload.username;
});
builder.addCase(refreshToken.rejected, (state, action: PayloadAction<any>) => {
state.status = "failed";
state.error = action.payload;
});
// Получение информации о пользователе
builder.addCase(fetchWhoAmI.pending, (state) => {
state.status = "loading";
state.error = null;
});
builder.addCase(fetchWhoAmI.fulfilled, (state, action: PayloadAction<{ username: string }>) => {
state.status = "succeeded";
state.username = action.payload.username;
});
builder.addCase(fetchWhoAmI.rejected, (state, action: PayloadAction<any>) => {
state.status = "failed";
state.error = action.payload;
});
},
});
export const { logout } = authSlice.actions;
export const authReducer = authSlice.reducer;

View File

@@ -1,15 +1,25 @@
import { configureStore } from "@reduxjs/toolkit";
//import { userReducer } from "./slices/user";
import { authReducer } from "./slices/auth";
//import { useDispatch } from "react-redux";
//const dispatch = useDispatch();
//dispatch(loginUser({ login: "123", password: "pas" }));
// useSelector((state: any) => state.user.isAuthorized.status);
const store = configureStore({
// использование
// import { useAppDispatch, useAppSelector } from '../redux/hooks';
// import { setUser, logout } from '../redux/slice/userSlice';
// export default function Profile() {
// const dispatch = useAppDispatch();
// const user = useAppSelector((state) => state.user);
export const store = configureStore({
reducer: {
//user: userReducer,
auth: authReducer,
},
});
export default store;
// тип состояния всего стора
export type RootState = ReturnType<typeof store.getState>;
// тип dispatch
export type AppDispatch = typeof store.dispatch;

View File

@@ -1,108 +1,98 @@
// import React from "react";
// import { Button } from "../../components/button/Button";
// import { Input } from "../../components/input/Input";
// import { useDispatch, useSelector } from "react-redux";
// import { useNavigate } from "react-router-dom";
// import { loginUser } from "../../redux/slices/user";
// import { setUsername, setPassword } from "../../redux/slices/user";
// import { cn } from "../../lib/cn";
import { useState, useEffect } from "react";
import { PrimaryButton } from "../../../components/button/PrimaryButton";
import { Input } from "../../../components/input/Input";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { useNavigate } from "react-router-dom";
import { loginUser } from "../../../redux/slices/auth";
import { cn } from "../../../lib/cn";
const Login = () => {
// const dispatch = useDispatch();
// const navigate = useNavigate();
const dispatch = useAppDispatch();
const navigate = useNavigate();
// const [inputUsername, setInputUsername] = React.useState<string>("");
// const [inputPassword, setInputPassword] = React.useState<string>("");
// const [inputClickLogin, setInputClickLogin] = React.useState<boolean>(false);
const [username, setUsername] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [submitClicked, setSubmitClicked] = useState<boolean>(false);
// const changeUsername = (s: string) => {
// dispatch(setUsername(s));
// setInputUsername(s);
// };
// const changePassword = (s: string) => {
// dispatch(setPassword(s));
// setInputPassword(s);
// };
const { status, error, jwt } = useAppSelector((state) => state.auth);
// const isAuthorised = useSelector((state: any) => state.user.isAuthorized);
// После успешного логина
useEffect(() => {
if (jwt) {
navigate("/home/offices"); // или другая страница после входа
}
}, [jwt]);
// React.useEffect(() => {
// if (isAuthorised) navigate("/home/offices");
// }, [isAuthorised]);
const handleLogin = () => {
setSubmitClicked(true);
// const clickLogin = () => {
// setInputClickLogin(true);
// if (inputUsername == "" || inputPassword == "") return;
// setInputClickLogin(false);
// dispatch(loginUser());
if (!username || !password) return;
dispatch(loginUser({ username, password }));
};
const navigateToRegister = () => {
navigate("/auth/register");
};
// if (isAuthorised) navigate("/home/offices");
// };
// const clickNavigateRegister = () => {
// navigate("/auth/register");
// };
return (
<div className="h-full w-full bg-default-100 flex items-center justify-center">
<div className=" bg-layout-background w-[25rem] h-[34.375rem] rounded-[15px] box-border p-[25px] relative">
<div className="text-content-1 w-full h-[3.125rem] text-[28px] font-bold text-center">
<div className="bg-layout-background w-[25rem] rounded-[15px] box-border p-[25px] relative">
<div className="text-content-1 w-full text-[28px] font-bold text-center">
Вход в аккаунт
</div>
<div className="text-content-1 w-full h-[3.4375rem] text-[12px] text-center mt-[15px]">
Для начала работы вам необходимо войти в аккаунт. Заполните поля ниже
и нажмите кнопку войти
<div className="text-content-1 w-full text-[12px] text-center mt-[15px]">
Для начала работы войдите в аккаунт. Заполните поля ниже и нажмите "Войти".
</div>
{/* <div className="mt-[15px]">
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[20px] overflow-hidden",
inputClickLogin && inputUsername == "" && "h-[21px]"
)}
>
<div className="mt-[15px] flex flex-col gap-4">
<div className={cn(
"text-[14px] text-danger font-medium transition-all overflow-hidden",
submitClicked && !username && "h-[21px]"
)}>
Поле не может быть пустым
</div>
<Input
color="danger"
required
label="Логин"
radius="sm"
className="w-[22rem]"
onChange={changeUsername}
required
onChange={(val) => setUsername(val)}
/>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[15px] overflow-hidden",
inputClickLogin && inputPassword == "" && "h-[21px]"
)}
>
<div className={cn(
"text-[14px] text-danger font-medium transition-all overflow-hidden",
submitClicked && !password && "h-[21px]"
)}>
Поле не может быть пустым
</div>
<Input
required
label="Пароль"
type="password"
radius="sm"
className="w-[22rem]"
onChange={changePassword}
required
onChange={(val) => setPassword(val)}
/>
{status === "failed" && error && (
<div className="text-[14px] text-danger font-medium">{error}</div>
)}
</div>
<div className="w-[calc(100%-50px)] absolute bottom-0">
<Button
<div className="w-[calc(100%-50px)]">
<PrimaryButton
className="w-full mb-[8px]"
size="lg"
onClick={clickLogin}
text="Войти"
onClick={handleLogin}
text={status === "loading" ? "Вход..." : "Войти"}
disabled={status === "loading"}
/>
<Button
variant="bordered"
color="default"
className="w-full mb-[25px]"
size="lg"
onClick={clickNavigateRegister}
<PrimaryButton
className="w-full mb-[25px]"
onClick={navigateToRegister}
text="Зарегистрироваться"
/>
</div> */}
</div>
</div>
</div>
);

View File

@@ -1,204 +1,109 @@
// import React from "react";
// import { Button } from "../../components/button/Button";
// import { Checkbox } from "../../components/checkbox/Checkbox";
// import { Input } from "../../components/input/Input";
// import { useDispatch, useSelector } from "react-redux";
// import { useNavigate } from "react-router-dom";
// import {
// setEmail,
// setUsername,
// setPassword,
// registerUser,
// } from "../../redux/slices/user";
// import { cn } from "../../lib/cn";
import { useState, useEffect } from "react";
import { PrimaryButton } from "../../../components/button/PrimaryButton";
import { Input } from "../../../components/input/Input";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { useNavigate } from "react-router-dom";
import { registerUser } from "../../../redux/slices/auth";
import { cn } from "../../../lib/cn";
const Register = () => {
// const dispatch = useDispatch();
// const navigate = useNavigate();
const dispatch = useAppDispatch();
const navigate = useNavigate();
// const [inputUsername, setInputUsername] = React.useState<string>("");
// const [inputEmail, setInputEmail] = React.useState<string>("");
// const [inputPassword, setInputPassword] = React.useState<string>("");
// const [inputRepeatPassword, setInputRepeatPassword] =
// React.useState<string>("");
// const [inputChecked, setInputChecked] = React.useState<boolean>(false);
// const [inputClickRegister, setInputClickRegister] =
// React.useState<boolean>(false);
const [username, setUsername] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [submitClicked, setSubmitClicked] = useState<boolean>(false);
// const changeEmail = (s: string) => {
// setInputEmail(s);
// dispatch(setEmail(s));
// };
// const changeUsername = (s: string) => {
// setInputUsername(s);
// dispatch(setUsername(s));
// };
// const changePassword = (s: string) => {
// setInputPassword(s);
// dispatch(setPassword(s));
// };
const { status, error, jwt } = useAppSelector((state) => state.auth);
// const { username, email } = useSelector((state: any) => state.user);
// После успешной регистрации
useEffect(() => {
if (jwt) {
navigate("/home/offices"); // или на любую страницу после логина
}
}, [jwt]);
// const isAuthorized = useSelector((state: any) => state.user.isAuthorized);
const handleRegister = () => {
setSubmitClicked(true);
// React.useEffect(() => {
// if (isAuthorized) navigate("/home/offices");
// }, [isAuthorized]);
if (!username || !email || !password) return;
// const clickNavigateLogin = () => {
// navigate("/auth/login");
// };
// const completeRegister = () => {
// setInputClickRegister(true);
// if (
// inputChecked == false ||
// inputEmail == "" ||
// inputUsername == "" ||
// inputPassword == "" ||
// inputRepeatPassword == "" ||
// inputPassword != inputRepeatPassword
// )
// return;
// setInputClickRegister(false);
// dispatch(registerUser());
// if (isAuthorized) navigate("/home");
// };
dispatch(registerUser({ username, email, password }));
};
return (
<div className="h-full w-full bg-default-100 flex items-center justify-center">
<div className=" bg-layout-background w-[25rem] rounded-[15px] box-border p-[25px] relative">
<div className="text-content-1 w-full h-[3.125rem] text-[28px] font-bold text-center">
Регистрация аккаунта
<div className="bg-layout-background w-[25rem] rounded-[15px] box-border p-[25px] relative">
<div className="text-content-1 w-full text-[28px] font-bold text-center">
Регистрация
</div>
<div className="text-content-1 w-full h-[3.4375rem] text-[12px] text-center mt-[15px]">
Для начала работы вам необходимо создать аккаунт. Заполните поля ниже
и нажмите кнопку продолжить
<div className="text-content-1 w-full text-[12px] text-center mt-[15px]">
Для создания аккаунта заполните поля ниже и нажмите кнопку "Зарегистрироваться"
</div>
{/* <div>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[15px] overflow-hidden",
inputClickRegister && inputUsername == "" && "h-[21px]"
)}
>
<div className="mt-[15px] flex flex-col gap-4">
{/* Username */}
<div className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden",
submitClicked && !username && "h-[21px]"
)}>
Поле не может быть пустым
</div>
<Input
required
label="Логин"
radius="sm"
className="w-[22rem]"
onChange={changeUsername}
defaultState={username}
required
onChange={(val) => setUsername(val)}
/>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[15px] overflow-hidden",
inputClickRegister && inputEmail == "" && "h-[21px]"
)}
>
{/* Email */}
<div className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden",
submitClicked && !email && "h-[21px]"
)}>
Поле не может быть пустым
</div>
<Input
required
label="Почта"
label="Email"
type="email"
radius="sm"
className="w-[22rem]"
onChange={changeEmail}
defaultState={email}
required
onChange={(val) => setEmail(val)}
/>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[15px] overflow-hidden",
inputClickRegister && inputPassword == "" && "h-[21px]"
)}
>
{/* Password */}
<div className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden",
submitClicked && !password && "h-[21px]"
)}>
Поле не может быть пустым
</div>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden",
inputClickRegister &&
inputRepeatPassword != inputPassword &&
"h-[21px]"
)}
>
Пароли не совпадают
</div>
<Input
required
label="Пароль"
type="password"
radius="sm"
className="w-[22rem]"
onChange={changePassword}
/>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all mt-[15px] overflow-hidden",
inputClickRegister && inputRepeatPassword == "" && "h-[21px]"
)}
>
Поле не может быть пустым
</div>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden",
inputClickRegister &&
inputRepeatPassword != inputPassword &&
"h-[21px]"
)}
>
Пароли не совпадают
</div>
<Input
required
label="Повторите пароль"
type="password"
radius="sm"
className="w-[22rem]"
onChange={setInputRepeatPassword}
onChange={(val) => setPassword(val)}
/>
<div
className={cn(
"text-[14px] text-danger font-medium h-0 transition-all overflow-hidden mt-[20px]",
inputClickRegister && inputChecked == false && "h-[21px]"
)}
>
Это обязательное поле
</div>
<div className="relative">
<Checkbox
className="z-10"
onChange={(state: boolean) => {
setInputChecked(state);
}}
/>
<div className="text-[10px] absolute top-0 left-[35px] text-content-1">
Согласен с Условиями обслуживания и Политикой конфиденциальности
</div>
</div>
{/* Ошибка от сервера */}
{status === "failed" && error && (
<div className="text-[14px] text-danger font-medium">{error}</div>
)}
</div>
<Button
className="w-full mb-[8px] mt-[20px]"
size="lg"
onClick={completeRegister}
text="Зарегистрироваться"
/>
<Button
variant="bordered"
color="default"
className="w-full mb-[25px]"
size="lg"
onClick={clickNavigateLogin}
text="Вернуться ко входу"
/> */}
<div className="w-[calc(100%-50px)] absolute bottom-0">
<PrimaryButton
className="w-full mb-[8px]"
onClick={handleRegister}
text={status === "loading" ? "Регистрация..." : "Зарегистрироваться"}
disabled={status === "loading"}
/>
</div>
</div>
</div>
);