From 8df53a4ed5c5b2d1767616f7803717d04dbf9d78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D0=B0=D0=BB=D0=B8=D0=B9=20=D0=9B=D0=B0?= =?UTF-8?q?=D0=B2=D1=88=D0=BE=D0=BD=D0=BE=D0=BA?= <114582703+valavshonok@users.noreply.github.com> Date: Thu, 23 Oct 2025 14:03:01 +0300 Subject: [PATCH] login --- .env | 1 + package-lock.json | 259 +++++++++++++++++++++++++++++++ package.json | 3 +- src/axios.ts | 8 + src/main.tsx | 5 + src/redux/hooks.ts | 8 + src/redux/slices/auth.ts | 155 ++++++++++++++++++ src/redux/store.ts | 24 ++- src/views/home/auth/Login.tsx | 130 +++++++--------- src/views/home/auth/Register.tsx | 227 ++++++++------------------- 10 files changed, 581 insertions(+), 239 deletions(-) create mode 100644 .env create mode 100644 src/axios.ts create mode 100644 src/redux/hooks.ts create mode 100644 src/redux/slices/auth.ts diff --git a/.env b/.env new file mode 100644 index 0000000..f3e9216 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +VITE_API_URL=https://api.liquidcode.ru \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 83484c5..8b747af 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@reduxjs/toolkit": "^2.9.2", "@types/react-redux": "^7.1.33", + "axios": "^1.12.2", "clsx": "^2.1.1", "framer-motion": "^11.9.0", "postcss": "^8.4.47", @@ -1799,6 +1800,12 @@ "dev": true, "license": "Python-2.0" }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, "node_modules/autoprefixer": { "version": "10.4.20", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", @@ -1837,6 +1844,17 @@ "postcss": "^8.1.0" } }, + "node_modules/axios": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", + "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1911,6 +1929,19 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -2028,6 +2059,18 @@ "dev": true, "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", @@ -2117,6 +2160,15 @@ "dev": true, "license": "MIT" }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -2129,6 +2181,20 @@ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", "license": "MIT" }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -2148,6 +2214,51 @@ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "license": "MIT" }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", @@ -2594,6 +2705,26 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreground-child": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", @@ -2610,6 +2741,22 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fraction.js": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", @@ -2682,6 +2829,43 @@ "node": ">=6.9.0" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/glob": { "version": "10.4.5", "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", @@ -2751,6 +2935,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -2768,6 +2964,33 @@ "node": ">=4" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", @@ -3092,6 +3315,15 @@ "yallist": "^3.0.2" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -3114,6 +3346,27 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -3540,6 +3793,12 @@ "node": ">= 0.8.0" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index ec6a523..df92240 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview" @@ -12,6 +12,7 @@ "dependencies": { "@reduxjs/toolkit": "^2.9.2", "@types/react-redux": "^7.1.33", + "axios": "^1.12.2", "clsx": "^2.1.1", "framer-motion": "^11.9.0", "postcss": "^8.4.47", diff --git a/src/axios.ts b/src/axios.ts new file mode 100644 index 0000000..3953643 --- /dev/null +++ b/src/axios.ts @@ -0,0 +1,8 @@ +import axios from "axios"; + +const instance = axios.create({ + baseURL: import.meta.env.VITE_API_URL, + withCredentials: true, +}); + +export default instance; diff --git a/src/main.tsx b/src/main.tsx index 85ed88c..dafd342 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -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( + + + ); diff --git a/src/redux/hooks.ts b/src/redux/hooks.ts new file mode 100644 index 0000000..610c2c0 --- /dev/null +++ b/src/redux/hooks.ts @@ -0,0 +1,8 @@ +import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; +import type { RootState, AppDispatch } from './store'; + +// типизированный dispatch +export const useAppDispatch = () => useDispatch(); + +// типизированный selector +export const useAppSelector: TypedUseSelectorHook = useSelector; diff --git a/src/redux/slices/auth.ts b/src/redux/slices/auth.ts new file mode 100644 index 0000000..c526bd0 --- /dev/null +++ b/src/redux/slices/auth.ts @@ -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) => { + 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) => { + 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) => { + 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) => { + state.status = "failed"; + state.error = action.payload; + }); + }, +}); + +export const { logout } = authSlice.actions; +export const authReducer = authSlice.reducer; diff --git a/src/redux/store.ts b/src/redux/store.ts index 7e94cc8..b13acc1 100644 --- a/src/redux/store.ts +++ b/src/redux/store.ts @@ -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; + +// тип dispatch +export type AppDispatch = typeof store.dispatch; diff --git a/src/views/home/auth/Login.tsx b/src/views/home/auth/Login.tsx index 35d5e68..19c39a3 100644 --- a/src/views/home/auth/Login.tsx +++ b/src/views/home/auth/Login.tsx @@ -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(""); - // const [inputPassword, setInputPassword] = React.useState(""); - // const [inputClickLogin, setInputClickLogin] = React.useState(false); + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [submitClicked, setSubmitClicked] = useState(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 (
-
-
+
+
Вход в аккаунт
-
- Для начала работы вам необходимо войти в аккаунт. Заполните поля ниже - и нажмите кнопку войти +
+ Для начала работы войдите в аккаунт. Заполните поля ниже и нажмите "Войти".
- {/*
-
+
+
Поле не может быть пустым
setUsername(val)} /> -
+ +
Поле не может быть пустым
setPassword(val)} /> + + {status === "failed" && error && ( +
{error}
+ )}
-
-
*/} +
); diff --git a/src/views/home/auth/Register.tsx b/src/views/home/auth/Register.tsx index 645df30..0611bf3 100644 --- a/src/views/home/auth/Register.tsx +++ b/src/views/home/auth/Register.tsx @@ -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(""); - // const [inputEmail, setInputEmail] = React.useState(""); - // const [inputPassword, setInputPassword] = React.useState(""); - // const [inputRepeatPassword, setInputRepeatPassword] = - // React.useState(""); - // const [inputChecked, setInputChecked] = React.useState(false); - // const [inputClickRegister, setInputClickRegister] = - // React.useState(false); + const [username, setUsername] = useState(""); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [submitClicked, setSubmitClicked] = useState(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 (
-
-
- Регистрация аккаунта +
+
+ Регистрация
-
- Для начала работы вам необходимо создать аккаунт. Заполните поля ниже - и нажмите кнопку продолжить +
+ Для создания аккаунта заполните поля ниже и нажмите кнопку "Зарегистрироваться"
- {/*
-
+
+ {/* Username */} +
Поле не может быть пустым
setUsername(val)} /> -
+ + {/* Email */} +
Поле не может быть пустым
setEmail(val)} /> -
+ + {/* Password */} +
Поле не может быть пустым
-
- Пароли не совпадают -
-
- Поле не может быть пустым -
-
- Пароли не совпадают -
- setPassword(val)} /> -
- Это обязательное поле -
-
- { - setInputChecked(state); - }} - /> -
- Согласен с Условиями обслуживания и Политикой конфиденциальности -
-
+ {/* Ошибка от сервера */} + {status === "failed" && error && ( +
{error}
+ )}
-
);