feat: multi-usuário com autenticação JWT

- Tabela `profiles` + coluna `profile_id` em todas as entidades
  (categories, transactions, recurring_expenses, accounts, player_profile,
   xp_events, player_quests, player_achievements, player_cosmetics)
- Dados existentes migrados para profile_id = 1 (Manoel)
- CLI `./api create-user --name <n> --password <p>` cria perfil com
  seed de categorias e player_profile; faz upsert de senha se já existir
- Auth substituída: cookie+APP_PASSWORD → JWT Bearer 24h (HS256)
- Middleware RequireAuth injeta profile_id no context de todas as rotas
- Todos os repositórios filtram por profile_id do context
- Endpoints: POST /api/auth/login, GET /api/auth/me,
  POST /api/auth/change-password, POST /api/logout
- Frontend: auth store usa localStorage (fc_token/fc_profile),
  api.ts envia Authorization header, LoginView usa campo name
- SettingsView reescrita com troca de senha e logout
- docker-compose.yml: remove APP_USERNAME/APP_PASSWORD, adiciona JWT_SECRET

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
2026-05-27 20:04:44 -03:00
co-authored by Claude Sonnet 4.6
parent 50637bd590
commit acbce4edc0
49 changed files with 2662 additions and 382 deletions
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"financeiro-carvalho/internal/middleware"
"financeiro-carvalho/internal/model"
)
@@ -17,7 +18,6 @@ type ManualTransactionRepository interface {
Update(ctx context.Context, t model.Transaction) (*model.Transaction, error)
Delete(ctx context.Context, id int) error
DeleteByMonth(ctx context.Context, month string) (int, error)
// HasMatchingTransaction checks if a category has a transaction of the given type in the given month.
HasMatchingTransaction(ctx context.Context, categoryID *int, month string, amount float64, txType string) (bool, error)
}
@@ -28,12 +28,13 @@ func NewManualTransactionRepository(db *pgxpool.Pool) ManualTransactionRepositor
}
func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
query := `
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
FROM transactions`
args := []any{}
FROM transactions WHERE profile_id = $1`
args := []any{pid}
if month != "" {
query += ` WHERE TO_CHAR(date, 'YYYY-MM') = $1`
query += ` AND TO_CHAR(date, 'YYYY-MM') = $2`
args = append(args, month)
}
query += ` ORDER BY date DESC, id DESC`
@@ -56,10 +57,11 @@ func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transact
}
func (r *manualTxRepo) GetByID(ctx context.Context, id int) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var t model.Transaction
err := r.db.QueryRow(ctx, `
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
FROM transactions WHERE id = $1`, id).
FROM transactions WHERE id = $1 AND profile_id = $2`, id, pid).
Scan(&t.ID, &t.Date, &t.Amount, &t.Description, &t.Type, &t.Source, &t.CategoryID, &t.AccountID, &t.CreatedAt, &t.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@@ -68,24 +70,26 @@ func (r *manualTxRepo) GetByID(ctx context.Context, id int) (*model.Transaction,
}
func (r *manualTxRepo) Create(ctx context.Context, t model.Transaction) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var out model.Transaction
err := r.db.QueryRow(ctx, `
INSERT INTO transactions (date, amount, description, type, source, category_id, account_id)
VALUES ($1, $2, $3, $4, 'manual', $5, $6)
INSERT INTO transactions (date, amount, description, type, source, category_id, account_id, profile_id)
VALUES ($1, $2, $3, $4, 'manual', $5, $6, $7)
RETURNING id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at`,
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID).
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID, pid).
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.AccountID, &out.CreatedAt, &out.UpdatedAt)
return &out, err
}
func (r *manualTxRepo) Update(ctx context.Context, t model.Transaction) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var out model.Transaction
err := r.db.QueryRow(ctx, `
UPDATE transactions
SET date=$1, amount=$2, description=$3, type=$4, category_id=$5, account_id=$6, updated_at=NOW()
WHERE id=$7 AND source='manual'
WHERE id=$7 AND source='manual' AND profile_id=$8
RETURNING id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at`,
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID, t.ID).
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID, t.ID, pid).
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.AccountID, &out.CreatedAt, &out.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
@@ -94,7 +98,8 @@ func (r *manualTxRepo) Update(ctx context.Context, t model.Transaction) (*model.
}
func (r *manualTxRepo) Delete(ctx context.Context, id int) error {
tag, err := r.db.Exec(ctx, `DELETE FROM transactions WHERE id = $1`, id)
pid := middleware.ProfileIDFromCtx(ctx)
tag, err := r.db.Exec(ctx, `DELETE FROM transactions WHERE id = $1 AND profile_id = $2`, id, pid)
if err != nil {
return err
}
@@ -105,7 +110,9 @@ func (r *manualTxRepo) Delete(ctx context.Context, id int) error {
}
func (r *manualTxRepo) DeleteByMonth(ctx context.Context, month string) (int, error) {
tag, err := r.db.Exec(ctx, `DELETE FROM transactions WHERE TO_CHAR(date, 'YYYY-MM') = $1`, month)
pid := middleware.ProfileIDFromCtx(ctx)
tag, err := r.db.Exec(ctx,
`DELETE FROM transactions WHERE TO_CHAR(date, 'YYYY-MM') = $1 AND profile_id = $2`, month, pid)
if err != nil {
return 0, err
}
@@ -114,16 +121,17 @@ func (r *manualTxRepo) DeleteByMonth(ctx context.Context, month string) (int, er
func (r *manualTxRepo) HasMatchingTransaction(ctx context.Context, categoryID *int, month string, amount float64, txType string) (bool, error) {
if categoryID == nil {
// No category set — cannot auto-match, always report as uncovered
return false, nil
}
pid := middleware.ProfileIDFromCtx(ctx)
var count int
err := r.db.QueryRow(ctx, `
SELECT COUNT(*) FROM transactions
WHERE category_id = $1
AND TO_CHAR(date, 'YYYY-MM') = $2
AND type = $3
AND amount BETWEEN $4 * 0.9 AND $4 * 1.1`,
*categoryID, month, txType, amount).Scan(&count)
AND amount BETWEEN $4 * 0.9 AND $4 * 1.1
AND profile_id = $5`,
*categoryID, month, txType, amount, pid).Scan(&count)
return count > 0, err
}