Metadata-Version: 2.4
Name: gates-sdk
Version: 0.1.4
Summary: SDK em Python para integrar com o Gates para autenticação via Cognito e gestão de usuários
Author: Intelicity
License: MIT License
        
        Copyright (c) 2025 Intelicity
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/intelicity/gates-python-sdk
Project-URL: Repository, https://github.com/intelicity/gates-python-sdk
Project-URL: Documentation, https://github.com/intelicity/gates-python-sdk#readme
Project-URL: Bug Reports, https://github.com/intelicity/gates-python-sdk/issues
Project-URL: Source Code, https://github.com/intelicity/gates-python-sdk
Keywords: aws,cognito,jwt,authentication,gates,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyjwt[crypto]>=2.8
Requires-Dist: httpx<1.0,>=0.27
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: flake8>=6.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: isort>=5.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: build>=0.10; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.21; extra == "test"
Dynamic: license-file

# Gates SDK (Python)

[![PyPI version](https://badge.fury.io/py/gates-sdk.svg)](https://badge.fury.io/py/gates-sdk)
[![Python versions](https://img.shields.io/pypi/pyversions/gates-sdk.svg)](https://pypi.org/project/gates-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

SDK em Python para autenticação de usuários com tokens JWT do AWS Cognito e integração com o backend do Gates para gerenciamento de perfis. Estruturado para publicação no PyPI.

## Características

- ✅ Autenticação com tokens JWT do AWS Cognito
- ✅ Validação de grupos de usuários
- ✅ Cache automático de chaves públicas
- ✅ Cliente HTTP assíncrono para API do Gates
- ✅ Suporte a profiles de usuário personalizados
- ✅ Tratamento robusto de erros
- ✅ Type hints completos
- ✅ Testes unitários abrangentes

## Instalação

```bash
pip install gates-sdk
```

### Instalação para desenvolvimento

```bash
# Clone o repositório
git clone https://github.com/intelicity/gates-python-sdk.git
cd gates-python-sdk

# Crie um ambiente virtual
python -m venv venv

# Ative o ambiente virtual (Windows)
venv\Scripts\activate
# ou Linux/Mac:
# source venv/bin/activate

# Instale em modo de desenvolvimento
pip install -e ".[dev]"
```

## Uso

### Autenticação

```python
from gates_sdk import AuthService

auth = AuthService(
    region="sa-east-1",
    user_pool_id="sa-east-1_xxxxxxxxx",
    audience="your-client-id",
    required_group=["admin", "user"],  # opcional
)

try:
    user = auth.verify_token(token)
    print("Usuário autenticado", user)
    print("É membro do grupo?", auth.is_member_of(user.groups or []))
except Exception as exc:
    print("Falha ao autenticar:", exc)
```

### Serviço de usuários

```python
from gates_sdk import UserService

user_service = UserService(
    base_url="https://api.example.com",
    system="your-system-name",
)

users = user_service.get_all_users(id_token)
print(users.profiles, users.total)

profile = user_service.get_profile(id_token)
print(profile)
```

### Variáveis de ambiente

```bash
export GATES_REGION=sa-east-1
export GATES_USER_POOL_ID=sa-east-1_xxxxxxxxx
export GATES_CLIENT_ID=your-cognito-client-id
export GATES_BACKEND_URL=https://your-backend-api.com
export GATES_SYSTEM_NAME=your-system-name
```

Também é possível instanciar os serviços lendo essas variáveis com `os.getenv`.

## Desenvolvimento

### Configuração inicial

```bash
# Instalar dependências de desenvolvimento
pip install -e ".[dev]"

# Configurar pre-commit hooks (opcional)
pre-commit install
```

### Comandos úteis

```bash
# Executar testes
pytest

# Testes com cobertura
pytest --cov=src --cov-report=html

# Formatação de código
black src tests
isort src tests

# Verificar formatação sem modificar
black --check src tests
isort --check-only src tests

# Lint
flake8 src tests

# Verificação de tipos
mypy src

# Executar todas as verificações
pytest && black --check src tests && isort --check-only src tests && flake8 src tests && mypy src
```

### Usando o Makefile (Linux/Mac)

```bash
make help          # Mostra todos os comandos disponíveis
make install-dev    # Instala dependências de desenvolvimento
make test          # Executa testes
make format        # Formata código
make check         # Executa todas as verificações
make build         # Constrói o pacote
make upload-test   # Publica no TestPyPI
```

### Usando o script PowerShell (Windows)

```powershell
# Publicar no TestPyPI
.\publish.ps1 -Target test

# Publicar no PyPI (produção)
.\publish.ps1 -Target prod

# Pular testes durante publicação
.\publish.ps1 -SkipTests

# Forçar publicação sem confirmação
.\publish.ps1 -Force
```

### Estrutura do projeto

```
gates-python-sdk/
├── src/
│   ├── __init__.py          # Exports principais
│   ├── auth.py              # Serviço de autenticação
│   ├── cache.py             # Sistema de cache
│   ├── errors.py            # Exceções customizadas
│   ├── models.py            # Modelos de dados
│   ├── user.py              # Serviço de usuários
│   └── py.typed             # Marcador de type hints
├── tests/
│   ├── test_auth.py         # Testes de autenticação
│   ├── test_cache.py        # Testes de cache
│   └── test_user.py         # Testes de usuários
├── .github/workflows/       # GitHub Actions
├── pyproject.toml          # Configuração do projeto
├── CHANGELOG.md            # Histórico de mudanças
├── LICENSE                 # Licença MIT
├── MANIFEST.in             # Arquivos para incluir no pacote
├── Makefile               # Comandos para Unix/Linux
├── publish.ps1            # Script de publicação para Windows
├── publish.py             # Script de publicação Python
└── README.md              # Este arquivo
```

### Publicação

1. **Atualizar versão** em `pyproject.toml`
2. **Atualizar** `CHANGELOG.md`
3. **Executar testes**: `pytest`
4. **Testar no TestPyPI**: `.\publish.ps1 -Target test`
5. **Publicar no PyPI**: `.\publish.ps1 -Target prod`

### Testes

O projeto inclui testes unitários abrangentes:

```bash
# Executar todos os testes
pytest

# Executar com cobertura
pytest --cov=src

# Executar testes específicos
pytest tests/test_auth.py

# Executar com output verboso
pytest -v
```

### Integração Contínua

O projeto está configurado com GitHub Actions para:

- ✅ Testes automatizados em Python 3.9-3.12
- ✅ Verificação de formatação e lint
- ✅ Verificação de tipos com mypy
- ✅ Build e verificação do pacote
- ✅ Publicação automática no PyPI via releases

## Requisitos

- Python ≥ 3.9
- pyjwt[crypto] ≥ 2.8
- httpx ≥ 0.27

## Licença

MIT - veja o arquivo [LICENSE](LICENSE) para detalhes.

## Contribuição

1. Fork o projeto
2. Crie uma branch para sua feature (`git checkout -b feature/nova-feature`)
3. Commit suas mudanças (`git commit -am 'Adiciona nova feature'`)
4. Push para a branch (`git push origin feature/nova-feature`)
5. Abra um Pull Request

## Suporte

Para questões e suporte, abra uma [issue](https://github.com/intelicity/gates-python-sdk/issues) no GitHub.
