chore(docs): alinhar integração front/backend e CORS

master
Artur Oliveira 2025-12-16 10:50:14 -03:00
parent 116261e7ff
commit 53f64dd15f
5 changed files with 106 additions and 100 deletions

View File

@ -1,38 +1,36 @@
# Hit Server Manager # Servers Manager
Plataforma interna da Hit Communications para catalogar os servidores corporativos e expor essas informações de forma rápida ao time de Análise de Sistemas e Desenvolvimento. O backend centraliza cadastros, contexto técnico (tipo, aplicação e banco) e credenciais operacionais, facilitando consultas padronizadas e mantendo histórico de alterações. Plataforma interna para catalogar servidores corporativos e facilitar consultas rápidas pelo time de desenvolvimento/analistas. Inclui backend em Spring Boot (JWT + refresh token em cookies) e frontend React/Vite consumindo os endpoints.
## Principais recursos ## Estrutura
- CRUD completo de usuários internos e servidores - `backend/`: API em Spring Boot 4 (Java 21), JWT stateless, cookies para auth.
- Validação de domínio corporativo para criação de usuários - `frontned/`: Front em React + Vite (TS), login integrado via cookies.
- Mapeamentos DTO ↔ entidades com MapStruct - `postman_collection.json`: Coleção para testar autenticação e CRUDs de usuários/servidores.
- API REST documentada via coleção Postman (`postman_collection.json`)
- Persistência em H2 (memória/disco) com Spring Data JPA e geração automática de IDs personalizados para servidores
## Stack ## Requisitos
- Java 21 + Spring Boot 4.0 - JDK 21
- Spring Web MVC, Validation, Data JPA - Node 20+ (Yarn ou npm)
- H2 Database
- MapStruct 1.6
- Lombok
- Spring Security (JWT em breve)
- Docker Compose para orquestração local
- ReactJS
## Como rodar ## Rodando local
1. **Pré-requisitos**: JDK 21 e acesso ao Gradle Wrapper (`./gradlew`). 1. **Backend**
2. **Instalar dependências e rodar testes**:
```bash
./gradlew clean test
```
3. **Subir o backend**:
```bash ```bash
cd backend
./gradlew bootRun ./gradlew bootRun
``` ```
4. A API ficará disponível em `http://localhost:8080`. Utilize a coleção Postman incluída para exercitar os endpoints de `Users` e `Servers` (`{{base_url}}` já configurado com esse endereço). Variáveis úteis: `JWT_SECRET` (>=32 chars), `DB_*` (Postgres). Por padrão usa `localhost:8080`.
## Próximos passos 2. **Frontend**
- [ ] Substituir H2 por PostgreSQL para persistência ```bash
- [ ] Proteger os endpoints com autenticação (Spring Security com JWT) cd frontned
- [ ] Criar o frontend React integrado ao backend cp .env.example .env # ajuste VITE_BACKEND_URL se necessário
- [ ] Containerizar backend + frontend com Docker Compose yarn install # ou npm install
yarn dev # ou npm run dev
```
Acesse `http://localhost:5173`.
3. **Testar via Postman**
Importe `postman_collection.json`. Rode "Auth / Login" para setar cookies e seguir para os demais endpoints.
## Documentação específica
- Backend: `backend/README.md`
- Frontend: `frontned/README.md`

41
backend/README.md 100644
View File

@ -0,0 +1,41 @@
# Backend - Servers Manager
API REST em Spring Boot 4 (Java 21) com autenticação JWT stateless e refresh token em cookie HttpOnly.
## Stack
- Spring Boot 4.0 (Web MVC, Validation, Data JPA)
- Spring Security (JWT, stateless)
- MapStruct 1.6, Lombok
- PostgreSQL (padrão) ou H2
- JJWT 0.12 para geração/validação de tokens
## Configuração
Variáveis principais:
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWD` — Postgres
- `JWT_SECRET` — chave HMAC >= 32 chars
- `security.jwt.access-token-expiration` — padrão 30m
- `security.jwt.refresh-token-expiration` — padrão 30d
Arquivo `src/main/resources/application.yaml` já traz defaults; adicione um `.env` ou exporte variáveis conforme o ambiente.
Seed: `src/main/resources/data.sql` cria usuário padrão `default@hittelco.com` (senha `senha123`, bcrypt).
## Endpoints chave
- `POST /api/auth/login` — autentica e devolve `access_token` (cookie) + `refresh_token` (HttpOnly).
- `POST /api/auth/refresh` — reemite cookies a partir do refresh.
- `POST /api/auth/signup` — cria usuário (requer auth).
- CRUD `/api/users` e `/api/servers` protegidos.
## Rodar local
```bash
./gradlew bootRun
```
API em `http://localhost:8080` com CORS liberado para `http://localhost:5173`.
## Testes
```bash
./gradlew test
```
## Postman
Use `postman_collection.json` na raiz; o login grava cookies e variáveis `access_token`/`refresh_token`.

View File

@ -1,73 +1,36 @@
# React + TypeScript + Vite # Frontend - Servers Manager
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. ## Stack
- React 19, React Router 7
- Axios (withCredentials)
- Tailwind (config in `tailwind.config.js`)
- react-hot-toast para feedback
Currently, two official plugins are available: ## Configuração
Crie `.env` a partir de `.env.example`:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh ```
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh VITE_BACKEND_URL=http://localhost:8080
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: ## Rodar
```bash
```js yarn install # ou npm install
// eslint.config.js yarn dev # ou npm run dev
import reactX from 'eslint-plugin-react-x' ```
import reactDom from 'eslint-plugin-react-dom' Acesse `http://localhost:5173`.
export default defineConfig([ ## Fluxo de login
globalIgnores(['dist']), - Página `/login` envia `POST /api/auth/login` com email/senha.
{ - Tokens vêm em cookies (`access_token` e `refresh_token` HttpOnly). Axios usa `withCredentials`.
files: ['**/*.{ts,tsx}'], - Após sucesso, redireciona para `/` (ajuste rota/dashboard conforme evoluir).
extends: [
// Other configs... ## Estrutura
// Enable lint rules for React - `src/Api.ts`: cliente axios com `withCredentials`.
reactX.configs['recommended-typescript'], - `src/pages/Login.tsx`: tela de login e toasts.
// Enable lint rules for React DOM - `src/components/Layout.tsx`: layout base.
reactDom.configs.recommended,
], ## Build/Lint
languageOptions: { ```bash
parserOptions: { yarn build
project: ['./tsconfig.node.json', './tsconfig.app.json'], yarn lint
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```

View File

@ -1,13 +1,14 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'; import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import './App.css'; import './App.css';
import { Login } from './pages/Login'; import { Login } from './pages/Login';
import { Dashboard } from './pages/Dashboard';
function App() { function App() {
return ( return (
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route path="/" element={<Navigate to="/login" replace />} /> <Route path="/" element={<Dashboard />} />
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>

View File

@ -0,0 +1,3 @@
export const Dashboard = () => {
return <div>Dashboard Page</div>;
};