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
9 changes: 8 additions & 1 deletion deploy/.env.production.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,11 @@ RABBITMQ_DEFAULT_PASS=replace-with-a-strong-rabbitmq-password
# Secrets.
JWT_SECRET=replace-with-a-strong-random-secret
JWT_ACCESS_TTL=15m
JWT_REFRESH_TTL=168h
JWT_REFRESH_TTL=168h

# Cookie settings.
COOKIE_SECURE=true

# Default admin account seeded on first startup.
ADMIN_USERNAME=admin
ADMIN_PASSWORD=replace-with-a-strong-admin-password
5 changes: 5 additions & 0 deletions deploy/docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ services:
REDIS_URL: redis://valkey:6379/0
RABBITMQ_URL: amqp://paca:paca@rabbitmq:5672/
JWT_SECRET: dev-change-in-production
JWT_ACCESS_TTL: 15m
JWT_REFRESH_TTL: 168h
COOKIE_SECURE: "false"
ADMIN_USERNAME: admin
ADMIN_PASSWORD: adminpassword
volumes:
- ../services/api:/workspace
- go_mod_cache:/go/pkg/mod
Expand Down
3 changes: 3 additions & 0 deletions deploy/docker-compose.prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ services:
JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET}
JWT_ACCESS_TTL: ${JWT_ACCESS_TTL:-15m}
JWT_REFRESH_TTL: ${JWT_REFRESH_TTL:-168h}
COOKIE_SECURE: ${COOKIE_SECURE:-true}
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?set ADMIN_PASSWORD}
depends_on:
postgres:
condition: service_healthy
Expand Down
10 changes: 5 additions & 5 deletions deploy/nginx/gateway.conf
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ server {
limit_req zone=auth burst=5 nodelay;
limit_req_status 429;

proxy_pass http://api_backend/v1/auth/;
proxy_pass http://api_backend/api/v1/auth/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
Expand All @@ -140,15 +140,15 @@ server {

# -- All other API routes -------------------------------------------------
#
# Strips the /api prefix before forwarding to the upstream:
# /api/v1/users → /v1/users
# /api/healthz → /healthz
# Forwards the /api prefix as-is to the upstream:
# /api/v1/users → /api/v1/users
# /api/healthz → /api/healthz

location /api/ {
limit_req zone=api burst=50 nodelay;
limit_req_status 429;

proxy_pass http://api_backend/;
proxy_pass http://api_backend/api/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
Expand Down
67 changes: 41 additions & 26 deletions docs/api/http-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ These routes already exist in the Go API service.
| Method | Path | Auth | Function |
|---|---|---|---|
| `GET` | `/healthz` | No | Liveness/health probe for infrastructure, containers, and local development. |
| `POST` | `/v1/auth/login` | No | Validate user credentials and issue an access token plus refresh token. |
| `POST` | `/v1/auth/refresh` | No | Exchange a valid refresh token for a new access token. |
| `POST` | `/v1/auth/logout` | Access token | Revoke the current authenticated token/session. |
| `POST` | `/v1/auth/login` | No | Validate user credentials and set access/refresh tokens as HttpOnly cookies. |
| `POST` | `/v1/auth/refresh` | No | Exchange refresh token cookie for rotated access/refresh token cookies. |
| `POST` | `/v1/auth/logout` | Access token | Revoke the current authenticated token/session and clear cookies. |
| `POST` | `/v1/users` | No | Register a new user account. |
| `GET` | `/v1/users/me` | Access token | Return the authenticated caller's own profile. |
| `PATCH` | `/v1/users/:id` | Access token | Update mutable profile fields for the specified user. Current implementation supports `name`. |
| `PATCH` | `/v1/users/:id` | Access token | Update mutable profile fields for the specified user. Current implementation supports `full_name`. |
| `DELETE` | `/v1/users/:id` | Access token + `ADMIN` role | Delete a user account. |

## Current Request and Response Contracts
Expand All @@ -121,14 +121,14 @@ These routes already exist in the Go API service.

Function:

- authenticate a user with email and password;
- return a fresh access token and refresh token pair.
- authenticate a user with username and password;
- set access and refresh tokens as HttpOnly cookies.

Request body:

```json
{
"email": "[email protected]",
"username": "alice",
"password": "secret123"
}
```
Expand All @@ -139,8 +139,7 @@ Success response:
{
"success": true,
"data": {
"access_token": "...",
"refresh_token": "..."
"message": "logged in"
},
"request_id": "..."
}
Expand All @@ -150,14 +149,20 @@ Success response:

Function:

- accept a refresh token;
- issue a new access token without requiring credentials again.
- read refresh token from HttpOnly cookie;
- issue a rotated access and refresh token pair as HttpOnly cookies.

Request body:
Request body: (empty - token read from cookie)

Success response:

```json
{
"refresh_token": "..."
"success": true,
"data": {
"message": "token refreshed"
},
"request_id": "..."
}
```

Expand All @@ -174,6 +179,18 @@ Headers:
Authorization: Bearer <access-token>
```

Success response:

```json
{
"success": true,
"data": {
"message": "logged out"
},
"request_id": "..."
}
```

### `POST /v1/users`

Function:
Expand All @@ -186,9 +203,9 @@ Request body:

```json
{
"email": "[email protected]",
"username": "alice",
"password": "secret123",
"name": "Alice"
"full_name": "Alice"
}
```

Expand All @@ -197,8 +214,8 @@ Success response data:
```json
{
"id": "uuid",
"email": "[email protected]",
"name": "Alice",
"username": "alice",
"full_name": "Alice",
"role": "USER",
"created_at": "2026-03-24T00:00:00Z"
}
Expand All @@ -216,13 +233,13 @@ Function:
Function:

- update mutable user profile fields;
- current implementation supports `name` only.
- current implementation supports `full_name` only.

Request body:

```json
{
"name": "Updated Name"
"full_name": "Updated Name"
}
```

Expand Down Expand Up @@ -347,12 +364,10 @@ To keep the API coherent and aligned with the current codebase, implement the ne

## Known Model Gaps

There is currently a mismatch between the documentation and the first implementation slice:

- [../architecture/database-schema.md](../architecture/database-schema.md) models integer IDs, `username`, and `full_name`.
- The implemented API and first SQL migration use UUID IDs plus `email`, `name`, and `role` fields.
The auth/user implementation is now aligned with the database schema:

Recommended rule:
- Users are identified by `username` (unique, required) and stored with `full_name`.
- Authentication uses `username` + password; there is no email field.
- UUIDs are used for all public resource identifiers.

- use the implemented auth/user contract as the near-term API baseline;
- update the database schema document before adding project/task endpoints so the storage model and HTTP contract move together.
The schema and HTTP contract are consistent. Before adding the next slice (projects/tasks), update [../architecture/database-schema.md](../architecture/database-schema.md) first so storage model and HTTP contract continue to move together.
57 changes: 54 additions & 3 deletions services/api/internal/bootstrap/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ package bootstrap

import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"time"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/paca/api/internal/config"
userdom "github.com/paca/api/internal/domain/user"
"github.com/paca/api/internal/platform/authz"
"github.com/paca/api/internal/platform/cache"
"github.com/paca/api/internal/platform/database"
Expand All @@ -23,6 +26,7 @@ import (
usersvc "github.com/paca/api/internal/service/user"
"github.com/paca/api/internal/transport/http/handler"
"github.com/paca/api/internal/transport/http/router"
"golang.org/x/crypto/bcrypt"
)

// App holds the HTTP server and any resources that need graceful shutdown.
Expand Down Expand Up @@ -61,18 +65,29 @@ func New(cfg *config.Config) (*App, error) {

// --- Repositories -------------------------------------------------------
userRepo := pgRepo.NewUserRepository(db)
blacklist := redisRepo.NewTokenBlacklist(redisClient)
refreshStore := redisRepo.NewRefreshTokenStore(redisClient)

// --- Admin seeding -------------------------------------------------------
if err := seedAdmin(context.Background(), userRepo, cfg.Admin, log); err != nil {
return nil, fmt.Errorf("bootstrap: %w", err)
}

// --- Services -----------------------------------------------------------
authService := authsvc.New(userRepo, tokenManager, blacklist, cfg.JWT.RefreshTTL)
authService := authsvc.New(userRepo, tokenManager, refreshStore, cfg.JWT.RefreshTTL)
userService := usersvc.New(userRepo)

// --- Handlers -----------------------------------------------------------
cookieCfg := handler.CookieConfig{
Secure: cfg.Server.CookieSecure,
AccessTTL: cfg.JWT.AccessTTL,
RefreshTTL: cfg.JWT.RefreshTTL,
}

deps := router.Deps{
TokenManager: tokenManager,
AuthzPolicy: policy,
Health: handler.NewHealthHandler(),
Auth: handler.NewAuthHandler(authService),
Auth: handler.NewAuthHandler(authService, cookieCfg),
User: handler.NewUserHandler(userService),
Log: log,
}
Expand Down Expand Up @@ -106,3 +121,39 @@ func (a *App) Shutdown(ctx context.Context) error {
}
return a.server.Shutdown(ctx)
}

// seedAdmin ensures the default admin account exists in the database.
// If the account already exists it is left unchanged.
func seedAdmin(ctx context.Context, repo userdom.Repository, cfg config.AdminConfig, log *slog.Logger) error {
_, err := repo.FindByUsername(ctx, cfg.Username)
if err == nil {
// Admin already exists — nothing to do.
return nil
}
if !errors.Is(err, userdom.ErrNotFound) {
return fmt.Errorf("seed admin: lookup: %w", err)
}

hash, err := bcrypt.GenerateFromPassword([]byte(cfg.Password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("seed admin: hash password: %w", err)
}

now := time.Now()
admin := &userdom.User{
ID: uuid.New(),
Username: cfg.Username,
PasswordHash: string(hash),
FullName: "Admin",
Role: userdom.RoleAdmin,
CreatedAt: now,
UpdatedAt: now,
}

if err := repo.Create(ctx, admin); err != nil {
return fmt.Errorf("seed admin: create: %w", err)
}

log.Info("admin account created", "username", cfg.Username)
return nil
}
10 changes: 9 additions & 1 deletion services/api/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,20 @@ type Config struct {
Redis RedisConfig
RabbitMQ RabbitMQConfig
JWT JWTConfig
Admin AdminConfig
Env string // development | production
}

// ServerConfig holds HTTP server settings.
type ServerConfig struct {
Port string
Port string
CookieSecure bool // set Secure flag on auth cookies; enable when behind an SSL-terminating proxy
}

// AdminConfig holds the default administrator credentials seeded on first startup.
type AdminConfig struct {
Username string
Password string
}

// DatabaseConfig holds the primary database connection settings.
Expand Down
23 changes: 22 additions & 1 deletion services/api/internal/config/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"os"
"strconv"
"time"

"github.com/joho/godotenv"
Expand All @@ -27,6 +28,11 @@ func Load() (*Config, error) {
return nil, fmt.Errorf("config: JWT_REFRESH_TTL: %w", err)
}

cookieSecure, err := strconv.ParseBool(env("COOKIE_SECURE", "false"))
if err != nil {
return nil, fmt.Errorf("config: COOKIE_SECURE: %w", err)
}

// Collect all missing required keys before returning so the caller sees
// every problem in a single error rather than one failure at a time.
var errs []error
Expand All @@ -51,14 +57,25 @@ func Load() (*Config, error) {
errs = append(errs, err)
}

adminUser, err := requireEnv("ADMIN_USERNAME")
if err != nil {
errs = append(errs, err)
}

adminPass, err := requireEnv("ADMIN_PASSWORD")
if err != nil {
errs = append(errs, err)
}

if len(errs) > 0 {
return nil, errors.Join(errs...)
}

return &Config{
Env: env("ENV", "development"),
Server: ServerConfig{
Port: env("PORT", "8080"),
Port: env("PORT", "8080"),
CookieSecure: cookieSecure,
},
Comment thread
pikann marked this conversation as resolved.
Resolved
Database: DatabaseConfig{
DSN: dsn,
Expand All @@ -74,6 +91,10 @@ func Load() (*Config, error) {
AccessTTL: accessTTL,
RefreshTTL: refreshTTL,
},
Admin: AdminConfig{
Username: adminUser,
Password: adminPass,
},
}, nil
}

Expand Down
Loading
Loading