feat: autenticação com cookie de sessão + tela de login Arcade Neon
- Go: middleware RequireAuth protege todas as rotas /api/* - Go: POST /api/login valida APP_USERNAME/APP_PASSWORD e emite cookie HttpOnly 30 dias - Go: GET /api/auth/me e POST /api/logout - Vue: LoginView com design Arcade Neon - Vue: router guard redireciona para /login se não autenticado - Vue: api.ts redireciona para /login em qualquer 401 - docker-compose: APP_USERNAME e APP_PASSWORD como env vars Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"financeiro-carvalho/internal/db"
|
||||
"financeiro-carvalho/internal/handler"
|
||||
authmw "financeiro-carvalho/internal/middleware"
|
||||
"financeiro-carvalho/internal/migration"
|
||||
"financeiro-carvalho/internal/repository"
|
||||
"financeiro-carvalho/internal/service"
|
||||
@@ -78,7 +79,12 @@ func main() {
|
||||
|
||||
r.Get("/health", handler.Health)
|
||||
|
||||
r.Post("/api/login", authmw.LoginHandler)
|
||||
r.Post("/api/logout", authmw.LogoutHandler)
|
||||
r.Get("/api/auth/me", authmw.MeHandler)
|
||||
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Use(authmw.RequireAuth)
|
||||
r.Get("/categories", categoryHandler.List)
|
||||
r.Post("/categories", categoryHandler.Create)
|
||||
r.Put("/categories/{id}", categoryHandler.Update)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cookieName = "cf_session"
|
||||
|
||||
var (
|
||||
mu sync.RWMutex
|
||||
sessions = map[string]time.Time{}
|
||||
)
|
||||
|
||||
func newToken() string {
|
||||
b := make([]byte, 32)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
func validSession(token string) bool {
|
||||
mu.RLock()
|
||||
defer mu.RUnlock()
|
||||
exp, ok := sessions[token]
|
||||
return ok && time.Now().Before(exp)
|
||||
}
|
||||
|
||||
func RequireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie(cookieName)
|
||||
if err != nil || !validSession(cookie.Value) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "corpo inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
wantUser := os.Getenv("APP_USERNAME")
|
||||
wantPass := os.Getenv("APP_PASSWORD")
|
||||
if wantUser == "" || body.Username != wantUser || body.Password != wantPass {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "credenciais inválidas"})
|
||||
return
|
||||
}
|
||||
|
||||
token := newToken()
|
||||
mu.Lock()
|
||||
sessions[token] = time.Now().Add(30 * 24 * time.Hour)
|
||||
mu.Unlock()
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
MaxAge: 30 * 24 * 60 * 60,
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{"ok": "true"})
|
||||
}
|
||||
|
||||
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if cookie, err := r.Cookie(cookieName); err == nil {
|
||||
mu.Lock()
|
||||
delete(sessions, cookie.Value)
|
||||
mu.Unlock()
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func MeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie(cookieName)
|
||||
if err != nil || !validSession(cookie.Value) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import HomeView from '../views/HomeView.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'login',
|
||||
component: () => import('../views/LoginView.vue'),
|
||||
meta: { public: true },
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
name: 'home',
|
||||
@@ -42,4 +49,11 @@ const router = createRouter({
|
||||
],
|
||||
})
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
if (to.meta.public) return true
|
||||
const auth = useAuthStore()
|
||||
const ok = await auth.check()
|
||||
if (!ok) return { name: 'login' }
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import router from '@/router'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
@@ -6,6 +8,10 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
|
||||
headers: body ? { 'Content-Type': 'application/json' } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
if (res.status === 401) {
|
||||
router.push({ name: 'login' })
|
||||
throw new Error('Sessão expirada')
|
||||
}
|
||||
if (res.status === 204) return undefined as T
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error ?? 'Erro desconhecido')
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const checked = ref(false)
|
||||
const authenticated = ref(false)
|
||||
|
||||
async function check(): Promise<boolean> {
|
||||
if (checked.value) return authenticated.value
|
||||
try {
|
||||
const res = await fetch('/api/auth/me')
|
||||
authenticated.value = res.status === 204
|
||||
} catch {
|
||||
authenticated.value = false
|
||||
}
|
||||
checked.value = true
|
||||
return authenticated.value
|
||||
}
|
||||
|
||||
async function login(username: string, password: string): Promise<void> {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = await res.json()
|
||||
throw new Error(data.error ?? 'Erro ao fazer login')
|
||||
}
|
||||
authenticated.value = true
|
||||
checked.value = true
|
||||
}
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
await fetch('/api/logout', { method: 'POST' })
|
||||
authenticated.value = false
|
||||
checked.value = false
|
||||
}
|
||||
|
||||
return { checked, authenticated, check, login, logout }
|
||||
})
|
||||
@@ -0,0 +1,183 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
loading.value = true
|
||||
try {
|
||||
await auth.login(username.value, password.value)
|
||||
router.push('/')
|
||||
} catch (e: any) {
|
||||
error.value = e.message ?? 'Erro desconhecido'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<div class="login-card">
|
||||
<div class="login-title">
|
||||
<span class="fc-pixel title-text">CARVALHO</span>
|
||||
<span class="fc-pixel title-sub">FINANCE · v1.0</span>
|
||||
</div>
|
||||
|
||||
<form class="login-form" @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label class="fc-pixel field-label">USUÁRIO</label>
|
||||
<input
|
||||
v-model="username"
|
||||
type="text"
|
||||
class="login-input"
|
||||
autocomplete="username"
|
||||
:disabled="loading"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="fc-pixel field-label">SENHA</label>
|
||||
<input
|
||||
v-model="password"
|
||||
type="password"
|
||||
class="login-input"
|
||||
autocomplete="current-password"
|
||||
:disabled="loading"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="login-error fc-pixel">{{ error }}</div>
|
||||
|
||||
<button type="submit" class="login-btn fc-pixel" :disabled="loading">
|
||||
{{ loading ? 'ENTRANDO...' : '▶ ENTRAR' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--fc-bg);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
background: var(--fc-bg-panel);
|
||||
border: 2px solid var(--fc-accent-3);
|
||||
border-radius: 8px;
|
||||
padding: 2.5rem 2rem;
|
||||
box-shadow:
|
||||
0 0 24px rgb(var(--fc-accent-3-rgb) / 0.3),
|
||||
0 0 8px rgb(var(--fc-accent-3-rgb) / 0.15);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.title-text {
|
||||
font-size: 1rem;
|
||||
color: var(--fc-accent-2);
|
||||
text-shadow: 0 0 10px var(--fc-accent-2);
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 0.45rem;
|
||||
color: var(--fc-text-dim);
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
font-size: 0.45rem;
|
||||
color: var(--fc-text-dim);
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.login-input {
|
||||
background: var(--fc-bg-raised);
|
||||
border: 1px solid var(--fc-panel-edge);
|
||||
border-radius: 4px;
|
||||
color: var(--fc-text);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.login-input:focus {
|
||||
border-color: var(--fc-accent-3);
|
||||
box-shadow: 0 0 6px rgb(var(--fc-accent-3-rgb) / 0.4);
|
||||
}
|
||||
|
||||
.login-input:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.login-error {
|
||||
font-size: 0.4rem;
|
||||
color: var(--fc-red);
|
||||
text-align: center;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
background: var(--fc-accent-3);
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
color: var(--fc-bg);
|
||||
cursor: pointer;
|
||||
font-size: 0.5rem;
|
||||
letter-spacing: 1px;
|
||||
padding: 0.75rem;
|
||||
transition: opacity 0.15s, box-shadow 0.15s;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.login-btn:hover:not(:disabled) {
|
||||
box-shadow: 0 0 12px rgb(var(--fc-accent-3-rgb) / 0.6);
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.login-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
+9
-2
@@ -17,14 +17,21 @@ services:
|
||||
app:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${APP_PORT:-8080}:8080"
|
||||
environment:
|
||||
DATABASE_URL: postgres://financeiro:${POSTGRES_PASSWORD:-financeiro}@postgres:5432/financeiro?sslmode=disable
|
||||
PORT: 8080
|
||||
APP_USERNAME: ${APP_USERNAME}
|
||||
APP_PASSWORD: ${APP_PASSWORD}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- default
|
||||
- dokploy-network
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
networks:
|
||||
dokploy-network:
|
||||
external: true
|
||||
|
||||
Reference in New Issue
Block a user