2024-04-25 16:01:08: merge [main:7f9a52684105c7ff0a068812245c462ceb6d553e];

This commit is contained in:
txix committed 2024-04-25 16:01:08 +03:00
1 parent 5a5f104174
commit a31c44eb7b
121 files changed
+14802 -84

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
PROXY_URL=
VITE_APP_TOKEN=
+4
View File
@@ -0,0 +1,4 @@
node_modules/
tsconfig.json
public/config.js
vite.config.ts
+71
View File
@@ -0,0 +1,71 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:prettier/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:@typescript-eslint/recommended",
"plugin:import/typescript"
],
"ignorePatterns": ["node_modules", "build", "generateVersionFile.cjs"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module",
"project": "./tsconfig.json",
"tsconfigRootDir": "./"
},
"plugins": [
"react",
"import",
"@typescript-eslint",
"react-hooks",
"prettier"
],
"rules": {
"import/no-named-as-default":"off",
"prettier/prettier": "off",
"quotes": ["error", "single"],
"react/jsx-filename-extension": [
1,
{
"extensions": [".js", ".jsx", ".tsx"]
}
],
"react/jsx-one-expression-per-line": "off",
"react/prop-types": 0,
"react/react-in-jsx-scope": "off",
"semi": ["error", "never"],
"@typescript-eslint/no-unused-vars": ["off"],
"@typescript-eslint/no-explicit-any": ["off", null],
"@typescript-eslint/no-non-null-assertion": ["off"],
"import/no-unresolved": "error",
"no-unused-vars": "off"
},
"settings": {
"import/parsers": {
"@typescript-eslint/parser": [".ts", ".tsx"]
},
"react": {
"version": "detect"
},
"import/resolver": {
"typescript": {
"alwaysTryTypes": true
},
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"moduleDirectory": ["node_modules", "src/"]
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
.idea/
dist/
build/
node_modules/
src/**/*.jsx
tests/__coverage__/
tests/**/*.jsx
.yarn/*
!.yarn/patches
!.yarn/releases
!.yarn/plugins
!.yarn/sdks
!.yarn/versions
.pnp.*
.env
version.json
+42
View File
@@ -0,0 +1,42 @@
{
"trailingComma": "none",
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"quoteProps": "preserve",
"arrowParens": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"proseWrap": "never",
"htmlWhitespaceSensitivity": "strict",
"plugins": ["@trivago/prettier-plugin-sort-imports"],
"useTabs": false,
"overrides": [
{
"files": "*.tsx",
"options": {
"parser": "typescript"
}
}
],
"importOrder": [
"^@core/(.*)$",
"^@assets/(.*)$",
"^@constants/(.*)$",
"^@ui/(.*)$",
"^@widgets/(.*)$",
"^@components/(.*)$",
"^@modules/(.*)$",
"^@pages/(.*)$",
"^@utils/(.*)$",
"^@hooks/(.*)$",
"^@services/(.*)$",
"^@stores/(.*)$",
"^@routes/(.*)$",
"^@type/(.*)$",
"^./*.*.ts",
"^[./]",
"^./*.*.(scss|css)"
],
"importOrderSeparation": true
}
+42
View File
@@ -0,0 +1,42 @@
## 0.8.1
- Перенос UserMenu в список главного меню в Layout
## 0.8.0
- Добавлена страница 'Роли'
## 0.7.0
- Добавлена страница 'Сессии'
## 0.6.0
- Добавлена страница 'Просмотр журналов ИБ'
## 0.5.0
- Добавлена страница 'Пользователи' и страница редактирования пользователя
## 0.4.0
- Добавлен экран управления доступами приложений
- Исправлены корневые стили приложения
- Обновлена поддержка пользовательских разрешений для страниц
- Добавлена локализация Antd
## 0.3.2
- Добавлен generateVersionFile.cjs
## 0.3.1
-Добавлена обработка ошибок в интерсепторсе
## 0.3.0
- Добавлен экран Профиля
- Добавлено хранилище ролей
- Изменен пакетный менеджер на npm
- Улучшения стилей приложения
## 0.2.6
- Добавлено модальное окно
## 0.2.5
- UserMenu изменен и перенесен из Header в Menu из Layout, удален Header
## 0.2.4
- Изменен Layout
## 0.2.3
- Добавлен экран входа
## 0.2.2
- Добавлен редирект после логина
## 0.2.1
- ThemeProvider заменен на ConfigProvider в компоненте <App>
## 0.2.0
- Добавлены роли и приватный роутер
## 0.1.0
- Инициализирован проект
- Добавлена темная тема antd
- Добавлен layout
+12
View File
@@ -0,0 +1,12 @@
FROM node:20-alpine as build-deps
WORKDIR /usr/src/app
COPY . ./
RUN apk add git
RUN npm install
RUN npm run build
FROM nginx:1.25-alpine-slim
EXPOSE 80
COPY cfg/80_isp-admin-ui.conf /etc/nginx/conf.d/80_isp-admin-ui.conf
COPY --from=build-deps /usr/src/app/build /opt/msp/isp-admin-ui
+21 -84
View File
@@ -1,93 +1,30 @@
# isp-admin-ui
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
## Getting started
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
## Expanding the ESLint configuration
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
## Add your files
- Configure the top-level `parserOptions` property like this:
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.txix.ru/isp/isp-admin-ui.git
git branch -M main
git push -uf origin main
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname
}
}
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.txix.ru/isp/isp-admin-ui/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
+18
View File
@@ -0,0 +1,18 @@
server {
listen 80;
server_name localhost;
root /opt/msp/isp-admin-ui/;
location / {
try_files $uri /index.html;
}
location /api {
client_max_body_size 10M;
proxy_pass http://10.2.4.241:9003;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
+33
View File
@@ -0,0 +1,33 @@
const fs = require('fs');
const packageJson = require('./package.json');
function writeJsonFile(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data));
}
function readHtmlFile(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
function writeHtmlFile(filePath, data) {
fs.writeFileSync(filePath, data);
}
const welcomePagePath = 'build/index.html';
let indexHtml = readHtmlFile(welcomePagePath);
const scriptTagRegex = /<script type="module">window\.AppVersion\s*=\s*'.*';<\/script>/;
const scriptTag = `<script type="module">window.AppVersion = '${packageJson.version}';</script>`;
indexHtml = indexHtml
.replace(scriptTagRegex, '')
.replace('</head>', `${scriptTag}</head>`);
writeHtmlFile(welcomePagePath, indexHtml);
const versionData = {
version: packageJson.version,
};
writeJsonFile('build/version.json', versionData);
writeJsonFile('version.json', versionData);
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<script type="module" src="/src/index.tsx"></script>
<script type="module">
window.AppVersion = APP_VERSION
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>
+9920
View File
File diff suppressed because it is too large. Load diff
+72
View File
@@ -0,0 +1,72 @@
{
"name": "isp-admin-ui",
"private": true,
"version": "0.8.1",
"type": "module",
"scripts": {
"start": "vite",
"build": "tsc && vite build && node generateVersionFile.cjs",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"fix:prettier": "prettier --write \"src/**/*.{ts,tsx, js}\"",
"lint:fix": "eslint --fix .",
"analyze": "source-map-explorer 'build/static/js/*.js'",
"prepare": "husky install"
},
"dependencies": {
"@reduxjs/toolkit": "^2.2.3",
"@types/react-router-dom": "^5.3.3",
"axios": "^1.6.8",
"isp-ui-kit": "https://github.com/txix-open/isp-ui-kit",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.51.2",
"react-redux": "^9.1.0",
"react-resizable": "^3.0.5",
"react-router-dom": "^6.22.3",
"simplebar": "^6.2.5",
"simplebar-react": "^3.2.4"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@types/node": "^20.12.4",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.24",
"@types/react-resizable": "^3.0.7",
"@typescript-eslint/eslint-plugin": "^7.5.0",
"@typescript-eslint/parser": "^7.5.0",
"@vitejs/plugin-legacy": "^5.3.2",
"@vitejs/plugin-react": "^4.2.1",
"@vitejs/plugin-react-swc": "^3.6.0",
"antd": "5.16.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"husky": "^9.0.11",
"prettier": "^3.2.5",
"sass": "^1.74.1",
"terser": "^5.30.3",
"typescript": "^5.4.3",
"vite": "^5.2.8",
"vite-plugin-style-import": "^2.0.0",
"vite-plugin-svgr": "^4.2.0",
"vite-tsconfig-paths": "^4.3.2"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"husky": {
"hooks": {
"pre-coomit": "eslint --fix .",
"pre-push": "eslint --fix ."
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="24" height="24" fill="url(#pattern0)"/>
<defs>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_121_5920" transform="scale(0.0025)"/>
</pattern>
<image id="image0_121_5920" width="400" height="400" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAYAAACAvzbMAAAgAElEQVR4Ae29e9AcVbnvn7JqV/mP5w/P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njMJUaR0NhBzwc4EW3FzNVXFFBdaiXC0Q27VPlXq7ci55HWc833JNLWwzdg+/68LNyZtabVpffo2GglfDElFG2LyIuIgwtpOzr1+W+lNFOm+ZJMmgZ19NzukNMYNjgkbSFLfCzzB0tUVLXCUrmetiEEn6vRRfLAx1bQunnLlmnBFJRZYBBzVlKnmi2esUENpbr4Xyi4KAGZd7roumESSP8/tCzH2osmKFdDXJ3Rzb+Css6eA+h572X+r/yCL9w2XqyVXNEKiIRP1zXkw2F38SGr3TSystWIZiwUsqdpz1PWb/DtEfoM6Y9dvkjDwZfAaXxWbEDugAy+TX4dYKdGglXJmmPkGl8DuS5mDLyOcb37B7I74MdHqkTRuQb5+X8BDJwPa6L3+rcoZf8UvBX3vMnX05ZTH62TcX6DdMu6x7oeYsnp44nGzS8twIS6XRlqQ7g4gdwIFMif4IVcPSVnIXgd2W9QlKQA4B82sKNPkgDpAC4zdkcbacLnyEifEcQDgQRFLskCCJKxBCRqc2YtsqSs563vDmULine truncated
</defs>
</svg>

After

Width:  |  Height:  |  Size: 35 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.2118 12.3535L9.15396 8.29564C9.78364 7.48158 10.1243 6.48627 10.1243 5.43939C10.1243 4.18627 9.6352 3.01127 8.75083 2.12533C7.86645 1.23939 6.68833 0.751892 5.43677 0.751892C4.1852 0.751892 3.00708 1.24095 2.1227 2.12533C1.23677 3.0097 0.749268 4.18627 0.749268 5.43939C0.749268 6.69095 1.23833 7.86908 2.1227 8.75345C3.00708 9.63939 4.18364 10.1269 5.43677 10.1269C6.48364 10.1269 7.47739 9.78627 8.29146 9.15814L12.3493 13.2144C12.3612 13.2263 12.3753 13.2357 12.3908 13.2422C12.4064 13.2486 12.4231 13.2519 12.4399 13.2519C12.4567 13.2519 12.4734 13.2486 12.4889 13.2422C12.5045 13.2357 12.5186 13.2263 12.5305 13.2144L13.2118 12.5347C13.2237 12.5228 13.2331 12.5087 13.2396 12.4931C13.246 12.4776 13.2493 12.4609 13.2493 12.4441C13.2493 12.4272 13.246 12.4106 13.2396 12.395C13.2331 12.3795 13.2237 12.3654 13.2118 12.3535ZM7.91177 7.91439C7.24927 8.57533 6.37114 8.93939 5.43677 8.93939C4.50239 8.93939 3.62427 8.57533 2.96177 7.91439C2.30083 7.25189 1.93677 6.37377 1.93677 5.43939C1.93677 4.50502 2.30083 3.62533 2.96177 2.96439C3.62427 2.30345 4.50239 1.93939 5.43677 1.93939C6.37114 1.93939 7.25083 2.30189 7.91177 2.96439C8.57271 3.62689 8.93677 4.50502 8.93677 5.43939C8.93677 6.37377 8.57271 7.25346 7.91177 7.91439Z" fill="black" fill-opacity="0.85"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 382 KiB

+16
View File
@@ -0,0 +1,16 @@
import { PropsWithChildren } from 'react'
import { useRole } from '@hooks/useRole.tsx'
import { PermissionKeysType } from '@type/roles.type.ts'
const AdminPermission = ({ children }: PropsWithChildren) => {
const { hasPermission } = useRole()
if (hasPermission(PermissionKeysType.read)) {
return <>{children}</>
}
return null
}
export default AdminPermission
+27
View File
@@ -0,0 +1,27 @@
import { ConfigProvider } from 'antd'
import ruRu from 'antd/locale/ru_RU'
import { useState } from 'react'
import { lightTheme } from '@constants/theme.ts'
import { Context } from '@stores/index.tsx'
import Routers from '@routes/Routers'
import './app.scss'
const App = () => {
const [themes, setTheme] = useState(lightTheme)
return (
<div className="app">
<Context.Provider value={{ setTheme }}>
<ConfigProvider theme={themes} locale={ruRu}>
<Routers />
</ConfigProvider>
</Context.Provider>
</div>
)
}
export default App
@@ -0,0 +1,36 @@
@import 'src/constants/style/styleConst';
.app-access-content {
height: 100%;
width: 100%;
min-width: 760px;
padding: $basic-padding * 2;
border: 1px solid $border-color;
&__header {
display: flex;
justify-content: space-between;
margin-bottom: $basic-margin * 2;
&__action-buttons {
display: flex;
gap: $basic-margin * 2;
}
}
&__main {
display: grid;
grid-template-columns:1fr 1fr;
&__tree-search-input {
width: 350px;
margin-bottom: $basic-margin * 2;
}
}
.unknown-label {
color: $error-red
}
}
@@ -0,0 +1,4 @@
export interface AppAccessContentPropsType {
id: number
paramPrefix: string
}
+208
View File
@@ -0,0 +1,208 @@
import { SearchOutlined } from '@ant-design/icons'
import { Button, Input, message, Spin, TreeProps } from 'antd'
import { ChangeEvent, FC, memo, useEffect, useState } from 'react'
import { Navigate, useSearchParams } from 'react-router-dom'
import AccessListTree from '@widgets/AccessListTree'
import SelectedAccessMethod from '@widgets/SelectedAccessMethod'
import { AppAccessContentPropsType } from '@components/AppAccessContent/app-access-content.type.ts'
import { setSearchValue } from '@utils/columnLayoutUtils.ts'
import useRole from '@hooks/useRole.tsx'
import accessListApi from '@services/accessListService.ts'
import routeApi from '@services/routeService.ts'
import { routePaths } from '@routes/routePaths.ts'
import { AccessListMethodType, EndpointType } from '@type/accessList.type.ts'
import { PermissionKeysType } from '@type/roles.type.ts'
import './app-access-content.scss'
const unknownMethodKey = 'неизвестные методы'
const AppAccessContent: FC<AppAccessContentPropsType> = ({
id,
paramPrefix
}) => {
const [messageApi, contextHolder] = message.useMessage()
const { hasPermission } = useRole()
const canWrite = hasPermission(PermissionKeysType.write)
const {
data: methods = [],
isLoading: isMethodsLoading,
isError: isMethodsError,
isSuccess: isMethodsSuccess
} = accessListApi.useGetByIdQuery({ id })
const [setList] = accessListApi.useSetListMutation()
const [setOne] = accessListApi.useSetOneMutation()
const {
data: routes = {
originalResponse: [],
moduleEndpoints: {},
allRouteMap: {}
},
isLoading: isRouteLoading,
isError: isRouteError,
isSuccess: isRouteSuccess
} = routeApi.useGetAllRoutesQuery()
const { moduleEndpoints, allRouteMap } = routes
const [defaultAllRoutes, setDefaultAllRoutes] = useState<
Record<string, EndpointType[]>
>({})
const [searchParams, setSearchParams] = useSearchParams()
const searchValue = searchParams.get(paramPrefix) || ''
const isLoading = isMethodsLoading || isRouteLoading
const isError = isMethodsError || isRouteError
const isSuccess = isMethodsSuccess && isRouteSuccess
const openSuccessMessage = (body: string) => {
messageApi.success(body)
}
const openErrorMessage = (body: string) => {
messageApi.error(body)
}
const createAllMethodList = (status: boolean) => {
return Object.keys(allRouteMap).map((key) => {
return {
method: key,
value: status
}
})
}
const onCheck: TreeProps['onCheck'] = (_, info): void | never[] => {
const { node } = info
if (!node.children) {
const sendData = {
appId: id,
method: node.key as string,
value: !node.checked
}
setOne(sendData)
.then(() => {
openSuccessMessage('Статус метода успешно изменен')
})
.catch(() => {
openErrorMessage('Не удалось изменить статус метода')
})
return
}
const newCheckedKeys = node.children.map((child) => ({
method: child.key as string,
value: !node.checked
}))
setListMethods(newCheckedKeys)
}
const onChange = (e: ChangeEvent<HTMLInputElement>) => {
const { value } = e.target
setSearchValue(value.trim().toLowerCase(), setSearchParams, paramPrefix)
}
const setListMethods = (methods: AccessListMethodType[]) => {
setList({
appId: id,
methods: methods
})
.then(() => {
openSuccessMessage('Статус методов успешно изменен')
})
.catch(() => {
openErrorMessage('Не удалось изменить статус методов')
})
}
const setAllMethods = (status: boolean) => {
const methods = createAllMethodList(status)
setListMethods(methods)
}
const getAllRoutes = () => {
const missingRoute: EndpointType[] = []
const copyAllRoutes = { ...moduleEndpoints }
methods.forEach((item) => {
if (!allRouteMap[item.method]) {
missingRoute.push({ path: item.method } as EndpointType)
}
})
if (missingRoute.length) {
copyAllRoutes[unknownMethodKey] = missingRoute
}
return copyAllRoutes
}
useEffect(() => {
const allRoutes = getAllRoutes()
setDefaultAllRoutes(allRoutes)
}, [isSuccess])
if (isLoading) {
return <Spin className="spin" />
}
if (isError) {
return <Navigate to={routePaths.error} />
}
return (
<div className="app-access-content">
{contextHolder}
<div className="app-access-content__header">
<Input
prefix={<SearchOutlined />}
allowClear
className="app-access-content__main__tree-search-input"
value={searchValue}
placeholder="Найти метод"
onChange={onChange}
/>
<div className="app-access-content__header__action-buttons">
<Button disabled={!canWrite}
onClick={() => {
setAllMethods(false)
}}
>
Запретить все
</Button>
<Button
disabled={!canWrite}
onClick={() => {
setAllMethods(true)
}}
>
Выбрать все
</Button>
</div>
</div>
<div className="app-access-content__main">
<AccessListTree
searchValue={searchValue}
onCheck={onCheck}
defaultAllRoutes={defaultAllRoutes}
methods={methods}
/>
<SelectedAccessMethod
unknownMethodKey={unknownMethodKey}
methods={methods}
allRoutes={defaultAllRoutes}
/>
</div>
</div>
)
}
export default memo(AppAccessContent)
@@ -0,0 +1,10 @@
export type ChangePasswordModalType = {
oldPassword: string
newPassword: string
confirmPassword: string
}
export type ChangePasswordModalProps = {
open: boolean
onClose: () => void
}
@@ -0,0 +1,68 @@
import { FormComponents } from 'isp-ui-kit'
import { FC } from 'react'
import { useForm } from 'react-hook-form'
import Modal from '@widgets/Modal'
import {
ChangePasswordModalProps,
ChangePasswordModalType
} from '@components/ChangePasswordModal/change-password-modal.type.ts'
const { FormInputPassword } = FormComponents
const ChangePasswordModal: FC<ChangePasswordModalProps> = ({
open,
onClose
}) => {
const { control, handleSubmit } = useForm<ChangePasswordModalType>({
mode: 'onChange'
})
const onSubmit = (formValue: ChangePasswordModalType) => {
//TODO добавить бэк, как появится
console.log(formValue)
}
return (
<Modal
title="Сменить пароль"
open={open}
onClose={onClose}
onOk={handleSubmit(onSubmit)}
footer={{ onOkText: 'Изменить пароль', onCanselText: 'Отмена' }}
>
<form key="change-pass-modal">
<FormInputPassword
rules={{
required: { value: true, message: 'Поле не может быть пустым' }
}}
label="Старый пароль"
control={control}
name="oldPassword"
/>
<FormInputPassword
rules={{
required: { value: true, message: 'Поле не может быть пустым' }
}}
label="Новый пароль"
control={control}
name="newPassword"
/>
<FormInputPassword
rules={{
required: { value: true, message: 'Поле не может быть пустым' },
validate: (value, formValues) => {
const { newPassword } = formValues
return value !== newPassword ? 'Пароли не совпадают' : true
}
}}
label="Подтвердите пароль"
control={control}
name="confirmPassword"
/>
</form>
</Modal>
)
}
export default ChangePasswordModal
+5
View File
@@ -0,0 +1,5 @@
.error-page {
min-height: 100vh;
display: flex;
justify-content: center;
}
+9
View File
@@ -0,0 +1,9 @@
const ErrorPage = () => {
return (
<section className="error-page">
<p>Извините, ошибка</p>
</section>
)
}
export default ErrorPage
+35
View File
@@ -0,0 +1,35 @@
const DefaultUser = () => {
return (
<span role="img" className="anticon ant-menu-item-icon">
<svg
data-icon="appstore"
width="1.5em"
height="1.5em"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<rect width="24" height="24" fill="url(#pattern0)" />
<defs>
<pattern
id="pattern0"
patternContentUnits="objectBoundingBox"
width="1"
height="1"
>
<use xlinkHref="#image0_121_5920" transform="scale(0.0025)" />
</pattern>
<image
id="image0_121_5920"
width="400"
height="400"
xlinkHref="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAYAAACAvzbMAAAgAElEQVR4Ae29e9AcVbnvn7JqV/mP5w/PH5YQuQgYRcIlBaRAkmACKBQ3cQPyCwUGs1Pctv5gi8IBIWhSapAtAmfDO+/7GhRPwQbMBSFbSDCH24YYCJDpSZBggSGFsnETiVwUjM+pT/N26PS7Vt+mu2d19zNVUzPTM9O91tNrfb/rua4JE/ShEmiQBBa/IB8c3iQTf7xBpoz0ZNZIT04d9uSCoa7MH+7K9UM9ubXjyYqOJw91urKm05WnO55s6HTl+SFPNg958sqQJ1s7PXmr05V3/WdP3uLY2Heb+e3Yf572z8G5PFnBuf1rcC1PLuDatIG20Cba1iBRa1dUAioBlUC9JHDHS/LhMXI4dcSTi4Y3yI1jhAAJvDHUFXH5SRt98vFkBW2nDxANfaJv9bob2lqVgEpAJeCYBOaLfOAnG+UTACuaQ6crSzs9WT/kyTaXyaGQtnmyjb7SZ/qODJAFMnHsNmlzVAIqAZXAYCXAqts3NXlyUacnI8OerMV8VAgYO66NZOkjMhmTzciY1jJLNZbBjl29ukpAJVChBFhF+/4AfBI9ud33OTQI5LMQQmG/xW/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2t5LELWQ9+bo/9JNGEw5tjInRVaJJXwVMGLine truncated
/>
</defs>
</svg>
</span>
)
}
export default DefaultUser
+215
View File
@@ -0,0 +1,215 @@
import {
LockOutlined,
LogoutOutlined,
ProfileOutlined
} from '@ant-design/icons'
import { ConfigProvider, Layout, Menu, Spin } from 'antd'
import { useContext, useEffect, useState } from 'react'
import { Navigate, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { localStorageKeys } from '@constants/localStorageKeys.ts'
import DefaultUser from '@components/Icons/DefaultUser.tsx'
import {
MenuItemKeysType,
MenuItemType,
menuKeys
} from '@components/Layout/layout.type.ts'
import { LocalStorage } from '@utils/localStorageUtils.ts'
import { useAppDispatch, useAppSelector } from '@hooks/redux.ts'
import useLogout from '@hooks/useLogout.tsx'
import useRole from '@hooks/useRole.tsx'
import { fetchProfile } from '@stores/redusers/ActionCreators.ts'
import { StateProfileStatus } from '@stores/redusers/ProfileSlice.ts'
import { routePaths } from '@routes/routePaths.ts'
import { PermissionKeysType } from '@type/roles.type.ts'
import './layout.scss'
const { Content, Sider } = Layout
const LayoutComponent = () => {
const [collapsed, setCollapsed] = useState<boolean>(false)
const [selectedMenuKeys, setSelectedMenuKeys] = useState<MenuItemKeysType[]>(
[]
)
const [openKeys, setOpenKeys] = useState<string[]>([])
const dispatch = useAppDispatch()
const {
status,
profile: { firstName }
} = useAppSelector((state) => state.profileReducer)
const location = useLocation()
const navigate = useNavigate()
const { hasPermission } = useRole()
const { theme } = useContext(ConfigProvider.ConfigContext)
const userToken = LocalStorage.get(localStorageKeys.USER_TOKEN)
const { logoutUser } = useLogout()
const hideItem = (permission: PermissionKeysType | PermissionKeysType[]) => {
if (Array.isArray(permission)) {
const result = permission.reduce((acc, currentValue) => {
const hasPermissionFunc = hasPermission(currentValue)
return hasPermissionFunc || acc
}, false)
return result ? '' : 'hide-item'
}
return hasPermission(permission) ? '' : 'hide-item'
}
const menuItems: MenuItemType[] = [
{
label: firstName || '',
key: 'userManagement',
className: 'user-item',
icon: <DefaultUser />,
children: [
{
label: 'Профиль',
key: 'profile',
icon: <ProfileOutlined />
},
{
label: 'Выход',
key: 'logout',
icon: <LogoutOutlined />
}
]
},
{
label: 'Доступы приложений',
key: 'appAccess',
className: hideItem([PermissionKeysType.read]),
icon: <LockOutlined />
},
{
label: 'Пользователи и роли',
key: 'sessionManagement',
className: hideItem([PermissionKeysType.read]),
icon: <ProfileOutlined />,
children: [
{
label: 'Пользователи',
key: 'users',
className: hideItem(PermissionKeysType.read)
},
{
label: 'Пользовательские сессии',
key: 'sessions',
className: hideItem(PermissionKeysType.read)
},
{
label: 'Просмотр журналов ИБ',
key: 'securityLog',
className: hideItem(PermissionKeysType.read)
},
{
label: 'Роли',
key: 'roles',
className: hideItem(PermissionKeysType.read)
}
]
}
]
useEffect(() => {
ConfigProvider.config({
holderRender: (children) => (
<ConfigProvider prefixCls="static" theme={theme}>
{children}
</ConfigProvider>
)
})
}, [theme])
useEffect(() => {
if (userToken) {
dispatch(fetchProfile())
}
}, [])
useEffect(() => {
const menuKey = location.pathname.split('/')[1] as MenuItemKeysType
const menuItem = menuKeys[menuKey]
if (menuItem) {
setSelectedMenuKeys([menuItem.key])
setOpenKeys(menuItem.parent)
}
}, [location])
const handlerOnClickMenu = ({ key }: any): void => {
switch (key) {
case MenuItemKeysType.logout: {
logoutUser()
break
}
case MenuItemKeysType.profile: {
navigate(routePaths.profile)
break
}
case MenuItemKeysType.users:
navigate(routePaths.users)
break
case MenuItemKeysType.sessions:
navigate(routePaths.sessions)
break
case MenuItemKeysType.securityLog:
navigate(routePaths.securityLog)
break
case MenuItemKeysType.appAccess:
navigate(routePaths.appAccess)
break
case MenuItemKeysType.roles:
navigate(routePaths.roles)
break
default:
}
}
if (status === StateProfileStatus.rejected) {
return <Navigate to={routePaths.error} replace />
}
return (
<Layout className="layout" data-cy="homePage">
{status === StateProfileStatus.pending ? (
<Spin size="large" />
) : (
<>
<Sider
width="250px"
data-cy="aside"
theme="light"
collapsible
collapsed={collapsed}
onCollapse={(value) => setCollapsed(value)}
>
<Menu
onOpenChange={(keys) => setOpenKeys(keys)}
openKeys={openKeys}
selectedKeys={selectedMenuKeys}
onClick={handlerOnClickMenu}
theme="light"
mode="inline"
items={menuItems}
/>
</Sider>
<Layout className="site-layout">
<Content className="site-layout__content">
<Outlet />
</Content>
</Layout>
</>
)}
</Layout>
)
}
export default LayoutComponent
+95
View File
@@ -0,0 +1,95 @@
@import 'src/constants/style/styleConst';
.layout {
min-height: 100vh !important;
position: relative;
.hide-item {
display: none !important;
}
.ant-spin {
position: absolute;
top: 50%;
left: 50%;
}
.header {
display: flex;
align-items: center;
justify-content: flex-end;
line-height: 18px;
background: #fff;
padding: 0;
&__search {
max-width: 300px;
border: none;
margin-right: auto;
padding-right: 40px;
position: relative;
&:after {
content: '';
background: url("/src/assets/icon/search-icon.svg");
width: 13px;
height: 13px;
position: absolute;
right: 45px;
top: 50%;
transform: translateY(-50%);
}
.ant-input-search .ant-input:focus, .ant-input-search .ant-input:hover {
border-color: red !important;
}
& .ant-input {
border: none;
}
& button {
border: none;
display: none;
}
}
}
.ant-menu {
border-inline-end: none !important;
}
.ant-menu-title-content {
color: #1B1B1B;
padding-left: 10px
}
}
.user-item {
padding: $basic-padding 0 $basic-padding * 3;
& .ant-menu-submenu-arrow {
display: none !important;
}
border-bottom: 1px solid lightgray;
border-radius: 0 !important;
& .ant-menu-submenu-title {
padding-left: 21px !important;
}
& .ant-menu-title-content {
margin: 0 !important;
padding-left: 17px !important;
}
}
.ant-menu-inline-collapsed {
& .user-item {
& .ant-menu-submenu-title {
padding-left: 24px !important;
padding-top: 5px !important;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
import { MenuProps } from 'antd'
export enum MenuItemKeysType {
users = 'users',
sessions = 'sessions',
securityLog = 'securityLog',
appAccess = 'appAccess',
roles = 'roles',
logout = 'logout',
profile = 'profile'
}
interface MenuItem {
key: MenuItemKeysType
parent: string[]
}
export const menuKeys: Record<MenuItemKeysType, MenuItem> = {
[MenuItemKeysType.users]: {
key: MenuItemKeysType.users,
parent: ['sessionManagement']
},
[MenuItemKeysType.sessions]: {
key: MenuItemKeysType.sessions,
parent: ['sessionManagement']
},
[MenuItemKeysType.securityLog]: {
key: MenuItemKeysType.securityLog,
parent: ['sessionManagement']
},
[MenuItemKeysType.appAccess]: {
key: MenuItemKeysType.appAccess,
parent: []
},
[MenuItemKeysType.roles]: {
key: MenuItemKeysType.roles,
parent: ['sessionManagement']
},
[MenuItemKeysType.logout]: {
key: MenuItemKeysType.logout,
parent: ['']
},
[MenuItemKeysType.profile]: {
key: MenuItemKeysType.profile,
parent: ['']
}
}
export type MenuItemType = Required<MenuProps>['items'][number]
+38
View File
@@ -0,0 +1,38 @@
import { Descriptions, Spin } from 'antd'
import { RoleListProps } from '@components/RoleList/role-list.type.ts'
import roleApi from '@services/roleService.ts'
import './role-list.scss'
const RoleList = ({ userRoles }: RoleListProps) => {
const { data: roles = [], isLoading, isError } = roleApi.useGetAllRolesQuery()
const roleIds = new Set(userRoles)
if (isError) {
return null
}
return (
<Descriptions layout="vertical" className="role-list">
<Descriptions.Item label="Список ролей">
{isLoading ? (
<Spin className="spin" />
) : (
<ul>
{roles.map((roleData) => {
if (roleIds.has(roleData.id) && roleData.name) {
return <li key={roleData.id}>{roleData.name}</li>
}
return null
})}
</ul>
)}
</Descriptions.Item>
</Descriptions>
)
}
export default RoleList
+19
View File
@@ -0,0 +1,19 @@
@import "src/constants/style/styleConst";
.role-list {
.ant-descriptions-item-label {
font-size: $text-size-header2;
}
.spin {
position: initial;
}
ul, li {
list-style-position: inside
}
li {
font-size: $text-size
}
}
@@ -0,0 +1,3 @@
export type RoleListProps = {
userRoles: number[]
}
+163
View File
@@ -0,0 +1,163 @@
import { Divider, Table, message } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { FormComponents } from 'isp-ui-kit'
import { useEffect, useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { useParams } from 'react-router-dom'
import { ValidationRules } from '@constants/form/validationRules.ts'
import SaveButton from '@ui/SaveButton'
import AgreementModal from '@widgets/AgreementModal'
import { RolesContentPropsType } from '@components/RolesContent/roles-content.type.ts'
import useRole from '@hooks/useRole.tsx'
import { PermissionKeysType, RoleType } from '@type/roles.type.ts'
import './roles-content.scss'
const newRole: Partial<RoleType> = {
externalGroup: '',
name: '',
permissions: []
}
const columns: ColumnsType = [
{
title: 'Действие',
dataIndex: 'name'
},
{
title: 'Ключ в системе',
dataIndex: 'key'
}
]
const { FormInput } = FormComponents
const RolesContent = ({
role,
permissions,
saveRole,
title = 'Редактировать',
immutable = false
}: RolesContentPropsType) => {
const {
control,
formState: { isDirty },
getValues,
reset
} = useForm<RoleType>({
defaultValues: role,
mode: 'onChange'
})
const { hasPermission } = useRole()
const { id: selectedItemId } = useParams()
const [openModal, setOpenModal] = useState<boolean>(false)
const isUpdateRole = hasPermission(PermissionKeysType.write)
const isCreateRole = hasPermission(PermissionKeysType.write)
const isSaveBtnAvailable =
selectedItemId === 'new' ? isCreateRole : isUpdateRole
const isExternalGroup = hasPermission(PermissionKeysType.write)
useEffect(() => {
if (!role) {
reset(newRole)
} else {
reset(role)
}
}, [role])
const handleSubmitForm = (changeMessage: string) => {
if (!changeMessage) {
message.error('Поле не может быть пустым')
return
}
const formValue = getValues()
formValue.changeMessage = changeMessage
saveRole(formValue)
setOpenModal(false)
}
const renderFormTable = () => (
<Controller
control={control}
name="permissions"
render={({ field: { value, onChange } }) => (
<Table
columns={columns}
dataSource={permissions}
pagination={{ pageSize: 10 }}
scroll={{
y: 'calc(100vh - 450px)',
}}
rowSelection={{
selectedRowKeys: value,
type: 'checkbox',
onChange: (selectedRowKeys) => {
onChange(selectedRowKeys)
},
getCheckboxProps: () => ({
disabled: immutable
})
}}
/>
)}
/>
)
return (
<>
{openModal && (
<AgreementModal
open
destroyOnClose
onCancel={() => setOpenModal(false)}
okText="Сохранить"
title="Для подтверждения изменений укажите причину"
description="Основание для измений"
onConfirm={handleSubmitForm}
/>
)}
<form className="roles-content">
<div className="roles-content__header">
<h2
data-cy="roles-content__header__title"
className="roles-content__header__title"
>
{title}
</h2>
<SaveButton
disabled={!isDirty || !isSaveBtnAvailable}
type="primary"
data-cy="roles-content__header__save-button"
onClick={() => setOpenModal(true)}
className="roles-content__header__save-button"
/>
</div>
<Divider />
<FormInput
data-cy="roles-content__input__name"
rules={{ required: ValidationRules.required }}
label="Наименование роли"
name="name"
control={control}
/>
<FormInput
data-cy="roles-content__input__external-group"
disabled={!isExternalGroup}
label="Группы ЕСК"
name="externalGroup"
control={control}
/>
{renderFormTable()}
</form>
</>
)
}
export default RolesContent
@@ -0,0 +1,11 @@
@import "../../constants/style/styleConst";
.roles-content {
padding: $basic-padding*3;
min-width: 400px;
&__header {
display: flex;
justify-content: space-between;
}
}
@@ -0,0 +1,9 @@
import { NewRoleType, PermissionType, RoleType } from '@type/roles.type.ts'
export interface RolesContentPropsType {
role?: Partial<RoleType>
title?: string
immutable?: boolean
permissions: PermissionType[]
saveRole: (formValue: RoleType | NewRoleType) => void
}
+20
View File
@@ -0,0 +1,20 @@
@import "src/constants/style/styleConst";
*, html {
margin:0;
padding:0;
box-sizing: border-box;
}
.app{
overflow: hidden;
height: 100vh;
padding: 0 $basic-padding;
min-height: 0;
min-width: 500px;
}
.wrap {
padding: 2 * $basic-padding;
border: 1px solid #F0F0F0;
}
+70
View File
@@ -0,0 +1,70 @@
type PathKeys =
| 'baseUrl'
| 'baseSystemUrl'
| 'baseConfigUrl'
| 'getAllRoles'
| 'createRole'
| 'updateRole'
| 'deleteRole'
| 'login'
| 'logout'
| 'getProfile'
| 'getUsers'
| 'createUser'
| 'updateUser'
| 'blockUser'
| 'deleteUser'
| 'getRoles'
| 'getAllPermissions'
| 'baseUserUrl'
| 'baseAdminUrl'
| 'getAllSession'
| 'revokeSession'
| 'getAllLogs'
| 'getLogEvents'
| 'setLogEvents'
| 'getSystemTree'
| 'getById'
| 'setList'
| 'setOne'
| 'getAllRoutes'
export const apiPaths: Record<PathKeys, string> = {
baseUrl: '/api/kkd-configuration-service',
baseAdminUrl: '/api/admin',
baseUserUrl: '/api/admin/user',
baseSystemUrl: '/api/system',
baseConfigUrl: '/api/config',
// ======= ROLES ======
getAllRoles: '/role/all',
createRole: '/role/create',
updateRole: '/role/update',
deleteRole: '/role/delete',
// ======= AUTH ======
login: '/api/admin/auth/login',
logout: '/api/admin/auth/logout',
// ======= PROFILE ======
getProfile: '/api/admin/user/get_profile',
// ======= USERS ======
getUsers: '/get_users',
createUser: '/create_user',
updateUser: '/update_user',
blockUser: '/block_user',
deleteUser: '/delete_user',
getRoles: '/get_roles',
getAllPermissions: '/get_permissions',
// ======= SESSIONS ======
getAllSession: '/session/all',
revokeSession: '/session/revoke',
// ======= LOGS ======
getAllLogs: '/log/all',
getLogEvents: '/log/events',
setLogEvents: '/log/set_events',
// ======= APPLICATIONS ======
getSystemTree: '/application/get_system_tree',
// ======= ACCESS_LIST ======
getById: '/access_list/get_by_id',
setList: '/access_list/set_list',
setOne: '/access_list/set_one',
getAllRoutes: '/routing/get_routes'
}
+5
View File
@@ -0,0 +1,5 @@
type ValidationRulesKeys = 'required'
export const ValidationRules: Record<ValidationRulesKeys, any> = {
required: { value: true, message: 'Поле не может быть пустым' }
}
+6
View File
@@ -0,0 +1,6 @@
type LocalStorageKeys = 'HEADER_NAME' | 'USER_TOKEN'
export const localStorageKeys: Record<LocalStorageKeys, string> = {
HEADER_NAME: 'HEADER_NAME',
USER_TOKEN: 'USER_TOKEN'
}
+6
View File
@@ -0,0 +1,6 @@
type MessagesKey = 'serverError' | 'loginError'
export const messages: Record<MessagesKey, string> = {
serverError: 'Внутренняя ошибка сервиса',
loginError: 'Неверный логин или пароль'
}
+11
View File
@@ -0,0 +1,11 @@
export enum SessionStatusKeysType {
allowed = 'ALLOWED',
revoked = 'REVOKED',
expired = 'EXPIRED'
}
export const sessionStatuses: Record<SessionStatusKeysType, string> = {
[SessionStatusKeysType.allowed]: 'Активная',
[SessionStatusKeysType.revoked]: 'Отмененная',
[SessionStatusKeysType.expired]: 'Истекшая'
}
+18
View File
@@ -0,0 +1,18 @@
$basic-margin: 8px;
$basic-padding: 8px;
$text-size: 1rem;
$text-size-header1: 1.7rem;
$text-size-header2: 1.25rem;
$text-color-gray: var(--ant-primary-color);
$background-color: #F0F2F5;
$grey: #606060;
$border-color: #d9d9d9;
$error-red: #cf1322;
$border-color: #F0F0F0;
$blue-color: #40A9FF;
$blue-light: #E6F7FF;
$text-color-blue: #1890FF;
+5
View File
@@ -0,0 +1,5 @@
import { theme } from 'antd'
export const darkTheme = { algorithm: theme.darkAlgorithm }
export const lightTheme = { algorithm: theme.defaultAlgorithm }
+6
View File
@@ -0,0 +1,6 @@
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import { AppDispatch, RootState } from '../stores'
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
+35
View File
@@ -0,0 +1,35 @@
import { useAuth } from 'isp-ui-kit'
import { useNavigate } from 'react-router-dom'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { localStorageKeys } from '@constants/localStorageKeys.ts'
import { getConfigProperty } from '@utils/configUtils.ts'
import { LocalStorage } from '@utils/localStorageUtils.ts'
import { routePaths } from '@routes/routePaths.ts'
const useLogout = () => {
const { logout, isLoading } = useAuth()
const navigate = useNavigate()
const headerName = LocalStorage.get(localStorageKeys.HEADER_NAME)
const logoutUser = () =>
logout(apiPaths.logout, {
'X-APPLICATION-TOKEN': getConfigProperty(
'APP_TOKEN',
import.meta.env.VITE_APP_TOKEN
),
[headerName]: LocalStorage.get(localStorageKeys.USER_TOKEN)
})
.then(() => {
LocalStorage.remove(localStorageKeys.USER_TOKEN)
LocalStorage.remove(localStorageKeys.HEADER_NAME)
navigate(routePaths.login, { replace: true })
})
.catch(() => {})
return { isLoading, logoutUser }
}
export default useLogout
+19
View File
@@ -0,0 +1,19 @@
import { useMemo } from 'react'
import { PermissionKeysType } from '@type/roles.type.ts'
import { useAppSelector } from './redux.ts'
export const useRole = () => {
const { profile } = useAppSelector((state: any) => state.profileReducer)
const role: string = useMemo(() => profile && profile.role, [profile])
const hasPermission = (permission: PermissionKeysType) => {
const userPermission = profile.permissions || []
return userPermission.includes(permission)
}
return { role, hasPermission }
}
export default useRole
+23
View File
@@ -0,0 +1,23 @@
import { setupListeners } from '@reduxjs/toolkit/query'
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux'
import { BrowserRouter } from 'react-router-dom'
import App from './components/App.tsx'
import { setupStore } from './stores'
import 'react-resizable/css/styles.css'
import 'simplebar-react/dist/simplebar.min.css'
const store = setupStore()
setupListeners(store.dispatch)
const root = createRoot(document.getElementById('root') as HTMLElement)
root.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
)
@@ -0,0 +1,15 @@
@import "src/constants/style/styleConst";
.app-access-page {
display: flex;
height: 100%;
.ant-tree {
background: none;
}
&__content-wrap{
width: 100%;
overflow-x: scroll;
}
}
Whitespace-only changes.
+111
View File
@@ -0,0 +1,111 @@
import { Spin } from 'antd'
import { Layout } from 'isp-ui-kit'
import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type'
import { memo, useEffect } from 'react'
import {
createSearchParams,
Navigate,
useNavigate,
useParams,
useSearchParams
} from 'react-router-dom'
import ListItem from '@widgets/ListItem'
import AppAccessContent from '@components/AppAccessContent'
import { setSearchValue, setSelectedItemId } from '@utils/columnLayoutUtils.ts'
import { filterFirstColumnItems } from '@utils/firstColumnUtils.ts'
import useRole from '@hooks/useRole.tsx'
import appApi from '@services/appService.ts'
import { routePaths } from '@routes/routePaths.ts'
import { SystemTreeAppType } from '@type/app.type.ts'
import { PermissionKeysType } from '@type/roles.type.ts'
import './app-access-page.scss'
const { Column, EmptyData } = Layout
const firstColumnSearchParam = 'search'
const findMethodParam = 'method'
const AppAccessPage = () => {
const {
data = { originalResponse: [], appList: [] },
isLoading,
isError
} = appApi.useGetSystemTreeQuery()
const { appList } = data
const navigate = useNavigate()
const { hasPermission } = useRole()
const { id: selectedItemId = '' } = useParams()
const [searchParams, setSearchParams] = useSearchParams()
const searchValue = searchParams.get(firstColumnSearchParam) || ''
const canRead = hasPermission(PermissionKeysType.read)
useEffect(() => {
if (!canRead) {
navigate(routePaths.home)
}
}, [canRead])
const handleOnChangeSearchValue = (value: string): void => {
setSearchValue(value, setSearchParams)
}
const onSelectedItemId = (id: string): void => {
setSearchValue('', setSearchParams, findMethodParam)
setSelectedItemId(
routePaths.appAccess,
id,
createSearchParams(searchParams).toString(),
navigate
)
}
if (isLoading) {
return <Spin className="spin" />
}
if (isError) {
return <Navigate to={routePaths.error} />
}
return (
<section className="app-access-page">
<Column
showAddBtn={false}
showRemoveBtn={false}
items={filterFirstColumnItems(
appList as ColumnItem<SystemTreeAppType>,
searchValue
)}
renderItems={(item) => <ListItem item={item} />}
searchValue={searchValue}
selectedItemId={selectedItemId}
setSelectedItemId={onSelectedItemId}
onChangeSearchValue={handleOnChangeSearchValue}
/>
<div className="app-access-page__content-wrap">
{selectedItemId ? (
<AppAccessContent
paramPrefix={findMethodParam}
key={`content-${selectedItemId}`}
id={Number(selectedItemId)}
/>
) : (
<EmptyData />
)}
</div>
</section>
)
}
export default memo(AppAccessPage)
+13
View File
@@ -0,0 +1,13 @@
.home-page {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-image: url("/src/assets/images/home-background.png");
font-size: calc(1.5vw + 1.5vh);
font-family: 'Roboto',sans-serif;
font-style: normal;
font-weight: 400;
line-height: 56px;
}
+7
View File
@@ -0,0 +1,7 @@
import './home-page.scss'
const HomePage = () => {
return <div className="home-page">Добро пожаловать!</div>
}
export default HomePage
+120
View File
@@ -0,0 +1,120 @@
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Divider } from 'antd'
import { AxiosError } from 'axios'
import { FormComponents, useAuth } from 'isp-ui-kit'
import { useForm } from 'react-hook-form'
import { useNavigate } from 'react-router-dom'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { ValidationRules } from '@constants/form/validationRules.ts'
import { localStorageKeys } from '@constants/localStorageKeys.ts'
import { messages } from '@constants/messages.ts'
import { getConfigProperty } from '@utils/configUtils.ts'
import { LocalStorage } from '@utils/localStorageUtils.ts'
import { routePaths } from '@routes/routePaths.ts'
import { MSPError } from '@type/index.ts'
import { LoginRequest } from '@type/login.type.ts'
import './login-page.scss'
const passwordLoginEnabled = getConfigProperty('ENABLE_PASSWORD_LOGIN', true)
const LoginPage = () => {
const { login, isLoading } = useAuth()
const { handleSubmit, control, setError } = useForm<LoginRequest>({
mode: 'onChange'
})
const navigate = useNavigate()
const setFormError = (statusText: string, message: string): void => {
setError('email', {})
setError('password', {
message,
type: statusText
})
}
const handleError = (err: AxiosError<MSPError>): void => {
const { response } = err
if (response && response.status === 401) {
setFormError(response.statusText, messages.loginError)
} else {
setFormError('serverError', messages.serverError)
}
}
const handleSubmitForm = (data: LoginRequest): void => {
login(apiPaths.login, data, {
'X-APPLICATION-TOKEN': getConfigProperty(
'APP_TOKEN',
import.meta.env.VITE_APP_TOKEN
)
})
.then((response) => {
LocalStorage.set(localStorageKeys.HEADER_NAME, response.headerName)
LocalStorage.set(localStorageKeys.USER_TOKEN, response.token)
const redirectUrl =
localStorage.getItem('redirectUrl') || routePaths.home
navigate(redirectUrl, { replace: true })
localStorage.removeItem('redirectUrl')
})
.catch((err: any) => handleError(err))
}
const renderInternalAuthForm = () => {
if (!passwordLoginEnabled) {
return null
}
return (
<>
<FormComponents.FormInput
data-cy="email-input"
control={control}
name="email"
className="login-page__content__email-field"
prefix={<UserOutlined className="color" />}
placeholder="Логин"
rules={{ required: ValidationRules.required }}
/>
<FormComponents.FormInput
data-cy="password-input"
control={control}
name="password"
className="login-page__content__password-field"
prefix={<LockOutlined className="color" />}
type="password"
placeholder="Пароль"
rules={{ required: ValidationRules.required }}
/>
<Button
data-cy="submit-btn"
disabled={isLoading}
loading={isLoading}
type="primary"
className="login-page__content__submit-btn"
onClick={handleSubmit(handleSubmitForm)}
>
Войти
</Button>
</>
)
}
return (
<section className="login-page">
<form className="login-page__content">
<h1 data-cy="login-title" className="login-page__content__title">
Вход в систему
</h1>
<Divider />
{renderInternalAuthForm()}
</form>
</section>
)
}
export default LoginPage
+53
View File
@@ -0,0 +1,53 @@
@import "src/constants/style/styleConst";
.login-page {
height: 100vh;
background: $background-color;
display: flex;
.ant-input {
width: 300px;
text-align: center;
}
.ant-divider-horizontal {
margin-top: $basic-margin !important;
}
.ant-form-item-explain-error {
margin-bottom: $basic-margin;
}
.color {
color: $text-color-gray;
}
&__content {
max-width: 360px;
margin: auto;
display: flex;
flex-direction: column;
&__title {
text-align: center;
font-family: 'Roboto', sans-serif;
font-size: $text-size;
line-height: 20px;
color: $text-color-gray;
}
&__submit-sudir-btn {
background: #0000000f;
margin-top: 4 * $basic-margin;
&:hover {
background: rgba(0, 0, 0, 0.09) !important;
}
}
}
.requiredInput::after {
content: "";
}
}
+58
View File
@@ -0,0 +1,58 @@
import { Button, Descriptions } from 'antd'
import { useState } from 'react'
import PermissionList from '@widgets/PermissionList'
import ChangePasswordModal from '@components/ChangePasswordModal'
import RoleList from '@components/RoleList'
import { useAppSelector } from '@hooks/redux.ts'
import useLogout from '@hooks/useLogout.tsx'
import './profile-page.scss'
const ProfilePage = () => {
const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
const { profile } = useAppSelector((state) => state.profileReducer)
const { logoutUser, isLoading } = useLogout()
return (
<section className="profile-page wrap">
<ChangePasswordModal
onClose={() => setIsModalOpen(false)}
open={isModalOpen}
/>
<h1 className="profile-page__title">{`${profile.lastName} ${profile.firstName}`}</h1>
<div className="profile-page__user-info">
<div className="profile-page__user-info__email-wrapper">
<Descriptions>
<Descriptions.Item label="Email">{profile.email}</Descriptions.Item>
</Descriptions>
</div>
</div>
<RoleList userRoles={profile.roles} />
<PermissionList permissions={profile.permissions} />
<div className="profile-page__actions">
<Button
loading={isLoading}
disabled={isLoading}
className="profile-page__actions__exit-btn"
type="primary"
onClick={logoutUser}
>
Выход
</Button>
<Button
className="profile-page__actions__change-pass-btn"
type="primary"
onClick={() => setIsModalOpen(true)}
>
Сменить пароль
</Button>
</div>
</section>
)
}
export default ProfilePage
+24
View File
@@ -0,0 +1,24 @@
@import '../../constants/style/styleConst';
.profile-page {
display: flex;
flex-direction: column;
align-items: start;
&__title {
font-size: $text-size-header1;
}
&__user-info {
margin-top: $basic-padding;
span {
font-size: $text-size !important;
}
}
&__actions {
display: flex;
gap: $basic-margin
}
}
@@ -0,0 +1,17 @@
import { StateProfileStatus } from '@stores/redusers/ProfileSlice.ts'
export type ProfileDataType = {
email: string
firstName: string
lastName: string
role: string
roles: number[]
permissions: string[]
idleTimeoutMs: number
}
export type ProfileType = {
profile: ProfileDataType
status: StateProfileStatus
error: string
}
+189
View File
@@ -0,0 +1,189 @@
import { List, Spin, message } from 'antd'
import { Layout } from 'isp-ui-kit'
import { useEffect } from 'react'
import {
createSearchParams,
useLocation,
useNavigate,
useParams,
useSearchParams
} from 'react-router-dom'
import RolesContent from '@components/RolesContent'
import { filterFirstColumnItems } from '@utils/firstColumnUtils.ts'
import useRole from '@hooks/useRole.tsx'
import roleApi from '@services/roleService.ts'
import userServiceApi from '@services/userService.ts'
import { routePaths } from '@routes/routePaths.ts'
import { NewRoleType, PermissionKeysType, RoleType } from '@type/roles.type.ts'
import './roles-page.scss'
const { Column, EmptyData, NoData } = Layout
const RolesPage = () => {
const { id: selectedItemId = '' } = useParams()
const navigate = useNavigate()
const location = useLocation()
const fromApp = location.state?.fromApp || false
const { role, hasPermission } = useRole()
const [searchParams, setSearchParams] = useSearchParams()
const searchValue = searchParams.get('search') || ''
const { data: permissionList = [], isLoading: isPermissionLoading } =
userServiceApi.useGetAllPermissionsQuery()
const { data = [], isLoading: isRolesLoading } = roleApi.useGetAllRolesQuery()
const [createRole] = roleApi.useCreateRoleMutation()
const [updateRole] = roleApi.useUpdateRoleMutation()
const [removeRole] = roleApi.useRemoveRoleMutation()
const isPageAvailable = hasPermission(PermissionKeysType.read)
const isAddRolePermissions = hasPermission(PermissionKeysType.write)
const isRemoveRolePermissions = hasPermission(PermissionKeysType.write)
const isLoading = isPermissionLoading || isRolesLoading
const isNew = selectedItemId === 'new'
useEffect(() => {
if (!fromApp) {
navigate(routePaths.roles)
}
}, [fromApp])
useEffect(() => {
if (!isPageAvailable) {
navigate(routePaths.home)
}
}, [isPageAvailable])
useEffect(() => {
if (!role) {
navigate(routePaths.error)
}
}, [role])
const setSelectedItemId = (id: string): void => {
navigate(
{
pathname: `${routePaths.roles}/${id}`,
search: createSearchParams(searchParams).toString()
},
{ replace: true, state: { fromApp: true } }
)
}
const handleOnChangeSearchValue = (value: string): void => {
setSearchParams((prev) => {
if (!value) {
prev.delete('search')
} else {
prev.set('search', value)
}
return prev
})
}
const handeOnAddItem = () => setSelectedItemId('new')
const handleUpdateRole = (formValue: RoleType | NewRoleType) => {
updateRole(formValue as RoleType)
.unwrap()
.then(() => {
message.success('Элемент успешно добавлен').then()
})
.catch(() => message.error('Не удалось сохранить роль'))
}
const handleCreateRole = (formValue: NewRoleType) => {
createRole(formValue)
.unwrap()
.then((res) => {
message.success('Элемент успешно добавлен').then()
setSelectedItemId(res.id.toString())
})
.catch(() => {
message.error('Не удалось добавить роль').then()
setSelectedItemId('')
})
}
const handleRemoveRole = (id: any) => {
const idAsNumber = parseInt(id, 10)
removeRole(idAsNumber)
.unwrap()
.then(() => {
message.success('Элемент успешно удален').then()
setSelectedItemId('')
})
.catch(() => message.error('Не удалось удалить роль'))
}
if (isLoading) {
return <Spin />
}
const currentRole = data
? data.find((item) => item.id.toString() === selectedItemId)
: null
const renderItems = (item: RoleType) => (
<List.Item data-cy="role-item">
<div className="role-item">
<span className="role-item__name">{item.name}</span>
<span className="role-item__id">id: {item.id}</span>
</div>
</List.Item>
)
const renderMainContent = () => {
if (isNew) {
return (
<RolesContent
saveRole={handleCreateRole}
permissions={permissionList}
title="Добавить"
/>
)
}
if (!selectedItemId) {
return <EmptyData />
}
if (!currentRole) {
return <NoData />
}
return (
<RolesContent
immutable={currentRole.immutable}
saveRole={handleUpdateRole}
permissions={permissionList}
role={currentRole}
/>
)
}
return (
<section className="roles-page three-columns">
<Column
items={filterFirstColumnItems(data, searchValue)}
showAddBtn={isAddRolePermissions}
showRemoveBtn={isRemoveRolePermissions}
onAddItem={handeOnAddItem}
onRemoveItem={handleRemoveRole}
onChangeSearchValue={handleOnChangeSearchValue}
renderItems={renderItems}
searchValue={searchValue}
selectedItemId={selectedItemId}
setSelectedItemId={setSelectedItemId}
/>
<div className="roles-page__content">{renderMainContent()}</div>
</section>
)
}
export default RolesPage
+81
View File
@@ -0,0 +1,81 @@
@import "../../constants/style/styleConst";
.roles-page {
height: 100%;
.role-item {
&__id {
color: $grey;
}
}
&__content {
overflow-x: scroll;
width: 100%
}
}
.three-columns {
display: flex;
background: #fff;
box-shadow: inset -1px 0px 0px $border-color;
height: 100%;
.column__header {
padding: $basic-padding * 2 $basic-padding;
svg {
fill: $blue-color;
}
}
.ant-input-affix-wrapper {
.ant-input-prefix {
margin-left: auto;
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
z-index: 10;
cursor: pointer;
}
}
.ant-input-affix-wrapper-focused {
.ant-input-prefix {
.anticon-search {
svg {
display: none;
}
}
}
}
.ant-list-items {
.column__items__item {
.ant-list-item-meta-title {
font-family: 'Roboto', sans-serif;
font-size: 14px;
line-height: 22px;
font-weight: 400;
color: $text-color-gray;
margin-left: 5px;
}
&.active {
background: $blue-light !important;
.ant-list-item-meta-title {
color: $text-color-blue;
}
svg {
path {
fill: $text-color-blue;
}
}
}
}
}
}
+126
View File
@@ -0,0 +1,126 @@
import { Pagination, Spin, Table } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { getUserFullName } from '@utils/userUtils/getFullNameUtil'
import useRole from '@hooks/useRole'
import securityLogServiceApi from '@services/securityLogService'
import userServiceApi from '@services/userService'
import { routePaths } from '@routes/routePaths.ts'
import { LogType } from '@type/log.type'
import { PermissionKeysType } from '@type/roles.type'
import './security-log-page.scss'
const limit = 10
const SecurityLogPage = () => {
const [getAllLogs, { data, isLoading: isLoadingLogs }] =
securityLogServiceApi.useGetAllLogsMutation()
const { data: allUsers = [], isLoading: isUsersLoading } =
userServiceApi.useGetAllUsersQuery()
const { role, hasPermission } = useRole()
const navigate = useNavigate()
const [currentPage, setCurrentPage] = useState(1)
const isLoading = isUsersLoading || isLoadingLogs
const isPageAvailable = hasPermission(PermissionKeysType.read)
useEffect(() => {
getAllLogs({ limit, offset: 0 })
}, [])
useEffect(() => {
if (!isPageAvailable) {
navigate(routePaths.home)
}
}, [isPageAvailable])
useEffect(() => {
if (!role) {
navigate(routePaths.error)
}
}, [role])
const handleChangePagination = (page: number) => {
setCurrentPage(page)
getAllLogs({ limit, offset: (page - 1) * limit })
}
if (isLoading || !data) {
return <Spin />
}
const columns: ColumnsType<LogType> = [
{
title: 'Пользователь',
dataIndex: 'userId',
key: 'userId',
render: (value) => {
const user = allUsers.find((el) => el.id === value)
if (user) {
return getUserFullName(user)
}
}
},
{
title: 'Время события',
dataIndex: 'createdAt',
key: 'createdAt',
render: (value) => {
const date = new Date(value)
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
}
},
{
title: 'Действие',
dataIndex: 'message',
key: 'message',
render: (value: string) =>
value.split('\n').map((line) => <p key={line}>{line}</p>)
}
]
const { totalCount, items } = data
return (
<section className="security-log-page">
<header className="security-log-page__header">
<span
data-cy="security-log-page__header__title"
className="security-log-page__header__title"
>
Просмотр журналов ИБ
</span>
</header>
<section className="security-log-page__content">
<div className="security-log-page__content__wrap-table">
<Table
rowKey={(record) => record.id}
pagination={false}
dataSource={items}
columns={columns}
/>
</div>
<div className="security-log-page__content__pagination">
<Pagination
showSizeChanger={false}
current={currentPage}
total={totalCount}
pageSize={limit}
onChange={handleChangePagination}
/>
</div>
</section>
</section>
)
}
export default SecurityLogPage
@@ -0,0 +1,36 @@
@import "src/constants/style/styleConst";
.security-log-page {
height: 100%;
background: #fff;
border: 1px solid $border-color;
&__header {
border-bottom: 1px solid $border-color;
padding: 0 3 * $basic-padding;
&__title {
padding: 3 * $basic-padding 0;
display: inline-block;
font-weight: 500;
font-size: 20px;
line-height: 28px;
}
}
&__content {
padding: 2 * $basic-padding 3 * $basic-padding;
&__wrap-table {
overflow-x: scroll;
height: calc(100vh - 200px);
}
&__pagination {
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
}
}
+172
View File
@@ -0,0 +1,172 @@
import { LogoutOutlined } from '@ant-design/icons'
import { Button, Popconfirm, Spin, Table, message, Pagination } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { SessionStatusKeysType, sessionStatuses } from '@constants/statuses'
import { getUserFullName } from '@utils/userUtils/getFullNameUtil'
import useRole from '@hooks/useRole'
import sessionServiceApi from '@services/sessionService'
import userServiceApi from '@services/userService'
import { routePaths } from '@routes/routePaths.ts'
import { PermissionKeysType } from '@type/roles.type.ts'
import { SessionType } from '@type/session.type'
import './sessions-page.scss'
const limit = 10
const SessionsPage = () => {
const [offset, setOffset] = useState<number>(0)
const { data, isLoading: isLoadingSession } =
sessionServiceApi.useGetAllSessionsQuery({ limit, offset })
const [revokeSession] = sessionServiceApi.useRevokeSessionMutation()
const { data: allUsers = [], isLoading: isUsersLoading } =
userServiceApi.useGetAllUsersQuery()
const { role, hasPermission } = useRole()
const navigate = useNavigate()
const [currentPage, setCurrentPage] = useState(1)
const isLoading = isUsersLoading || isLoadingSession
const isPageAvailable = hasPermission(PermissionKeysType.read)
const hasRevokePermission = hasPermission(PermissionKeysType.write)
useEffect(() => {
if (!isPageAvailable) {
navigate(routePaths.home)
}
}, [isPageAvailable])
useEffect(() => {
if (!role) {
navigate(routePaths.error)
}
}, [role])
const handleChangePagination = (page: number) => {
setCurrentPage(page)
const currentOffset = (page - 1) * limit
setOffset(currentOffset)
}
const handleRevokeSessions = (id: number) => {
revokeSession(id)
.unwrap()
.then(() => message.success('Сессия успешно завершена'))
.catch(() => message.info('Не удалось завершить сессию'))
}
if (isLoading || !data) {
return <Spin />
}
const columns: ColumnsType<SessionType> = [
{
title: 'Пользователь',
dataIndex: 'userId',
key: 'userId',
render: (value) => {
const user = allUsers.find((el) => el.id === value)
return user && getUserFullName(user)
}
},
{
title: 'Идентификатор',
dataIndex: 'id',
key: 'id'
},
{
title: 'Дата начала сессии',
dataIndex: 'createdAt',
key: 'createdAt',
render: (value) => {
const date = new Date(value)
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
}
},
{
title: 'Дата окончания сессии',
dataIndex: 'expiredAt',
key: 'expiredAt',
render: (value) => {
const date = new Date(value)
return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
}
},
{
title: 'Статус',
dataIndex: 'status',
key: 'status',
render: (value: SessionStatusKeysType) => sessionStatuses[value]
},
{
dataIndex: 'actions',
key: 'actions',
render: (_, record) => {
if (record.status !== SessionStatusKeysType.allowed) {
return null
}
return (
<>
{hasRevokePermission && (
<Popconfirm
title="Закончить эту сессию?"
onConfirm={() => handleRevokeSessions(record.id)}
>
<Button
data-cy="sessions-page__content__table__logout-btn"
type="primary"
className="sessions-page__content__table__logout-btn"
icon={<LogoutOutlined />}
/>
</Popconfirm>
)}
</>
)
}
}
]
const { totalCount, items } = data
return (
<section className="sessions-page">
<header className="sessions-page__header">
<span
data-cy="sessions-page__header__title"
className="sessions-page__header__title"
>
Пользовательские сессии
</span>
</header>
<section className="sessions-page__content">
<div className="sessions-page__content__wrap-table">
<Table
className="sessions-page__content__table"
rowKey={(record) => record.id}
pagination={false}
dataSource={items}
columns={columns}
/>
</div>
<div className="sessions-page__content__pagination">
<Pagination
showSizeChanger={false}
current={currentPage}
total={totalCount}
pageSize={limit}
onChange={handleChangePagination}
/>
</div>
</section>
</section>
)
}
export default SessionsPage
+42
View File
@@ -0,0 +1,42 @@
@import "src/constants/style/styleConst";
.sessions-page {
height: 100%;
background: #fff;
border: 1px solid $border-color;
&__header {
border-bottom: 1px solid $border-color;
padding: 0 3 * $basic-padding;
&__title {
padding: 3 * $basic-padding 0;
display: inline-block;
font-weight: 500;
font-size: 20px;
line-height: 28px;
}
}
&__content {
padding: 2 * $basic-padding 3 * $basic-padding;
&__wrap-table {
overflow-x: scroll;
height: calc(100vh - 200px);
}
&__table {
&__logout-btn {
color: $blue-color;
background: $blue-light;
}
}
&__pagination {
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
}
}
+230
View File
@@ -0,0 +1,230 @@
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons'
import { Button, message, Spin } from 'antd'
import { FormComponents } from 'isp-ui-kit'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { useLocation, useNavigate } from 'react-router-dom'
import { ValidationRules } from '@constants/form/validationRules.ts'
import { findExclusiveRole } from '@utils/roleUtils.ts'
import useRole from '@hooks/useRole.tsx'
import roleApi from '@services/roleService.ts'
import userServiceApi from '@services/userService.ts'
import { routePaths } from '@routes/routePaths.ts'
import { PermissionKeysType, RoleType } from '@type/roles.type.ts'
import { UserType } from '@type/user.type.ts'
import { LabelItem } from 'isp-ui-kit/dist/FormComponents/formTypes'
import './user-editor.scss'
const UserEditor = () => {
const location = useLocation()
const navigate = useNavigate()
const state = location.state as UserType
const isNew = location.pathname.includes('new')
const fromApp = location.state?.fromApp || false
const { hasPermission } = useRole()
const hasCreateUserPermission = hasPermission(PermissionKeysType.write)
const hasUpdateUserPermission = hasPermission(PermissionKeysType.write)
const [createUser] = userServiceApi.useCreateUserMutation()
const { data: roles = [], isLoading } = roleApi.useGetAllRolesQuery()
const [updateUser] = userServiceApi.useUpdateUserMutation()
const isSaveBtnAvailable = isNew
? hasCreateUserPermission
: hasUpdateUserPermission
const {
control,
formState: { isDirty },
getValues,
setValue,
watch,
reset
} = useForm<UserType>({
defaultValues: isNew
? {
description: '',
email: '',
firstName: '',
password: '',
roles: []
}
: state,
mode: 'onChange'
})
useEffect(() => {
if (isNew && !fromApp) {
navigate(routePaths.users)
}
}, [fromApp])
useEffect(() => {
const subscription = watch((value, { name, type }) => {
if (name === 'roles' && type === 'change') {
const exclusiveRole = findExclusiveRole(roles, value.roles as number[])
if (exclusiveRole) {
if (value.roles && value.roles.length > 1) {
message.info(
<>
Роль: <strong>{exclusiveRole.name}</strong> несовместима с
другими ролями
</>
)
}
setValue('roles', [exclusiveRole.id])
}
}
})
return () => subscription.unsubscribe()
}, [watch])
const sendForm = () => {
if (isNew) {
const newUser = {
email: getValues().email,
password: getValues().password,
description: getValues().description,
firstName: getValues().firstName,
lastName: getValues().lastName,
roles: getValues().roles
}
createUser(newUser)
.unwrap()
.then(() => {
message.success('Пользователь успешно создан')
navigate(routePaths.users)
})
.catch(() => {
message.error('Произошла ошибка создания пользователя')
})
} else {
const formData = getValues()
delete formData.lastSessionCreatedAt
updateUser(formData)
.unwrap()
.then(() => {
message.success('Пользователь успешно изменен')
reset({}, { keepValues: true })
})
.catch(() => {
message.error('Произошла ошибка обновления пользователя')
})
}
}
const createSelectOptions = (role: RoleType[]) => {
const options: LabelItem[] = role.map((r) => ({
value: r.id,
label: r.name
}))
return options
}
if (isLoading) {
return <Spin />
}
return (
<section className="user-editor">
<header className="user-editor__header">
<div className="user-editor__header__nav">
<Button
data-cy="user-editor__header__nav__backBtn"
className="user-editor__header__nav__backBtn"
type="text"
onClick={() => navigate(routePaths.users)}
icon={<ArrowLeftOutlined />}
/>
<h2 className="user-editor__header__name">
{isNew ? 'Новый пользователь' : `${state.firstName}`}
</h2>
<Button
disabled={!isDirty || !isSaveBtnAvailable}
data-cy="user-editor__header__btn"
className="user-editor__header__btn"
onClick={() => sendForm()}
type="primary"
icon={<SaveOutlined />}
>
Сохранить
</Button>
</div>
{isNew ? (
''
) : (
<span data-cy="user-editor__status" className="user-editor__status">
{state.lastSessionCreatedAt && (
<>
Последняя сессия &nbsp;
{new Date(state.lastSessionCreatedAt).toLocaleDateString()}
&nbsp;
{new Date(state.lastSessionCreatedAt).toLocaleTimeString()}
</>
)}
</span>
)}
</header>
<form className="user-editor__content">
<div className="user-editor__content__wrap">
<div className="user-editor__content__name">
<FormComponents.FormInput
label="Пользователь"
rules={{ required: ValidationRules.required }}
control={control}
name="firstName"
/>
</div>
<div className="user-editor__content__description">
<FormComponents.FormInput
label="Описание"
control={control}
name="description"
/>
</div>
<div className="user-editor__content__email">
<FormComponents.FormInput
label="Email"
rules={{ required: ValidationRules.required }}
control={control}
name="email"
/>
</div>
{isNew && (
<div className="user-editor__content__password">
<FormComponents.FormInputPassword
label="Пароль"
rules={{ required: ValidationRules.required }}
control={control}
name="password"
/>
</div>
)}
<div className="user-editor__content__roles">
<FormComponents.FormSelect
label="Добавить роль"
optionFilterProp="label"
disabled={!hasPermission(PermissionKeysType.write)}
control={control}
name="roles"
options={createSelectOptions(roles)}
/>
</div>
</div>
</form>
</section>
)
}
export default UserEditor
+66
View File
@@ -0,0 +1,66 @@
@import "../../constants/style/styleConst";
.user-editor {
background: #fff;
height: 100%;
border: 1px solid $border-color;
&__header {
border-bottom: 1px solid $border-color;
padding: $basic-padding *4 $basic-padding*3;
&__nav {
display: flex;
align-items: center;
margin-bottom: $basic-margin* 2.5;
&__backBtn {
margin-left: -$basic-margin;
margin-right: $basic-margin;
}
}
&__name {
font-family: 'Roboto', sans-serif;
font-style: normal;
font-weight: 500;
font-size: 20px;
line-height: 28px;
color: #000;
}
&__btn {
margin-left: auto;
}
}
&__status {
font-family: 'Roboto', sans-serif;
font-size: 16px;
line-height: 24px;
}
&__content {
&__wrap {
overflow-x: scroll;
height: calc(100vh - 200px);
}
.ant-form-item {
margin: 0;
}
&__name, &__description, &__email, &__roles, &__password {
padding: $basic-padding*1.5 $basic-padding*3;
h3 {
padding-bottom: $basic-padding*1;
font-family: 'Roboto', sans-serif;
font-weight: 400;
font-size: 14px;
line-height: 22px
}
}
}
}
+222
View File
@@ -0,0 +1,222 @@
import {
DeleteOutlined,
EditTwoTone,
LockOutlined,
UnlockOutlined,
PlusSquareOutlined
} from '@ant-design/icons'
import { Button, Popconfirm, Spin, Table, message } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getUserFullName } from '@utils/userUtils/getFullNameUtil.ts'
import useRole from '@hooks/useRole.tsx'
import roleApi from '@services/roleService.ts'
import userServiceApi from '@services/userService.ts'
import { routePaths } from '@routes/routePaths.ts'
import { PermissionKeysType } from '@type/roles.type.ts'
import { UserType } from '@type/user.type.ts'
import './users-page.scss'
const UsersPage = () => {
const { data: allUsers = [], isLoading: isUsersLoading } =
userServiceApi.useGetAllUsersQuery()
const { data: roles, isLoading: isRolesLoading } =
roleApi.useGetAllRolesQuery()
const [blockUser] = userServiceApi.useBlockUserMutation()
const [deleteUser] = userServiceApi.useDeleteUserMutation()
const { role, hasPermission } = useRole()
const navigate = useNavigate()
const isLoading = isRolesLoading || isUsersLoading
const isPageAvailable = hasPermission(PermissionKeysType.read)
const hasBlockUserPermission = hasPermission(PermissionKeysType.write)
const hasDeleteUserPermission = hasPermission(PermissionKeysType.write)
const hasUpdateUserPermission = hasPermission(PermissionKeysType.write)
const hasCreateUserPermission = hasPermission(PermissionKeysType.write)
useEffect(() => {
if (!isPageAvailable) {
navigate(routePaths.home)
}
}, [isPageAvailable])
useEffect(() => {
if (!role) {
navigate(routePaths.error)
}
}, [role])
const handleDeleteUser = (userId: number) => {
deleteUser(userId)
.unwrap()
.then(() => message.success('Пользователь успешно удален'))
.catch(() => message.error('Не удалось удалить пользователя'))
}
const handleBlockUser = (userId: number) => {
const currentUser = allUsers.find((el) => el.id === userId)
const successMessage = currentUser?.blocked
? `Пользователь ${currentUser.lastName} ${currentUser.firstName} успешно разблокирован`
: `Пользователь ${currentUser?.lastName} ${currentUser?.firstName} успешно заблокирован`
const errorMessage = currentUser?.blocked
? `Не удалось разблокировать пользователя ${currentUser.lastName} ${currentUser.firstName}`
: `Не удалось заблокировать пользователя ${currentUser?.lastName} ${currentUser?.firstName}`
blockUser(userId)
.unwrap()
.then(() => message.success(successMessage))
.catch(() => message.error(<>{errorMessage}</>))
}
if (isLoading) {
return <Spin />
}
const columns: ColumnsType<UserType> = [
{
title: 'id',
dataIndex: 'id',
key: 'id'
},
{
title: 'Пользователь',
dataIndex: 'name',
key: 'name',
render: (_, record) => getUserFullName(record)
},
{
title: 'Описание',
dataIndex: 'description',
key: 'description'
},
{
title: 'Email',
dataIndex: 'email',
key: 'email'
},
{
title: 'Роль',
dataIndex: 'roles',
key: 'roles',
render: (values: number[]) => {
const labels: any[] = []
values.forEach((value: number) => {
const roleLabel = roles?.find((el) => el.id === value)
if (roleLabel) {
labels.push(roleLabel.name)
}
})
return labels.map((label) => (
<div key={label} className="role-item">
{label}
</div>
))
}
},
{
title: 'Последняя сессия',
dataIndex: 'lastSessionCreatedAt',
key: 'lastSessionCreatedAt',
render: (value: string) =>
value ? new Date(value).toLocaleDateString() : ''
},
{
dataIndex: 'actions',
key: 'actions',
render: (_, record) => {
const blockTitle = record.blocked
? 'Вы действительно хотите разблокировать этого пользователя?'
: 'Вы действительно хотите заблокировать этого пользователя?'
return (
<div className="users-page__content__table__actions">
{hasBlockUserPermission && (
<Popconfirm
title={blockTitle}
onConfirm={() => handleBlockUser(record.id)}
>
<Button
data-cy={`users-page__content__table__actions__lock-btn ${record.id}`}
className="users-page__content__table__actions__lock-btn"
type="primary"
danger={record.blocked}
icon={record.blocked ? <LockOutlined /> : <UnlockOutlined />}
/>
</Popconfirm>
)}
{hasUpdateUserPermission && (
<div
data-cy={`users-page__content__table__actions__edit-btn ${record.id}`}
className="users-page__content__table__actions__edit-btn"
onClick={() => {
navigate(`${routePaths.users}/${record.id}`, {
state: { ...record }
})
}}
>
<EditTwoTone />
</div>
)}
{hasDeleteUserPermission && (
<Popconfirm
title="Вы действительно хотите удалить этого пользователя?"
onConfirm={() => handleDeleteUser(record.id)}
>
<Button
data-cy={`users-page__content__table__actions__delete-btn ${record.id}`}
className="users-page__content__table__actions__delete-btn"
type="primary"
icon={<DeleteOutlined />}
/>
</Popconfirm>
)}
</div>
)
}
}
]
return (
<section className="users-page">
<header className="users-page__header">
<span
data-cy="users-page__header__title"
className="users-page__header__title"
>
Пользователи
</span>
<Button
disabled={!hasCreateUserPermission}
onClick={() =>
navigate(`${routePaths.users}/new`, { state: { fromApp: true } })
}
data-cy="users-page__header__addButton"
type="primary"
icon={<PlusSquareOutlined />}
>
Добавить
</Button>
</header>
<section className="users-page__content">
<div className="users-page__content__wrap-table">
<Table
data-cy="users-page__content__table"
rowKey={(record) => record.id}
pagination={false}
dataSource={allUsers}
columns={columns}
/>
</div>
</section>
</section>
)
}
export default UsersPage
+70
View File
@@ -0,0 +1,70 @@
@import "src/constants/style/styleConst";
.users-page {
height: 100%;
background: #fff;
border: 1px solid $border-color;
&__header {
border-bottom: 1px solid $border-color;
padding: 0 3 * $basic-padding;
display: flex;
justify-content: space-between;
align-items: center;
&__title {
padding: 3 * $basic-padding 0;
display: inline-block;
font-weight: 500;
font-size: 20px;
line-height: 28px;
}
}
&__content {
padding: 2 * $basic-padding 3 * $basic-padding;
overflow-x: scroll;
&__wrap-table {
overflow-x: scroll;
height: calc(100vh - 200px);
}
&__table {
&__actions {
justify-content: flex-end;
display: flex;
gap: $basic-margin;
&__delete-btn {
color: $blue-color;
background: $blue-light;
}
&__edit-btn {
cursor: pointer;
background: $blue-light;
padding: 4px 10px;
border-radius: 8px;
&:hover {
path:first-child {
fill: $blue-color;
}
path:last-child {
fill: #fff;
}
background: $blue-color;
}
}
}
}
&__pagination {
margin-top: 20px;
}
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { localStorageKeys } from '@constants/localStorageKeys.ts'
import { LocalStorage } from '@utils/localStorageUtils.ts'
import { routePaths } from '@routes/routePaths.ts'
const PrivateRoute = () => {
const location = useLocation()
const userToken = LocalStorage.get(localStorageKeys.USER_TOKEN)
if (!userToken) {
LocalStorage.set('redirectUrl', location.pathname)
return <Navigate to={routePaths.login} replace />
}
return <Outlet />
}
export default PrivateRoute
+131
View File
@@ -0,0 +1,131 @@
import { Spin } from 'antd'
import { lazy, Suspense } from 'react'
import { Route, Routes } from 'react-router-dom'
import Layout from '@components/Layout'
import HomePage from '@pages/HomePage'
import PrivateRoute from '@routes/PrivateRoute'
import { routePaths } from '@routes/routePaths.ts'
const LoginPage = lazy(() => import('@pages/LoginPage'))
const ErrorPage = lazy(() => import('@components/ErrorPage'))
const ProfilePage = lazy(() => import('@pages/ProfilePage'))
const UsersPage = lazy(() => import('@pages/UsersPage'))
const RolesPage = lazy(() => import('@pages/RolesPage'))
const UserEditor = lazy(() => import('src/pages/UserEditor'))
const SessionsPage = lazy(() => import('@pages/SessionsPage'))
const SecurityLogPage = lazy(() => import('@pages/SecurityLogPage'))
const AppAccessPage = lazy(() => import('@pages/AppAccessPage'))
const Routers = () => {
return (
<Routes>
<Route element={<PrivateRoute />}>
<Route path={routePaths.home} element={<Layout />}>
<Route
index
element={
<Suspense fallback={<Spin />}>
<HomePage />
</Suspense>
}
/>
<Route
path={`${routePaths.profile}`}
element={
<Suspense fallback={<Spin />}>
<ProfilePage />
</Suspense>
}
/>
<Route
path={routePaths.users}
element={
<Suspense fallback={<Spin />}>
<UsersPage />
</Suspense>
}
/>
<Route
path={`${routePaths.users}/:id`}
element={
<Suspense fallback={<Spin />}>
<UserEditor />
</Suspense>
}
/>
<Route
path={routePaths.roles}
element={
<Suspense fallback={<Spin />}>
<RolesPage />
</Suspense>
}
>
<Route
path=":id"
element={
<Suspense fallback={<Spin />}>
<RolesPage />
</Suspense>
}
/>
</Route>
<Route
path={routePaths.sessions}
element={
<Suspense fallback={<Spin />}>
<SessionsPage />
</Suspense>
}
/>
<Route
path={routePaths.securityLog}
element={
<Suspense fallback={<Spin />}>
<SecurityLogPage />
</Suspense>
}
/>
<Route
path={`${routePaths.appAccess}`}
element={
<Suspense fallback={<Spin />}>
<AppAccessPage />
</Suspense>
}
>
<Route
path=":id"
element={
<Suspense fallback={<Spin />}>
<AppAccessPage />
</Suspense>
}
/>
</Route>
</Route>
</Route>
<Route
path={routePaths.error}
element={
<Suspense fallback={<Spin />}>
<ErrorPage />
</Suspense>
}
/>
<Route
path={routePaths.login}
element={
<Suspense fallback={<Spin />}>
<LoginPage />
</Suspense>
}
/>
</Routes>
)
}
export default Routers
+24
View File
@@ -0,0 +1,24 @@
type RoutePaths =
| 'home'
| 'notFound'
| 'error'
| 'login'
| 'profile'
| 'users'
| 'sessions'
| 'securityLog'
| 'roles'
| 'appAccess'
export const routePaths: Record<RoutePaths, string> = {
home: '/',
error: '/error',
notFound: '*',
login: '/login',
profile: '/profile',
users: '/users',
sessions: '/sessions',
securityLog: '/securityLog',
roles: '/roles',
appAccess: '/appAccess'
}
+35
View File
@@ -0,0 +1,35 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { axiosBaseQuery } from '@utils/apiUtils.ts'
import {
AccessListMethodType,
AccessListSetListRequestType,
AccessListSetListSetOneRequestType
} from '@type/accessList.type.ts'
const accessListApi = createApi({
reducerPath: 'accessListApi',
refetchOnFocus: true,
tagTypes: ['AccessItems'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }),
endpoints: (builder) => ({
getById: builder.query<AccessListMethodType[], { id: number }>({
query: ({ id }) => ({ url: apiPaths.getById, data: { id } }),
providesTags: () => ['AccessItems']
}),
setList: builder.mutation<AccessListMethodType[], AccessListSetListRequestType>({
query: (data) => ({ url: apiPaths.setList, data }),
invalidatesTags: () => ['AccessItems']
}),
setOne: builder.mutation<void, AccessListSetListSetOneRequestType>({
query: (data) => ({ url: apiPaths.setOne, data }),
invalidatesTags: () => ['AccessItems']
})
})
})
export default accessListApi
+52
View File
@@ -0,0 +1,52 @@
import { message } from 'antd'
import axios, { AxiosError } from 'axios'
import { localStorageKeys } from '@constants/localStorageKeys.ts'
import { getConfigProperty } from '@utils/configUtils.ts'
import { LocalStorage } from '@utils/localStorageUtils.ts'
import { routePaths } from '@routes/routePaths.ts'
import { MSPError } from '@type/index.ts'
export const apiService = axios.create({
timeout: 15000,
data: {}
})
apiService.defaults.headers.post['X-APPLICATION-TOKEN'] = getConfigProperty(
'APP_TOKEN',
import.meta.env.VITE_APP_TOKEN
)
apiService.interceptors.request.use(
async (config: any) => {
const headerName = LocalStorage.get(localStorageKeys.HEADER_NAME)
config.headers[headerName] = LocalStorage.get(localStorageKeys.USER_TOKEN)
return config
},
(error: AxiosError<MSPError>) => Promise.reject(error)
)
apiService.interceptors.response.use(
async (response: any) => response,
(error: AxiosError<MSPError>) => {
console.error(error)
if (error.response && error.response.status === 401) {
LocalStorage.clear()
message.error('Ваша сессия истекла"').then()
LocalStorage.set('redirectUrl', location.pathname)
window.location.href = routePaths.login
}
if (error.response && error.response.status >= 500) {
message
.error('Внутренняя ошибка сервиса, попробуйте повторить запрос')
.then()
}
return Promise.reject(error)
}
)
+33
View File
@@ -0,0 +1,33 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { axiosBaseQuery } from '@utils/apiUtils.ts'
import { AppApiResponseType, DomainType } from '@type/app.type.ts'
const appApi = createApi({
reducerPath: 'appService',
refetchOnFocus: true,
tagTypes: ['SystemTreeApps'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseSystemUrl }),
endpoints: (builder) => ({
getSystemTree: builder.query<AppApiResponseType, void>({
query: () => ({ url: apiPaths.getSystemTree }),
transformResponse: (response: DomainType[]) => {
const apps = response.flatMap(({ services }) =>
services.flatMap(({ apps }) => apps)
)
return {
originalResponse: response,
appList: apps
}
},
providesTags: () => ['SystemTreeApps']
})
})
})
export default appApi
+43
View File
@@ -0,0 +1,43 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { axiosBaseQuery } from '@utils/apiUtils.ts'
import { NewRoleType, RoleType } from '@type/roles.type.ts'
const roleApi = createApi({
reducerPath: 'roleApi',
refetchOnFocus: true,
tagTypes: ['Roles'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseAdminUrl }),
endpoints: (builder) => ({
getAllRoles: builder.query<RoleType[], void>({
query: () => ({ url: apiPaths.getAllRoles }),
providesTags: () => ['Roles']
}),
createRole: builder.mutation<RoleType, NewRoleType>({
query: (newRole) => ({
url: apiPaths.createRole,
data: newRole
}),
invalidatesTags: ['Roles']
}),
updateRole: builder.mutation<void, RoleType>({
query: (role) => ({
url: apiPaths.updateRole,
data: role
}),
invalidatesTags: ['Roles']
}),
removeRole: builder.mutation<void, number>({
query: (id) => ({
url: apiPaths.deleteRole,
data: { id }
}),
invalidatesTags: ['Roles']
})
})
})
export default roleApi
+50
View File
@@ -0,0 +1,50 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { axiosBaseQuery } from '@utils/apiUtils.ts'
import {
EndpointType,
RouteApiResponseType,
RouteType
} from '@type/accessList.type.ts'
const routeApi = createApi({
reducerPath: 'routeApi',
refetchOnFocus: true,
tagTypes: ['Routes'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseConfigUrl }),
endpoints: (builder) => ({
getAllRoutes: builder.query<RouteApiResponseType, void>({
query: () => ({ url: apiPaths.getAllRoutes }),
transformResponse: (response: RouteType[]) => {
const moduleEndpoints: Record<string, EndpointType[]> = {}
const allRouteMap: Record<string, EndpointType> = {}
response.forEach((route) => {
if (route.endpoints && route.endpoints.length) {
moduleEndpoints[route.moduleName] = route.endpoints
}
})
Object.keys(moduleEndpoints)
.sort()
.forEach((groupName) => {
moduleEndpoints[groupName].forEach((method) => {
allRouteMap[method.path] = method
})
})
return {
originalResponse: response,
moduleEndpoints: moduleEndpoints,
allRouteMap: allRouteMap
}
},
providesTags: () => ['Routes']
})
})
})
export default routeApi
+31
View File
@@ -0,0 +1,31 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths'
import { axiosBaseQuery } from '@utils/apiUtils'
import { LimitOffsetRequestType } from '@type/index.ts'
import { LogEventType, LogResponseType, SetEventType } from '@type/log.type'
const securityLogServiceApi = createApi({
reducerPath: 'securityLogService',
refetchOnFocus: true,
tagTypes: ['logs', 'events'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseAdminUrl }),
endpoints: (builder) => ({
getAllLogs: builder.mutation<LogResponseType, LimitOffsetRequestType>({
query: (request) => ({ url: apiPaths.getAllLogs, data: request }),
invalidatesTags: () => ['logs']
}),
getLogEvents: builder.query<LogEventType[], void>({
query: () => ({ url: apiPaths.getLogEvents }),
providesTags: () => ['events']
}),
setLogEvents: builder.mutation<void, SetEventType[]>({
query: (request) => ({ url: apiPaths.setLogEvents, data: request }),
invalidatesTags: () => ['events']
})
})
})
export default securityLogServiceApi
+27
View File
@@ -0,0 +1,27 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths'
import { axiosBaseQuery } from '@utils/apiUtils'
import { LimitOffsetRequestType } from '@type/index.ts'
import { SessionResponseType } from '@type/session.type'
const sessionServiceApi = createApi({
reducerPath: 'sessionService',
refetchOnFocus: true,
tagTypes: ['sessions'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseAdminUrl }),
endpoints: (builder) => ({
getAllSessions: builder.query<SessionResponseType, LimitOffsetRequestType>({
query: (request) => ({ url: apiPaths.getAllSession, data: request }),
providesTags: () => ['sessions']
}),
revokeSession: builder.mutation<void, number>({
query: (id) => ({ url: apiPaths.revokeSession, data: { id } }),
invalidatesTags: () => ['sessions']
})
})
})
export default sessionServiceApi
+54
View File
@@ -0,0 +1,54 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { axiosBaseQuery } from '@utils/apiUtils.ts'
import { PermissionType } from '@type/roles.type.ts'
import { NewUserType, UserResponseType, UserType } from '@type/user.type.ts'
const userServiceApi = createApi({
reducerPath: 'userServiceApi',
refetchOnFocus: true,
tagTypes: ['users', 'permissions'],
baseQuery: axiosBaseQuery({ baseUrl: apiPaths.baseUserUrl }),
endpoints: (builder) => ({
getAllUsers: builder.query<UserType[], void>({
query: () => ({ url: apiPaths.getUsers, data: { limit: 1000 } }),
transformResponse: (response: UserResponseType) => response.items,
providesTags: () => ['users']
}),
getAllPermissions: builder.query<PermissionType[], void>({
query: () => ({ url: apiPaths.getAllPermissions, data: {} }),
providesTags: () => ['permissions']
}),
blockUser: builder.mutation<void, number>({
query: (userId) => ({ url: apiPaths.blockUser, data: { userId } }),
invalidatesTags: () => ['users']
}),
deleteUser: builder.mutation<void, number>({
query: (userId) => ({
url: apiPaths.deleteUser,
data: { ids: [userId] }
}),
invalidatesTags: () => ['users']
}),
createUser: builder.mutation<UserType, NewUserType>({
query: (newUser) => ({
url: apiPaths.createUser,
data: newUser
}),
invalidatesTags: ['users']
}),
updateUser: builder.mutation<void, Omit<UserType, 'lastSessionCreatedAt'>>({
query: (user) => ({
url: apiPaths.updateUser,
data: user
}),
invalidatesTags: ['users']
})
})
})
export default userServiceApi
+55
View File
@@ -0,0 +1,55 @@
import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { theme } from 'antd'
import { MapToken, SeedToken } from 'antd/es/theme/interface'
import { createContext, Dispatch, SetStateAction } from 'react'
import sessionServiceApi from '@services/sessionService.ts'
import accessListApi from '@services/accessListService.ts'
import appApi from '@services/appService.ts'
import roleApi from '@services/roleService.ts'
import securityLogServiceApi from '@services/securityLogService.ts'
import userServiceApi from '@services/userService.ts'
import routeApi from '@services/routeService.ts'
import profileReducer from './redusers/ProfileSlice.ts'
export interface ContextProps {
setTheme: Dispatch<
SetStateAction<{ algorithm: (token: SeedToken) => MapToken }>
>
}
export const Context = createContext<ContextProps>({
setTheme: () => theme.defaultAlgorithm
})
const rootReducer = combineReducers({
profileReducer,
[roleApi.reducerPath]: roleApi.reducer,
[userServiceApi.reducerPath]: userServiceApi.reducer,
[sessionServiceApi.reducerPath]: sessionServiceApi.reducer,
[securityLogServiceApi.reducerPath]: securityLogServiceApi.reducer,
[appApi.reducerPath]: appApi.reducer,
[accessListApi.reducerPath]: accessListApi.reducer,
[routeApi.reducerPath]: routeApi.reducer
})
export const setupStore = () =>
configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(
roleApi.middleware,
userServiceApi.middleware,
securityLogServiceApi.middleware,
appApi.middleware,
accessListApi.middleware,
routeApi.middleware,
userServiceApi.middleware,
sessionServiceApi.middleware
)
})
export type RootState = ReturnType<typeof rootReducer>
export type AppStore = ReturnType<typeof setupStore>
export type AppDispatch = AppStore['dispatch']
+22
View File
@@ -0,0 +1,22 @@
import { createAsyncThunk } from '@reduxjs/toolkit'
import { apiPaths } from '@constants/api/apiPaths.ts'
import { ProfileDataType } from '@pages/ProfilePage/profile-page.type.ts'
import { apiService } from '@services/apiService.ts'
export const fetchProfile = createAsyncThunk(
'profile/fetchProfile',
async (_, { rejectWithValue }) => {
try {
const response = await apiService.post<ProfileDataType>(
apiPaths.getProfile
)
return response.data
} catch (error) {
return rejectWithValue(error)
}
}
)
+63
View File
@@ -0,0 +1,63 @@
import {
ActionReducerMapBuilder,
createSlice,
PayloadAction
} from '@reduxjs/toolkit'
import {
ProfileDataType,
ProfileType
} from '@pages/ProfilePage/profile-page.type.ts'
import { fetchProfile } from './ActionCreators.ts'
export enum StateProfileStatus {
resolved = 'resolved',
pending = 'pending',
rejected = 'rejected',
notInit = 'notInit'
}
export const initialState: ProfileType = {
profile: {
email: '',
firstName: '',
lastName: '',
role: '',
roles: [],
permissions: [],
idleTimeoutMs: 0
},
status: StateProfileStatus.notInit,
error: ''
}
export const profileSlice = createSlice({
name: 'profile',
initialState,
reducers: {
clearProfile(state) {
state.profile = initialState.profile
}
},
extraReducers: (builder: ActionReducerMapBuilder<ProfileType>) => {
builder
.addCase(
fetchProfile.fulfilled,
(state, action: PayloadAction<ProfileDataType>) => {
state.status = StateProfileStatus.resolved
state.profile = { ...action.payload }
}
)
.addCase(fetchProfile.pending, (state) => {
state.status = StateProfileStatus.pending
})
.addCase(fetchProfile.rejected, (state, action: any) => {
state.status = StateProfileStatus.rejected
state.error = action.payload
})
}
})
export default profileSlice.reducer
+48
View File
@@ -0,0 +1,48 @@
export interface AccessListMethodType {
method: string
value: boolean
}
export interface AccessListSetListRequestType {
appId: number
methods: AccessListMethodType[]
removeOld?: boolean
}
export interface AccessListSetListSetOneRequestType {
appId: number
method: string
value: boolean
}
export interface EndpointType {
extra: Record<string, any>
inner: boolean
path: string
userAuthRequired: boolean
}
export type AddressType = {
ip: string
port: string
}
export type RequiredModuleType = {
name: string
required: boolean
}
export type RouteType = {
address: AddressType
endpoints: EndpointType[]
libVersion: string
moduleName: string
requiredModules: RequiredModuleType[]
version: string
}
export interface RouteApiResponseType {
originalResponse: RouteType[]
moduleEndpoints: Record<string, EndpointType[]>
allRouteMap: Record<string, EndpointType>
}
+33
View File
@@ -0,0 +1,33 @@
interface TokenType {
appId: boolean
createdAt: string
expireTime: boolean
token: string
}
export interface SystemTreeAppType {
description: string
id: boolean
name: string
tokens: TokenType[]
type: string
}
interface SystemServiceType {
apps: SystemTreeAppType[]
description: string
id: boolean
name: string
}
export interface DomainType {
description: string
id: boolean
name: string
services: SystemServiceType[]
}
export interface AppApiResponseType {
originalResponse: DomainType[]
appList: SystemTreeAppType[]
}
+10
View File
@@ -0,0 +1,10 @@
export interface MSPError {
details: Array<any>
errorCode: string
errorMessage: string
}
export interface LimitOffsetRequestType {
limit: number
offset: number
}
+25
View File
@@ -0,0 +1,25 @@
export interface LogResponseType {
totalCount: number
items: LogType[]
}
export interface LogType {
id: string
userId: string
createdAt: string
message: string
}
export type LogEventKeyType =
| 'login_logout'
| 'role_changed'
| 'user_changed'
| 'user_blocked'
export interface LogEventType {
event: LogEventKeyType
name: string
enabled: boolean
}
export type SetEventType = Omit<LogEventType, 'name'>
+9
View File
@@ -0,0 +1,9 @@
export interface LoginRequest {
email: string
password: string
}
export interface LoginResponse {
expired: string
headerName: string
token: string
}
+24
View File
@@ -0,0 +1,24 @@
export enum PermissionKeysType {
read = 'read', // Просмотр страниц
write = 'write' // Редактирование страниц
}
export interface RoleType {
changeMessage?: string
createdAt: string
description: string
externalGroup: string
id: number
name: string
permissions: PermissionKeysType[]
updatedAt: string
immutable: boolean
exclusive: boolean
}
export type NewRoleType = Omit<RoleType, 'id' | 'createdAt' | 'updatedAt'>
export interface PermissionType {
key: PermissionKeysType
name: string
}
+14
View File
@@ -0,0 +1,14 @@
import { SessionStatusKeysType } from '@constants/statuses'
export interface SessionType {
userId: string
createdAt: string
expiredAt: string
id: number
status: SessionStatusKeysType
}
export interface SessionResponseType {
totalCount: number
items: SessionType[]
}
+28
View File
@@ -0,0 +1,28 @@
export interface UserType {
id: number
blocked: boolean
createdAt: string
email: string
password: string
firstName: string
lastName: string
roleId: number
roleName: string
roles: number[]
updatedAt: string
description: string
lastSessionCreatedAt?: string
}
export interface UserResponseType {
items: UserType[]
}
export interface NewUserType {
description: string
email: string
firstName: string
lastName: string
password: string
roles: number[]
}
+8
View File
@@ -0,0 +1,8 @@
.close-btn {
border: none;
background: transparent;
padding: 5px !important;
position: absolute;
top: 8px;
right: 8px;
}
+24
View File
@@ -0,0 +1,24 @@
import { Button } from 'antd'
import './close-btn.scss'
interface CloseBtnPropsType {
ariaLabel?: string
onClick: () => void
}
const CloseBtn = ({ onClick, ariaLabel }: CloseBtnPropsType) => {
return (
<Button className="close-btn" aria-label={ariaLabel} onClick={onClick}>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 50 50"
width="20px"
height="20px"
>
<path d="M 7.71875 6.28125 L 6.28125 7.71875 L 23.5625 25 L 6.28125 42.28125 L 7.71875 43.71875 L 25 26.4375 L 42.28125 43.71875 L 43.71875 42.28125 L 26.4375 25 L 43.71875 7.71875 L 42.28125 6.28125 L 25 23.5625 Z" />
</svg>
</Button>
)
}
export default CloseBtn
+13
View File
@@ -0,0 +1,13 @@
import { Button, ButtonProps } from 'antd'
import './save-button.scss'
const SaveButton = ({ className, icon, ...rest }: ButtonProps) => {
return (
<Button {...rest} className={`save-button ${className}`}>
Сохранить
</Button>
)
}
export default SaveButton
+4
View File
@@ -0,0 +1,4 @@
.save-button {
width: 150px;
min-width: 100px;
}
+52
View File
@@ -0,0 +1,52 @@
import { BaseQueryFn, retry } from '@reduxjs/toolkit/query/react'
import { AxiosError, AxiosRequestConfig } from 'axios'
import { apiService } from '@services/apiService.ts'
import { MSPError } from '@type/index.ts'
export const axiosBaseQuery =
(
{ baseUrl }: { baseUrl: string } = { baseUrl: '' }
): BaseQueryFn<
{
url: string
method?: AxiosRequestConfig['method']
data?: AxiosRequestConfig['data']
params?: AxiosRequestConfig['params']
},
unknown,
unknown
> =>
async ({ url, method = 'post', data, params }) => {
try {
const result = await apiService({
url: baseUrl + url,
method,
data,
params
})
return { data: result.data }
} catch (axiosError) {
const err = axiosError as AxiosError<MSPError>
return {
error: { ...err.response }
}
}
}
export const staggeredBaseQueryWithBailOut = (baseUrl: string) =>
retry(
async (args: string | AxiosRequestConfig['data'], api, extraOptions) => {
const result = await axiosBaseQuery({ baseUrl })(args, api, extraOptions)
const error = result.error as AxiosError<MSPError>
if (error && error?.status === 400) {
retry.fail(result.error)
}
return result
},
{
maxRetries: 5
}
)
+31
View File
@@ -0,0 +1,31 @@
import { NavigateFunction, SetURLSearchParams } from 'react-router-dom'
export const setSelectedItemId = (
path: string,
id: string,
searchParams: string,
navigate: NavigateFunction
): void => {
navigate(
{
pathname: `${path}/${id}`,
search: searchParams
},
{ replace: true }
)
}
export const setSearchValue = (
value: string,
setSearchParams: SetURLSearchParams,
prefix: string = 'search'
) => {
setSearchParams((prev) => {
if (!value) {
prev.delete(prefix)
} else {
prev.set(prefix, value)
}
return prev
})
}
+15
View File
@@ -0,0 +1,15 @@
declare global {
interface Window {
config: { [key: string]: any };
}
}
export const getConfigProperty = (property: string, defaultValue: any) => {
if (
window.config &&
Object.prototype.hasOwnProperty.call(window.config, property)
) {
return window.config[property]
}
return defaultValue
}
+11
View File
@@ -0,0 +1,11 @@
import { ColumnItem } from 'isp-ui-kit/dist/Layout/Column/column.type'
export const filterFirstColumnItems = <T extends NonNullable<unknown>>(
listItems: ColumnItem<T>[],
searchValue: string
): ColumnItem<T>[] =>
listItems
? listItems.filter((el) =>
el.name.toLowerCase().trim().includes(searchValue.toLowerCase().trim())
)
: []
+20
View File
@@ -0,0 +1,20 @@
export const LocalStorage = {
set(key: string, value: any): void {
const item = typeof value === 'string' ? value : JSON.stringify(value)
localStorage.setItem(key, item)
},
get(key: string): any | null {
const value = localStorage.getItem(key)
try {
return value ? JSON.parse(value) : null
} catch (error) {
return value
}
},
remove(key: string): void {
localStorage.removeItem(key)
},
clear(): void {
localStorage.clear()
}
}
+16
View File
@@ -0,0 +1,16 @@
import { RoleType } from '@type/roles.type.ts'
export const findExclusiveRole = (
roles: RoleType[],
watchRoles: number[] = []
) => {
let firstExclusiveElement = null
for (let i = 0; i < roles.length; i++) {
const item = roles[i]
if (item.exclusive === true && watchRoles.includes(item.id)) {
firstExclusiveElement = item
break
}
}
return firstExclusiveElement
}
+4
View File
@@ -0,0 +1,4 @@
import { UserType } from '@type/user.type.ts'
export const getUserFullName = (user: UserType): string =>
user ? `${user.lastName} ${user.firstName}` : ''
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more