Skip to main content

pgl_auth

Pacote Python para autenticação de alunos (matrícula + senha) e emissão de um token JWT de curta duração (4 horas) para acesso ao proxy dos modelos de IA usado na disciplina.

A API serverless que valida a matrícula/senha e emite o token (hospedada no Vercel) vive num repositório separado, pgl_auth_server — foi extraída daqui porque o pyproject.toml do pacote, na raiz deste repo, confundia a detecção de dependências da Vercel. Nenhuma credencial do banco fica no pacote instalado pelos alunos.

Componentes deste repositório

  • src/pgl_auth/ — pacote publicado no PyPI, instalado pelos alunos (pip install pgl-auth).
  • db/schema.sql — schema pgl_auth e tabela pgl_auth.students.
  • db/migrate.py — aplica schema.sql no banco (usa NEON_DATABASE_URL do .env).
  • db/create_student.py — cria/atualiza a senha de um aluno (hash bcrypt).
  • .github/workflows/publish.yml — CI que publica o pacote no PyPI a cada release do GitHub.

Uso pelo aluno

pip install pgl-auth
from pgl_auth import PGLAuthClient

client = PGLAuthClient()  # usa PGL_AUTH_API_URL/PGL_AUTH_REGISTER_URL ou os defaults do Vercel

# Só na primeira vez: cadastra a senha (a matrícula precisa já estar
# ativa em pgl_proxy.students). Levanta AlreadyRegisteredError se essa
# matrícula já tiver senha cadastrada.
client.register("2021012345", "minha_senha")

token = client.login("2021012345", "minha_senha")

# usar o token para chamar o proxy dos modelos
headers = client.auth_header()  # {"Authorization": "Bearer <token>"}

Ou via linha de comando:

pgl-auth 2021012345 --register   # cadastra a senha (só na primeira vez)
pgl-auth 2021012345              # loga e imprime o token

Estrutura da tabela pgl_auth.students

coluna tipo descrição
id UUID (PK) identificador único, gerado automaticamente
registration_number TEXT (UNIQUE) matrícula do aluno
password_hash TEXT hash bcrypt da senha (nunca texto puro)
is_active BOOLEAN se o aluno pode autenticar
updated_at TIMESTAMPTZ atualizado automaticamente via trigger

Provisionar o banco

pip install -e ".[admin]"
python db/migrate.py                 # cria schema + tabela
python db/create_student.py 2021012345   # cadastra/atualiza um aluno (pede a senha)

Testes

pip install -e ".[dev]"
pytest

tests/test_create_student.py garante as regras de negócio do cadastro de senha (bloqueio se a matrícula não existir ou estiver inativa em pgl_proxy.students, e overwrite do registro existente em pgl_auth.students). tests/test_client.py cobre o cliente HTTP usado pelos alunos. Os testes rodam com dependências mockadas — não tocam no banco real — e são executados automaticamente no CI antes de qualquer build/publish (job test em publish.yml).

API e deploy no Vercel

A API (FastAPI, POST /api/login) e as instruções de deploy no Vercel ficam no repositório separado pgl_auth_server — veja o README de lá. Depois do deploy, atualize DEFAULT_API_URL em src/pgl_auth/client.py (ou oriente os alunos a definir PGL_AUTH_API_URL) com a URL final.

Publicar o pacote no PyPI

O workflow .github/workflows/publish.yml roda a cada push na main (também em release/workflow_dispatch): testa, builda e publica no PyPI usando um API token guardado como secret do repositório.

Configuração única (uma vez só):

  1. pypi.org → Account settings → API tokens → Add API token.
    • Se o projeto pgl-auth ainda não existe no PyPI, crie o token com escopo "Entire account" (o escopo pode ser restrito ao projeto depois do primeiro publish).
  2. No GitHub: repo → Settings → Secrets and variables → Actions → New repository secret.
    • Nome: PYPI_API_TOKEN
    • Valor: o token gerado no passo anterior (começa com pypi-).
  3. Pronto — o job publish usa secrets.PYPI_API_TOKEN automaticamente.

skip-existing: true faz o publish ser ignorado (sem falhar o job) quando a versão em pyproject.toml já foi publicada antes, então pushes na main sem bump de versão não quebram o CI.

Para publicar uma nova versão:

# atualizar version em pyproject.toml
git tag v0.1.0 && git push origin v0.1.0
# criar uma Release no GitHub a partir dessa tag -> dispara o workflow

Metadata

Release files for pgl-auth 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pgl-auth 0.3.1
File Size Uploaded Provenance Actions
pgl_auth-0.3.1.tar.gz 10.2 kB Without provenance Details for pgl_auth-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pgl-auth 0.3.1
File Interpreter ABI Platform Actions
pgl_auth-0.3.1-py3-none-any.whl Python 3 none any Details for pgl_auth-0.3.1-py3-none-any.whl

Total release size: 16.6 kB

Release files / pgl_auth-0.3.1.tar.gz

Download URL pgl_auth-0.3.1.tar.gz
Size 10.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a5a5117f2a96b59468952d3cbf3eeb06f76f074f4813a8a4b97f5fbd871de526
BLAKE2b-256 checksum
How to use checksums
7a9f825584c0a92eed9eb494436271bb3190961feb212af06ba6b93009e29c39
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pgl_auth-0.3.1-py3-none-any.whl

Download URL pgl_auth-0.3.1-py3-none-any.whl
Size 6.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
913affe049a3e2554815df8f7b9b33b568add10e5d1c5cfc7f9765ea33a34240
BLAKE2b-256 checksum
How to use checksums
dbc79e8870104e088056b1b61ed3077e8235bc4a2841c2668af0d9d27d17edd2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for pgl-auth 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page