Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
SECRET_KEY=52a537b02391a583d9f00f975de1ed0406a628249effcd7d07d2928948546270
SECRET_KEY=troque-por-um-valor-gerado-com-openssl-rand-hex-32
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
# Endereço oficial; com ele, o endereço do Render redireciona para cá
PUBLIC_URL=
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<div align="center">

[![API Docs](https://img.shields.io/badge/🌐%20API%20Docs-009688?style=for-the-badge)](https://authservice-mbul.onrender.com/docs)
[![API Docs](https://img.shields.io/badge/🌐%20API%20Docs-009688?style=for-the-badge)](https://authservice.gcruz.dev.br/docs)
[![Licença](https://img.shields.io/badge/Licença-MIT-4ade80?style=for-the-badge)](./LICENSE)
[![Docker](https://img.shields.io/badge/Docker-Ready-2496ED?style=for-the-badge&logo=docker&logoColor=white)](./Dockerfile)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=for-the-badge&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
Expand All @@ -31,10 +31,11 @@

| | |
|---|---|
| 🔗 **Aplicação** | [authservice-mbul.onrender.com](https://authservice-mbul.onrender.com) |
| 📖 **API Docs** | [authservice-mbul.onrender.com/docs](https://authservice-mbul.onrender.com/docs) |
| 📡 **Health Check** | [authservice-mbul.onrender.com/health](https://authservice-mbul.onrender.com/health) |
| 🔗 **Aplicação** | [authservice.gcruz.dev.br](https://authservice.gcruz.dev.br) |
| 📖 **API Docs** | [authservice.gcruz.dev.br/docs](https://authservice.gcruz.dev.br/docs) |
| 📡 **Health Check** | [authservice.gcruz.dev.br/health](https://authservice.gcruz.dev.br/health) |
| ⚠️ **Aviso** | Hospedado no plano gratuito do Render — primeira requisição pode levar até **50 segundos** devido ao cold start |
| 🗂️ **Dados** | Os usuários ficam **em memória**: cada reinício ou cold start do servidor apaga as contas criadas |

</div>

Expand Down Expand Up @@ -231,20 +232,20 @@ Documentação interativa disponível em **`/docs`** após subir o serviço.

**Registrar usuário:**
```bash
curl -X POST https://authservice-mbul.onrender.com/register \
curl -X POST https://authservice.gcruz.dev.br/register \
-H "Content-Type: application/json" \
-d '{"email": "usuario@email.com", "password": "Senha123"}'
```

**Obter token:**
```bash
curl -X POST https://authservice-mbul.onrender.com/token \
curl -X POST https://authservice.gcruz.dev.br/token \
-d "username=usuario@email.com&password=Senha123"
```

**Acessar rota protegida:**
```bash
curl https://authservice-mbul.onrender.com/me \
curl https://authservice.gcruz.dev.br/me \
-H "Authorization: Bearer SEU_TOKEN_AQUI"
```

Expand All @@ -259,6 +260,7 @@ Crie um arquivo `.env` na raiz do projeto:
| `SECRET_KEY` | Chave secreta para assinar tokens JWT | — | ✅ Sim |
| `ALGORITHM` | Algoritmo de assinatura JWT | `HS256` | Não |
| `ACCESS_TOKEN_EXPIRE_MINUTES` | Expiração do token em minutos | `60` | Não |
| `PUBLIC_URL` | Endereço oficial (ex.: `https://authservice.gcruz.dev.br`). Quando definido, quem acessa pelo endereço `onrender.com` recebe um redirecionamento 308 para ele | vazio | Não |

**Exemplo `.env`:**
```env
Expand Down
5 changes: 5 additions & 0 deletions backend/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ class Settings(BaseSettings):
SECRET_KEY: str
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
# Endereço oficial (ex.: https://authservice.gcruz.dev.br). Com ele, quem
# chega pelo endereço do Render é redirecionado para cá.
PUBLIC_URL: str = ""
# Definida pelo próprio Render (ex.: authservice-mbul.onrender.com).
RENDER_EXTERNAL_HOSTNAME: str = ""

model_config = SettingsConfigDict(
env_file=".env",
Expand Down
25 changes: 24 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from backend.api.auth_routes import router as auth_router
from backend.core.config import settings
from backend.core.logger import get_logger
import os

Expand All @@ -20,6 +22,27 @@ async def lifespan(app: FastAPI):
lifespan=lifespan,
)

_public_url = settings.PUBLIC_URL.strip().rstrip("/")
_old_host = settings.RENDER_EXTERNAL_HOSTNAME.strip().lower()


@app.middleware("http")
async def redirect_old_host(request: Request, call_next):
"""Redireciona o endereço do Render (*.onrender.com) para PUBLIC_URL.

Só age quando as duas variáveis existem e o Host da requisição é o do
Render; o health check interno e o desenvolvimento local não mudam.
O 308 mantém o método e o corpo (POST /register, POST /token).
"""
host = request.headers.get("host", "").split(":")[0].lower()
if _public_url and _old_host and host == _old_host:
target = _public_url + request.url.path
if request.url.query:
target += "?" + request.url.query
return RedirectResponse(target, status_code=308)
return await call_next(request)


app.include_router(auth_router, tags=["Autenticação"])

# Caminho absoluto baseado em /code (WORKDIR do Docker)
Expand Down
28 changes: 0 additions & 28 deletions frontend/css/home.css
Original file line number Diff line number Diff line change
Expand Up @@ -122,34 +122,6 @@
border-right: none;
}

/* Senha inline */
.pass-mask {
letter-spacing: 4px;
font-size: 16px;
color: var(--color-text-secondary);
line-height: 1;
}

.pass-real {
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-accent);
}

.eye-inline {
background: none;
border: none;
cursor: pointer;
color: var(--color-text-muted);
font-size: 11px;
padding: 2px;
line-height: 1;
transition: color var(--transition);
flex-shrink: 0;
}

.eye-inline:hover { color: var(--color-accent); }

/* ── Token JWT ───────────────────────────────────────────────── */
.token-box {
background: var(--color-bg-primary);
Expand Down
35 changes: 0 additions & 35 deletions frontend/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -218,41 +218,6 @@ <h2 class="card-title">Dados Pessoais</h2>
>
<span class="dv" id="d-email">—</span>
</div>
<div class="data-row">
<span class="dk"
><i
class="fa-solid fa-lock"
aria-hidden="true"
></i>
Senha</span
>
<span class="dv">
<span
class="pass-mask"
id="pass-mask"
aria-hidden="true"
>••••••••</span
>
<span
class="pass-real"
id="pass-real"
style="display: none"
aria-label="Senha visível"
></span>
<button
class="eye-inline"
id="pass-eye-btn"
onclick="togglePassView()"
aria-label="Mostrar/ocultar senha"
>
<i
class="fa-regular fa-eye"
id="pass-eye-icon"
aria-hidden="true"
></i>
</button>
</span>
</div>
</div>
<div class="card-foot">
<button class="btn-sec" id="btn-me" onclick="loadMe()">
Expand Down
2 changes: 1 addition & 1 deletion frontend/js/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ const AuthPage = (() => {
const data = await res.json();

if (res.ok) {
Utils.Session.save(data.access_token, password, email);
Utils.Session.save(data.access_token, email);
Utils.showAlert(
"log-alert",
"✓ autenticado — redirecionando...",
Expand Down
29 changes: 1 addition & 28 deletions frontend/js/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@ const HomePage = (() => {
/* Estado local da página */
const state = {
token: null,
pass: null,
};

/* ── Inicialização ───────────────────────────────────────── */

function init() {
state.token = Utils.Session.token;
state.pass = Utils.Session.pass;

const noSession = document.getElementById("no-session");
const cardsGrid = document.querySelector(".cards-grid");
Expand Down Expand Up @@ -98,10 +96,6 @@ const HomePage = (() => {

// Dot online
document.getElementById("online-dot")?.classList.add("on");

// Senha real (apenas para exibição)
const passReal = document.getElementById("pass-real");
if (passReal && state.pass) passReal.textContent = state.pass;
}

/* ── Token JWT ───────────────────────────────────────────── */
Expand Down Expand Up @@ -141,33 +135,15 @@ const HomePage = (() => {

/* ── Mostrar/ocultar senha ───────────────────────────────── */

function togglePassView() {
const mask = document.getElementById("pass-mask");
const real = document.getElementById("pass-real");
const icon = document.getElementById("pass-eye-icon");
if (!mask || !real) return;

const isHidden = real.style.display === "none";
mask.style.display = isHidden ? "none" : "inline";
real.style.display = isHidden ? "inline" : "none";

if (icon) {
icon.className = isHidden
? "fa-regular fa-eye-slash"
: "fa-regular fa-eye";
}
}

/* ── Logout ──────────────────────────────────────────────── */

function logout() {
Utils.Session.clear();
state.token = null;
state.pass = null;
location.href = "index.html";
}

return { init, loadMe, copyToken, togglePassView, logout };
return { init, loadMe, copyToken, logout };
})();

/* ── Expõe globalmente para uso inline no HTML ─────────────── */
Expand All @@ -177,9 +153,6 @@ function loadMe() {
function copyToken() {
HomePage.copyToken();
}
function togglePassView() {
HomePage.togglePassView();
}
function logout() {
HomePage.logout();
}
Expand Down
10 changes: 8 additions & 2 deletions frontend/js/status.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const StatusPage = (() => {

function clearLog() {
const logBody = document.getElementById('status-log');
if (logBody) logBody.innerHTML = '';
if (logBody) logBody.replaceChildren();
}

/* ── Privado: status global (hero badge) ─────────────────── */
Expand Down Expand Up @@ -130,7 +130,13 @@ const StatusPage = (() => {

const line = document.createElement('div');
line.className = `log-line${type ? ` log-${type}` : ''}`;
line.innerHTML = `<span class="log-ts">${Utils.timestamp()}</span><span class="log-msg">${msg}</span>`;
const ts = document.createElement('span');
ts.className = 'log-ts';
ts.textContent = Utils.timestamp();
const text = document.createElement('span');
text.className = 'log-msg';
text.textContent = msg;
line.append(ts, text);
container.appendChild(line);

// Auto-scroll para o final
Expand Down
13 changes: 5 additions & 8 deletions frontend/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const Utils = (() => {
function showAlert(id, msg, type) {
const element = el(id);
if (!element) return;
element.innerHTML = msg;
element.textContent = msg;
element.className = `alert show ${type}`;
}

Expand All @@ -50,14 +50,14 @@ const Utils = (() => {
const element = el(id);
if (!element) return;
element.className = "alert";
element.innerHTML = "";
element.textContent = "";
}

/** Exibe alerta de página (temporário, 4s) */
function showPageAlert(id, msg, type) {
const element = el(id);
if (!element) return;
element.innerHTML = msg;
element.textContent = msg;
element.className = `alert page-alert show ${type}`;
setTimeout(() => element.classList.remove("show"), 4000);
}
Expand Down Expand Up @@ -150,16 +150,13 @@ const Utils = (() => {
get token() {
return _storage.getItem("auth_token");
},
get pass() {
return _storage.getItem("auth_pass");
},
get email() {
return _storage.getItem("auth_email");
},

save(token, pass, email) {
// A senha nunca é guardada no navegador: só o token e o e-mail.
save(token, email) {
_storage.setItem("auth_token", token);
_storage.setItem("auth_pass", pass);
_storage.setItem("auth_email", email);
},

Expand Down
Loading