pgl-auth 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pgl_auth/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from .client import PGLAuthClient, login
2
+ from .exceptions import PGLAuthError, AuthenticationError, InactiveAccountError
3
+
4
+ __all__ = [
5
+ "PGLAuthClient",
6
+ "login",
7
+ "PGLAuthError",
8
+ "AuthenticationError",
9
+ "InactiveAccountError",
10
+ ]
11
+
12
+ __version__ = "0.1.0"
pgl_auth/cli.py ADDED
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import sys
6
+
7
+ from .exceptions import PGLAuthError
8
+
9
+
10
+ def main() -> int:
11
+ parser = argparse.ArgumentParser(prog="pgl-auth", description="Autentica o aluno e imprime o token de acesso.")
12
+ parser.add_argument("matricula", nargs="?", help="Número de matrícula do aluno")
13
+ parser.add_argument("--api-url", dest="api_url", default=None, help="URL da API de autenticação")
14
+ args = parser.parse_args()
15
+
16
+ matricula = args.matricula or input("Matrícula: ")
17
+ senha = getpass.getpass("Senha: ")
18
+
19
+ from .client import PGLAuthClient
20
+
21
+ client = PGLAuthClient(api_url=args.api_url)
22
+ try:
23
+ token = client.login(matricula, senha)
24
+ except PGLAuthError as exc:
25
+ print(f"Erro: {exc}", file=sys.stderr)
26
+ return 1
27
+
28
+ print(token)
29
+ return 0
30
+
31
+
32
+ if __name__ == "__main__":
33
+ raise SystemExit(main())
pgl_auth/client.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ import requests
6
+
7
+ from .exceptions import AuthenticationError, InactiveAccountError, PGLAuthError
8
+
9
+ DEFAULT_API_URL = "https://pgl-auth.vercel.app/api/login"
10
+ API_URL_ENV_VAR = "PGL_AUTH_API_URL"
11
+
12
+
13
+ class PGLAuthClient:
14
+ """Cliente para autenticar alunos e obter o token de acesso ao proxy de modelos."""
15
+
16
+ def __init__(self, api_url: str | None = None, timeout: float = 10.0) -> None:
17
+ self.api_url = api_url or os.environ.get(API_URL_ENV_VAR, DEFAULT_API_URL)
18
+ self.timeout = timeout
19
+ self._token: str | None = None
20
+
21
+ def login(self, matricula: str, senha: str) -> str:
22
+ """Autentica o aluno e retorna o token JWT (válido por 4 horas)."""
23
+ try:
24
+ response = requests.post(
25
+ self.api_url,
26
+ json={"matricula": matricula, "senha": senha},
27
+ timeout=self.timeout,
28
+ )
29
+ except requests.RequestException as exc:
30
+ raise PGLAuthError(f"Falha ao contatar o serviço de autenticação: {exc}") from exc
31
+
32
+ if response.status_code == 401:
33
+ raise AuthenticationError("Matrícula ou senha inválidos.")
34
+ if response.status_code == 403:
35
+ raise InactiveAccountError("Cadastro do aluno está inativo.")
36
+
37
+ try:
38
+ response.raise_for_status()
39
+ except requests.HTTPError as exc:
40
+ raise PGLAuthError(f"Erro ao autenticar: {exc}") from exc
41
+
42
+ data = response.json()
43
+ self._token = data["access_token"]
44
+ return self._token
45
+
46
+ @property
47
+ def token(self) -> str | None:
48
+ return self._token
49
+
50
+ def auth_header(self) -> dict[str, str]:
51
+ """Retorna o cabeçalho Authorization pronto para chamar o proxy de modelos."""
52
+ if not self._token:
53
+ raise PGLAuthError("Nenhum token disponível. Chame login() primeiro.")
54
+ return {"Authorization": f"Bearer {self._token}"}
55
+
56
+
57
+ def login(matricula: str, senha: str, api_url: str | None = None) -> str:
58
+ """Atalho para autenticar sem instanciar PGLAuthClient diretamente."""
59
+ return PGLAuthClient(api_url=api_url).login(matricula, senha)
pgl_auth/exceptions.py ADDED
@@ -0,0 +1,10 @@
1
+ class PGLAuthError(Exception):
2
+ """Erro base para falhas de autenticação no pgl_auth."""
3
+
4
+
5
+ class AuthenticationError(PGLAuthError):
6
+ """Matrícula ou senha inválidos."""
7
+
8
+
9
+ class InactiveAccountError(PGLAuthError):
10
+ """Conta do aluno está inativa."""
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgl-auth
3
+ Version: 0.1.0
4
+ Summary: Cliente de autenticação para alunos acessarem o proxy de modelos de IA da disciplina.
5
+ Project-URL: Homepage, https://github.com/renansantosmendes/pgl_auth
6
+ Author-email: Renan Santos Mendes <renansantosmendes@gmail.com>
7
+ License-Expression: MIT
8
+ Requires-Python: >=3.9
9
+ Requires-Dist: requests>=2.31
10
+ Provides-Extra: admin
11
+ Requires-Dist: bcrypt>=4.2; extra == 'admin'
12
+ Requires-Dist: psycopg2-binary>=2.9; extra == 'admin'
13
+ Requires-Dist: python-dotenv>=1.0; extra == 'admin'
14
+ Provides-Extra: dev
15
+ Requires-Dist: bcrypt>=4.2; extra == 'dev'
16
+ Requires-Dist: psycopg2-binary>=2.9; extra == 'dev'
17
+ Requires-Dist: pytest>=8.0; extra == 'dev'
18
+ Requires-Dist: python-dotenv>=1.0; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pgl_auth
22
+
23
+ Pacote Python para autenticação de alunos (matrícula + senha) e emissão de um token JWT
24
+ de curta duração (4 horas) para acesso ao proxy dos modelos de IA usado na disciplina.
25
+
26
+ ## Componentes deste repositório
27
+
28
+ - `src/pgl_auth/` — pacote publicado no PyPI, instalado pelos alunos (`pip install pgl-auth`).
29
+ - `api/login.py` — API serverless (FastAPI) hospedada no Vercel, valida matrícula/senha no
30
+ Postgres e emite o JWT. Nenhuma credencial do banco fica no pacote instalado pelos alunos.
31
+ - `db/schema.sql` — schema `pgl_auth` e tabela `pgl_auth.students`.
32
+ - `db/migrate.py` — aplica `schema.sql` no banco (usa `NEON_DATABASE_URL` do `.env`).
33
+ - `db/create_student.py` — cria/atualiza a senha de um aluno (hash bcrypt).
34
+ - `.github/workflows/publish.yml` — CI que publica o pacote no PyPI a cada release do GitHub.
35
+
36
+ ## Uso pelo aluno
37
+
38
+ ```bash
39
+ pip install pgl-auth
40
+ ```
41
+
42
+ ```python
43
+ from pgl_auth import PGLAuthClient
44
+
45
+ client = PGLAuthClient() # usa PGL_AUTH_API_URL ou o default do Vercel
46
+ token = client.login("2021012345", "minha_senha")
47
+
48
+ # usar o token para chamar o proxy dos modelos
49
+ headers = client.auth_header() # {"Authorization": "Bearer <token>"}
50
+ ```
51
+
52
+ Ou via linha de comando:
53
+
54
+ ```bash
55
+ pgl-auth 2021012345
56
+ ```
57
+
58
+ ## Estrutura da tabela `pgl_auth.students`
59
+
60
+ | coluna | tipo | descrição |
61
+ |------------------|---------------|----------------------------------------------|
62
+ | `id` | UUID (PK) | identificador único, gerado automaticamente |
63
+ | `matricula` | TEXT (UNIQUE) | matrícula do aluno |
64
+ | `password_hash` | TEXT | hash bcrypt da senha (nunca texto puro) |
65
+ | `is_active` | BOOLEAN | se o aluno pode autenticar |
66
+ | `updated_at` | TIMESTAMPTZ | atualizado automaticamente via trigger |
67
+
68
+ ## Provisionar o banco
69
+
70
+ ```bash
71
+ pip install -e ".[admin]"
72
+ python db/migrate.py # cria schema + tabela
73
+ python db/create_student.py 2021012345 # cadastra/atualiza um aluno (pede a senha)
74
+ ```
75
+
76
+ ## Testes
77
+
78
+ ```bash
79
+ pip install -e ".[dev]"
80
+ pytest
81
+ ```
82
+
83
+ `tests/test_create_student.py` garante as regras de negócio do cadastro de senha
84
+ (bloqueio se a matrícula não existir ou estiver inativa em `pgl_proxy.students`,
85
+ e overwrite do registro existente em `pgl_auth.students`). `tests/test_client.py`
86
+ cobre o cliente HTTP usado pelos alunos. Os testes rodam com dependências
87
+ mockadas — não tocam no banco real — e são executados automaticamente no CI
88
+ antes de qualquer build/publish (job `test` em `publish.yml`).
89
+
90
+ ## Deploy da API no Vercel
91
+
92
+ 1. Importe este repositório no Vercel (Project → Add New → Project).
93
+ 2. Configure as variáveis de ambiente do projeto no Vercel:
94
+ - `NEON_DATABASE_URL`
95
+ - `JWT_SECRET_KEY`
96
+ 3. Deploy automático a cada push (o Vercel detecta `api/login.py` + `api/requirements.txt`
97
+ via `vercel.json` e cria a função serverless em `/api/login`).
98
+ 4. Atualize `DEFAULT_API_URL` em `src/pgl_auth/client.py` (ou oriente os alunos a definir
99
+ `PGL_AUTH_API_URL`) com a URL final do deploy.
100
+
101
+ ## Publicar o pacote no PyPI
102
+
103
+ O workflow `.github/workflows/publish.yml` roda a cada push na `main` (também em
104
+ release/`workflow_dispatch`): testa, builda e publica no PyPI usando um **API token**
105
+ guardado como secret do repositório.
106
+
107
+ Configuração única (uma vez só):
108
+
109
+ 1. pypi.org → Account settings → API tokens → **Add API token**.
110
+ - Se o projeto `pgl-auth` ainda não existe no PyPI, crie o token com escopo
111
+ "Entire account" (o escopo pode ser restrito ao projeto depois do primeiro publish).
112
+ 2. No GitHub: repo → Settings → Secrets and variables → Actions → **New repository secret**.
113
+ - Nome: `PYPI_API_TOKEN`
114
+ - Valor: o token gerado no passo anterior (começa com `pypi-`).
115
+ 3. Pronto — o job `publish` usa `secrets.PYPI_API_TOKEN` automaticamente.
116
+
117
+ `skip-existing: true` faz o publish ser ignorado (sem falhar o job) quando a versão em
118
+ `pyproject.toml` já foi publicada antes, então pushes na main sem bump de versão não
119
+ quebram o CI.
120
+
121
+ Para publicar uma nova versão:
122
+
123
+ ```bash
124
+ # atualizar version em pyproject.toml
125
+ git tag v0.1.0 && git push origin v0.1.0
126
+ # criar uma Release no GitHub a partir dessa tag -> dispara o workflow
127
+ ```
@@ -0,0 +1,8 @@
1
+ pgl_auth/__init__.py,sha256=NgYmvmpFYBg0R9RR5TzX4QZtMIKGt-vohiV7MCzV6Lk,268
2
+ pgl_auth/cli.py,sha256=wG0coxGSVO0YMmbtt-DMZ56WoNcDEWIZ_Bk0h7iOm0I,901
3
+ pgl_auth/client.py,sha256=X1wV6FPsRQXDMujH7kFZ3wB43QKnUUXqdFAKLk7xF0g,2160
4
+ pgl_auth/exceptions.py,sha256=KuuP7tvIvJzIj3z04jcOIX2TnETehwi3RN1tvXndFCA,263
5
+ pgl_auth-0.1.0.dist-info/METADATA,sha256=ttZfZ7Dwx6q5ZtVLqDyvLqibj1ezPzU2webhNA46IhA,5090
6
+ pgl_auth-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ pgl_auth-0.1.0.dist-info/entry_points.txt,sha256=Jz8lpYH51VcPOApaWHNzmuuo8w-V1zCQKNQ11OGAvNg,47
8
+ pgl_auth-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pgl-auth = pgl_auth.cli:main