pgl-auth 0.1.0__tar.gz

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.
@@ -0,0 +1,60 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ release:
7
+ types: [published]
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ test:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.12"
19
+
20
+ - name: Install package and test dependencies
21
+ run: python -m pip install -e ".[dev]"
22
+
23
+ - name: Run unit tests
24
+ run: python -m pytest
25
+
26
+ build:
27
+ needs: test
28
+ runs-on: ubuntu-latest
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+
32
+ - uses: actions/setup-python@v5
33
+ with:
34
+ python-version: "3.12"
35
+
36
+ - name: Install build tool
37
+ run: python -m pip install --upgrade build
38
+
39
+ - name: Build sdist and wheel
40
+ run: python -m build
41
+
42
+ - uses: actions/upload-artifact@v4
43
+ with:
44
+ name: dist
45
+ path: dist/
46
+
47
+ publish:
48
+ needs: build
49
+ runs-on: ubuntu-latest
50
+ steps:
51
+ - uses: actions/download-artifact@v4
52
+ with:
53
+ name: dist
54
+ path: dist/
55
+
56
+ - name: Publish to PyPI
57
+ uses: pypa/gh-action-pypi-publish@release/v1
58
+ with:
59
+ password: ${{ secrets.PYPI_API_TOKEN }}
60
+ skip-existing: true
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
@@ -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,107 @@
1
+ # pgl_auth
2
+
3
+ Pacote Python para autenticação de alunos (matrícula + senha) e emissão de um token JWT
4
+ de curta duração (4 horas) para acesso ao proxy dos modelos de IA usado na disciplina.
5
+
6
+ ## Componentes deste repositório
7
+
8
+ - `src/pgl_auth/` — pacote publicado no PyPI, instalado pelos alunos (`pip install pgl-auth`).
9
+ - `api/login.py` — API serverless (FastAPI) hospedada no Vercel, valida matrícula/senha no
10
+ Postgres e emite o JWT. Nenhuma credencial do banco fica no pacote instalado pelos alunos.
11
+ - `db/schema.sql` — schema `pgl_auth` e tabela `pgl_auth.students`.
12
+ - `db/migrate.py` — aplica `schema.sql` no banco (usa `NEON_DATABASE_URL` do `.env`).
13
+ - `db/create_student.py` — cria/atualiza a senha de um aluno (hash bcrypt).
14
+ - `.github/workflows/publish.yml` — CI que publica o pacote no PyPI a cada release do GitHub.
15
+
16
+ ## Uso pelo aluno
17
+
18
+ ```bash
19
+ pip install pgl-auth
20
+ ```
21
+
22
+ ```python
23
+ from pgl_auth import PGLAuthClient
24
+
25
+ client = PGLAuthClient() # usa PGL_AUTH_API_URL ou o default do Vercel
26
+ token = client.login("2021012345", "minha_senha")
27
+
28
+ # usar o token para chamar o proxy dos modelos
29
+ headers = client.auth_header() # {"Authorization": "Bearer <token>"}
30
+ ```
31
+
32
+ Ou via linha de comando:
33
+
34
+ ```bash
35
+ pgl-auth 2021012345
36
+ ```
37
+
38
+ ## Estrutura da tabela `pgl_auth.students`
39
+
40
+ | coluna | tipo | descrição |
41
+ |------------------|---------------|----------------------------------------------|
42
+ | `id` | UUID (PK) | identificador único, gerado automaticamente |
43
+ | `matricula` | TEXT (UNIQUE) | matrícula do aluno |
44
+ | `password_hash` | TEXT | hash bcrypt da senha (nunca texto puro) |
45
+ | `is_active` | BOOLEAN | se o aluno pode autenticar |
46
+ | `updated_at` | TIMESTAMPTZ | atualizado automaticamente via trigger |
47
+
48
+ ## Provisionar o banco
49
+
50
+ ```bash
51
+ pip install -e ".[admin]"
52
+ python db/migrate.py # cria schema + tabela
53
+ python db/create_student.py 2021012345 # cadastra/atualiza um aluno (pede a senha)
54
+ ```
55
+
56
+ ## Testes
57
+
58
+ ```bash
59
+ pip install -e ".[dev]"
60
+ pytest
61
+ ```
62
+
63
+ `tests/test_create_student.py` garante as regras de negócio do cadastro de senha
64
+ (bloqueio se a matrícula não existir ou estiver inativa em `pgl_proxy.students`,
65
+ e overwrite do registro existente em `pgl_auth.students`). `tests/test_client.py`
66
+ cobre o cliente HTTP usado pelos alunos. Os testes rodam com dependências
67
+ mockadas — não tocam no banco real — e são executados automaticamente no CI
68
+ antes de qualquer build/publish (job `test` em `publish.yml`).
69
+
70
+ ## Deploy da API no Vercel
71
+
72
+ 1. Importe este repositório no Vercel (Project → Add New → Project).
73
+ 2. Configure as variáveis de ambiente do projeto no Vercel:
74
+ - `NEON_DATABASE_URL`
75
+ - `JWT_SECRET_KEY`
76
+ 3. Deploy automático a cada push (o Vercel detecta `api/login.py` + `api/requirements.txt`
77
+ via `vercel.json` e cria a função serverless em `/api/login`).
78
+ 4. Atualize `DEFAULT_API_URL` em `src/pgl_auth/client.py` (ou oriente os alunos a definir
79
+ `PGL_AUTH_API_URL`) com a URL final do deploy.
80
+
81
+ ## Publicar o pacote no PyPI
82
+
83
+ O workflow `.github/workflows/publish.yml` roda a cada push na `main` (também em
84
+ release/`workflow_dispatch`): testa, builda e publica no PyPI usando um **API token**
85
+ guardado como secret do repositório.
86
+
87
+ Configuração única (uma vez só):
88
+
89
+ 1. pypi.org → Account settings → API tokens → **Add API token**.
90
+ - Se o projeto `pgl-auth` ainda não existe no PyPI, crie o token com escopo
91
+ "Entire account" (o escopo pode ser restrito ao projeto depois do primeiro publish).
92
+ 2. No GitHub: repo → Settings → Secrets and variables → Actions → **New repository secret**.
93
+ - Nome: `PYPI_API_TOKEN`
94
+ - Valor: o token gerado no passo anterior (começa com `pypi-`).
95
+ 3. Pronto — o job `publish` usa `secrets.PYPI_API_TOKEN` automaticamente.
96
+
97
+ `skip-existing: true` faz o publish ser ignorado (sem falhar o job) quando a versão em
98
+ `pyproject.toml` já foi publicada antes, então pushes na main sem bump de versão não
99
+ quebram o CI.
100
+
101
+ Para publicar uma nova versão:
102
+
103
+ ```bash
104
+ # atualizar version em pyproject.toml
105
+ git tag v0.1.0 && git push origin v0.1.0
106
+ # criar uma Release no GitHub a partir dessa tag -> dispara o workflow
107
+ ```
@@ -0,0 +1,57 @@
1
+ import os
2
+ from datetime import datetime, timedelta, timezone
3
+
4
+ import bcrypt
5
+ import jwt
6
+ import psycopg2
7
+ from fastapi import FastAPI, HTTPException
8
+ from pydantic import BaseModel
9
+
10
+ app = FastAPI()
11
+
12
+ TOKEN_TTL = timedelta(hours=4)
13
+
14
+
15
+ class LoginRequest(BaseModel):
16
+ matricula: str
17
+ senha: str
18
+
19
+
20
+ class LoginResponse(BaseModel):
21
+ access_token: str
22
+ token_type: str = "bearer"
23
+ expires_in: int
24
+
25
+
26
+ def _get_connection():
27
+ return psycopg2.connect(os.environ["NEON_DATABASE_URL"])
28
+
29
+
30
+ @app.post("/api/login", response_model=LoginResponse)
31
+ def login(payload: LoginRequest) -> LoginResponse:
32
+ with _get_connection() as conn:
33
+ with conn.cursor() as cur:
34
+ cur.execute(
35
+ "SELECT password_hash, is_active FROM pgl_auth.students WHERE matricula = %s",
36
+ (payload.matricula,),
37
+ )
38
+ row = cur.fetchone()
39
+
40
+ if row is None:
41
+ raise HTTPException(status_code=401, detail="Matrícula ou senha inválidos.")
42
+
43
+ password_hash, is_active = row
44
+
45
+ if not bcrypt.checkpw(payload.senha.encode("utf-8"), password_hash.encode("utf-8")):
46
+ raise HTTPException(status_code=401, detail="Matrícula ou senha inválidos.")
47
+
48
+ if not is_active:
49
+ raise HTTPException(status_code=403, detail="Cadastro do aluno está inativo.")
50
+
51
+ now = datetime.now(timezone.utc)
52
+ token = jwt.encode(
53
+ {"sub": payload.matricula, "iat": now, "exp": now + TOKEN_TTL},
54
+ os.environ["JWT_SECRET_KEY"],
55
+ algorithm="HS256",
56
+ )
57
+ return LoginResponse(access_token=token, expires_in=int(TOKEN_TTL.total_seconds()))
@@ -0,0 +1,5 @@
1
+ fastapi==0.115.0
2
+ psycopg2-binary==2.9.9
3
+ bcrypt==4.2.0
4
+ PyJWT==2.9.0
5
+ pydantic==2.9.2
File without changes
@@ -0,0 +1,92 @@
1
+ """Cria ou atualiza a senha de um aluno em pgl_auth.students.
2
+
3
+ Só é permitido criar/atualizar a senha se a matrícula já existir e estiver
4
+ ativa em pgl_proxy.students. Se a matrícula já tiver um registro em
5
+ pgl_auth.students, ele é sobrescrito (senha e is_active atualizados).
6
+
7
+ Uso:
8
+ python db/create_student.py <matricula> [--inactive]
9
+ A senha é solicitada de forma oculta no terminal.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import getpass
15
+ import os
16
+
17
+ import bcrypt
18
+ import psycopg2
19
+ from dotenv import load_dotenv
20
+
21
+ load_dotenv()
22
+
23
+ CHECK_PROXY_SQL = "SELECT is_active FROM pgl_proxy.students WHERE matricula = %s;"
24
+
25
+ UPSERT_SQL = """
26
+ INSERT INTO pgl_auth.students (matricula, password_hash, is_active)
27
+ VALUES (%s, %s, %s)
28
+ ON CONFLICT (matricula)
29
+ DO UPDATE SET password_hash = EXCLUDED.password_hash, is_active = EXCLUDED.is_active;
30
+ """
31
+
32
+
33
+ class StudentNotEligible(Exception):
34
+ """Levantada quando a matrícula não pode ter uma senha criada/atualizada."""
35
+
36
+
37
+ def get_proxy_active_status(cur, matricula: str) -> bool | None:
38
+ """Retorna is_active do aluno em pgl_proxy.students, ou None se não existir."""
39
+ cur.execute(CHECK_PROXY_SQL, (matricula,))
40
+ row = cur.fetchone()
41
+ return None if row is None else row[0]
42
+
43
+
44
+ def ensure_can_create_password(cur, matricula: str) -> None:
45
+ """Levanta StudentNotEligible se a matrícula não existir ou estiver inativa em pgl_proxy."""
46
+ status = get_proxy_active_status(cur, matricula)
47
+ if status is None:
48
+ raise StudentNotEligible(f"Matrícula {matricula} não encontrada em pgl_proxy.students.")
49
+ if not status:
50
+ raise StudentNotEligible(f"Matrícula {matricula} está inativa em pgl_proxy.students.")
51
+
52
+
53
+ def hash_password(senha: str) -> str:
54
+ return bcrypt.hashpw(senha.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
55
+
56
+
57
+ def upsert_auth_record(cur, matricula: str, password_hash: str, is_active: bool) -> None:
58
+ """Insere o registro de auth ou sobrescreve o existente para a mesma matrícula."""
59
+ cur.execute(UPSERT_SQL, (matricula, password_hash, is_active))
60
+
61
+
62
+ def main() -> None:
63
+ parser = argparse.ArgumentParser(description="Cria/atualiza um aluno no pgl_auth.")
64
+ parser.add_argument("matricula")
65
+ parser.add_argument("--inactive", action="store_true", help="Cria o aluno já como inativo")
66
+ args = parser.parse_args()
67
+
68
+ database_url = os.environ["NEON_DATABASE_URL"]
69
+
70
+ with psycopg2.connect(database_url) as conn:
71
+ with conn.cursor() as cur:
72
+ try:
73
+ ensure_can_create_password(cur, args.matricula)
74
+ except StudentNotEligible as exc:
75
+ raise SystemExit(str(exc)) from exc
76
+
77
+ senha = getpass.getpass("Senha: ")
78
+ confirmacao = getpass.getpass("Confirme a senha: ")
79
+ if senha != confirmacao:
80
+ raise SystemExit("As senhas não conferem.")
81
+
82
+ password_hash = hash_password(senha)
83
+
84
+ with conn.cursor() as cur:
85
+ upsert_auth_record(cur, args.matricula, password_hash, not args.inactive)
86
+ conn.commit()
87
+
88
+ print(f"Aluno {args.matricula} salvo com sucesso.")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
@@ -0,0 +1,28 @@
1
+ """Aplica db/schema.sql no banco apontado por NEON_DATABASE_URL (lido do .env)."""
2
+ from __future__ import annotations
3
+
4
+ import pathlib
5
+
6
+ import psycopg2
7
+ from dotenv import load_dotenv
8
+ import os
9
+
10
+ load_dotenv()
11
+
12
+ SCHEMA_PATH = pathlib.Path(__file__).parent / "schema.sql"
13
+
14
+
15
+ def main() -> None:
16
+ database_url = os.environ["NEON_DATABASE_URL"]
17
+ schema_sql = SCHEMA_PATH.read_text(encoding="utf-8")
18
+
19
+ with psycopg2.connect(database_url) as conn:
20
+ with conn.cursor() as cur:
21
+ cur.execute(schema_sql)
22
+ conn.commit()
23
+
24
+ print("Schema pgl_auth e tabela students aplicados com sucesso.")
25
+
26
+
27
+ if __name__ == "__main__":
28
+ main()
@@ -0,0 +1,28 @@
1
+ -- Schema e tabela de autenticação dos alunos para o pgl_auth.
2
+
3
+ CREATE EXTENSION IF NOT EXISTS pgcrypto;
4
+
5
+ CREATE SCHEMA IF NOT EXISTS pgl_auth;
6
+
7
+ CREATE TABLE IF NOT EXISTS pgl_auth.students (
8
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
9
+ matricula TEXT NOT NULL UNIQUE,
10
+ password_hash TEXT NOT NULL,
11
+ is_active BOOLEAN NOT NULL DEFAULT TRUE,
12
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
13
+ );
14
+
15
+ CREATE OR REPLACE FUNCTION pgl_auth.set_updated_at()
16
+ RETURNS TRIGGER AS $$
17
+ BEGIN
18
+ NEW.updated_at = now();
19
+ RETURN NEW;
20
+ END;
21
+ $$ LANGUAGE plpgsql;
22
+
23
+ DROP TRIGGER IF EXISTS trg_students_updated_at ON pgl_auth.students;
24
+
25
+ CREATE TRIGGER trg_students_updated_at
26
+ BEFORE UPDATE ON pgl_auth.students
27
+ FOR EACH ROW
28
+ EXECUTE FUNCTION pgl_auth.set_updated_at();
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pgl-auth"
7
+ version = "0.1.0"
8
+ description = "Cliente de autenticação para alunos acessarem o proxy de modelos de IA da disciplina."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [
13
+ { name = "Renan Santos Mendes", email = "renansantosmendes@gmail.com" },
14
+ ]
15
+ dependencies = [
16
+ "requests>=2.31",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ admin = [
21
+ "psycopg2-binary>=2.9",
22
+ "python-dotenv>=1.0",
23
+ "bcrypt>=4.2",
24
+ ]
25
+ dev = [
26
+ "pgl-auth[admin]",
27
+ "pytest>=8.0",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/renansantosmendes/pgl_auth"
32
+
33
+ [project.scripts]
34
+ pgl-auth = "pgl_auth.cli:main"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/pgl_auth"]
38
+
39
+ [tool.pytest.ini_options]
40
+ pythonpath = ["src", "."]
41
+ testpaths = ["tests"]
@@ -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"
@@ -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())
@@ -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)
@@ -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,67 @@
1
+ """Testes do pacote pgl_auth (cliente HTTP usado pelos alunos)."""
2
+ from __future__ import annotations
3
+
4
+ import pytest
5
+
6
+ from pgl_auth.client import PGLAuthClient
7
+ from pgl_auth.exceptions import AuthenticationError, InactiveAccountError
8
+
9
+
10
+ class FakeResponse:
11
+ def __init__(self, status_code, json_data=None):
12
+ self.status_code = status_code
13
+ self._json_data = json_data or {}
14
+
15
+ def json(self):
16
+ return self._json_data
17
+
18
+ def raise_for_status(self):
19
+ if self.status_code >= 400:
20
+ import requests
21
+
22
+ raise requests.HTTPError(f"status {self.status_code}")
23
+
24
+
25
+ def test_login_success_returns_token_and_stores_it(monkeypatch):
26
+ def fake_post(url, json, timeout):
27
+ assert json == {"matricula": "202100001", "senha": "minha_senha"}
28
+ return FakeResponse(200, {"access_token": "token-abc", "expires_in": 14400})
29
+
30
+ monkeypatch.setattr("pgl_auth.client.requests.post", fake_post)
31
+
32
+ client = PGLAuthClient(api_url="https://example.test/api/login")
33
+ token = client.login("202100001", "minha_senha")
34
+
35
+ assert token == "token-abc"
36
+ assert client.token == "token-abc"
37
+ assert client.auth_header() == {"Authorization": "Bearer token-abc"}
38
+
39
+
40
+ def test_login_invalid_credentials_raises_authentication_error(monkeypatch):
41
+ monkeypatch.setattr(
42
+ "pgl_auth.client.requests.post",
43
+ lambda url, json, timeout: FakeResponse(401),
44
+ )
45
+
46
+ client = PGLAuthClient(api_url="https://example.test/api/login")
47
+ with pytest.raises(AuthenticationError):
48
+ client.login("202100001", "senha_errada")
49
+
50
+
51
+ def test_login_inactive_account_raises_inactive_account_error(monkeypatch):
52
+ monkeypatch.setattr(
53
+ "pgl_auth.client.requests.post",
54
+ lambda url, json, timeout: FakeResponse(403),
55
+ )
56
+
57
+ client = PGLAuthClient(api_url="https://example.test/api/login")
58
+ with pytest.raises(InactiveAccountError):
59
+ client.login("202100001", "minha_senha")
60
+
61
+
62
+ def test_auth_header_without_login_raises_error():
63
+ client = PGLAuthClient(api_url="https://example.test/api/login")
64
+ from pgl_auth.exceptions import PGLAuthError
65
+
66
+ with pytest.raises(PGLAuthError):
67
+ client.auth_header()
@@ -0,0 +1,98 @@
1
+ """Garante as regras de negócio de db/create_student.py:
2
+
3
+ 1. Só é possível criar/atualizar senha se a matrícula existir e estiver
4
+ ativa em pgl_proxy.students.
5
+ 2. Um registro existente em pgl_auth.students é sobrescrito (upsert), não
6
+ duplicado, quando o mesmo aluno é recriado.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import bcrypt
11
+ import pytest
12
+
13
+ from db.create_student import (
14
+ UPSERT_SQL,
15
+ StudentNotEligible,
16
+ ensure_can_create_password,
17
+ get_proxy_active_status,
18
+ hash_password,
19
+ upsert_auth_record,
20
+ )
21
+
22
+
23
+ class FakeCursor:
24
+ """Cursor falso que responde com uma fila de resultados pré-definida."""
25
+
26
+ def __init__(self, fetchone_result=None):
27
+ self._fetchone_result = fetchone_result
28
+ self.executed = []
29
+
30
+ def execute(self, sql, params=None):
31
+ self.executed.append((sql, params))
32
+
33
+ def fetchone(self):
34
+ return self._fetchone_result
35
+
36
+
37
+ # --- Regra 1: elegibilidade via pgl_proxy.students ---------------------------------
38
+
39
+
40
+ def test_get_proxy_active_status_returns_true_when_active():
41
+ cur = FakeCursor(fetchone_result=(True,))
42
+ assert get_proxy_active_status(cur, "202100001") is True
43
+
44
+
45
+ def test_get_proxy_active_status_returns_false_when_inactive():
46
+ cur = FakeCursor(fetchone_result=(False,))
47
+ assert get_proxy_active_status(cur, "202100001") is False
48
+
49
+
50
+ def test_get_proxy_active_status_returns_none_when_not_found():
51
+ cur = FakeCursor(fetchone_result=None)
52
+ assert get_proxy_active_status(cur, "inexistente") is None
53
+
54
+
55
+ def test_ensure_can_create_password_allows_active_student():
56
+ cur = FakeCursor(fetchone_result=(True,))
57
+ ensure_can_create_password(cur, "202100001") # não deve levantar
58
+
59
+
60
+ def test_ensure_can_create_password_blocks_missing_student():
61
+ cur = FakeCursor(fetchone_result=None)
62
+ with pytest.raises(StudentNotEligible, match="não encontrada"):
63
+ ensure_can_create_password(cur, "inexistente")
64
+
65
+
66
+ def test_ensure_can_create_password_blocks_inactive_student():
67
+ cur = FakeCursor(fetchone_result=(False,))
68
+ with pytest.raises(StudentNotEligible, match="inativa"):
69
+ ensure_can_create_password(cur, "202100001")
70
+
71
+
72
+ # --- Regra 2: upsert sobrescreve registro existente em pgl_auth --------------------
73
+
74
+
75
+ def test_upsert_auth_record_uses_on_conflict_do_update():
76
+ """A query precisa ser um upsert (ON CONFLICT DO UPDATE), não um INSERT simples,
77
+ para garantir que recriar um aluno já cadastrado sobrescreve o registro em vez
78
+ de falhar por violação de unicidade ou criar um duplicado."""
79
+ assert "ON CONFLICT" in UPSERT_SQL
80
+ assert "DO UPDATE" in UPSERT_SQL
81
+ assert "password_hash = EXCLUDED.password_hash" in UPSERT_SQL
82
+ assert "is_active = EXCLUDED.is_active" in UPSERT_SQL
83
+
84
+
85
+ def test_upsert_auth_record_sends_expected_params():
86
+ cur = FakeCursor()
87
+ upsert_auth_record(cur, "202100001", "hash-fake", True)
88
+ assert cur.executed == [(UPSERT_SQL, ("202100001", "hash-fake", True))]
89
+
90
+
91
+ # --- hashing -------------------------------------------------------------------
92
+
93
+
94
+ def test_hash_password_is_not_plaintext_and_verifies_with_bcrypt():
95
+ hashed = hash_password("minha_senha")
96
+ assert hashed != "minha_senha"
97
+ assert bcrypt.checkpw(b"minha_senha", hashed.encode("utf-8"))
98
+ assert not bcrypt.checkpw(b"senha_errada", hashed.encode("utf-8"))
@@ -0,0 +1,7 @@
1
+ {
2
+ "functions": {
3
+ "api/login.py": {
4
+ "runtime": "@vercel/python"
5
+ }
6
+ }
7
+ }