Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eaa31efd64 | |||
| b0356bf103 |
@@ -23,20 +23,20 @@ Rules:
|
|||||||
| Layer | Package | Purpose | Status |
|
| Layer | Package | Purpose | Status |
|
||||||
|-------|---------|---------|--------|
|
|-------|---------|---------|--------|
|
||||||
| **CLI** | `cmd` | Cobra root command | 🛠 WIP |
|
| **CLI** | `cmd` | Cobra root command | 🛠 WIP |
|
||||||
| | `cmd/serve.go` | `mygo serve` — wire deps, start HTTP | 🛠 WIP |
|
| | `cmd/serve.go` | `mygo serve` — wire deps, start HTTP | ✅ |
|
||||||
| | `cmd/config.go` | `mygo config` — config subcommand | 🛠 WIP |
|
| | `cmd/config.go` | `mygo config` — config subcommand | 🛠 WIP |
|
||||||
| | `cmd/status.go` | `mygo status` — health check | 🛠 WIP |
|
| | `cmd/status.go` | `mygo status` — health check | 🛠 WIP |
|
||||||
| **Config** | `internal/config` | Viper load (YAML + env + flags) | 🛠 WIP |
|
| **Config** | `internal/config` | Viper load (YAML + env + flags), typed Duration config via built-in decode hook | ✅ |
|
||||||
| **App** | `internal/app` | Runtime dependency container and build metadata | 🛠 WIP |
|
| **App** | `internal/app` | Runtime dependency container and build metadata | 🛠 WIP |
|
||||||
| **HTTP** | `internal/server` | Gin router init, route registration, graceful shutdown | 🛠 WIP |
|
| **HTTP** | `internal/server` | Gin router init, route registration (public/protected split), graceful shutdown | ✅ |
|
||||||
| | `internal/handler` | HTTP handlers (auth, file, admin, webdav...) | 🛠 WIP |
|
| | `internal/handler` | HTTP handlers (auth, file, admin, webdav...) | 🛠 WIP |
|
||||||
| | `internal/middleware` | Gin middleware (logger, cors, auth) | 🛠 WIP |
|
| | `internal/middleware` | Gin middleware (logger, jwt, cors, auth) | 🛠 WIP |
|
||||||
| **Business** | `internal/service` | Business logic (auth, file, admin) | 🛠 WIP |
|
| **Business** | `internal/service` | Business logic: `AuthService` (register, login, refresh, logout, passkey CRUD) | ✅ |
|
||||||
| | `internal/model` | Domain types (User, File, errors) | 🛠 WIP |
|
| | `internal/model` | Domain types (User, File, Credential, Session), error codes | ✅ |
|
||||||
| **Data** | `internal/repository` | Repository interfaces + GORM implementations | 🛠 WIP |
|
| **Data** | `internal/repository` | Repository interfaces + GORM implementations (User, Session, File, Credential) | ✅ |
|
||||||
| | `internal/storage` | Storage backend interface + local disk impl | 🛠 WIP |
|
| | `internal/storage` | Storage backend interface + local disk impl | 🛠 WIP |
|
||||||
| **Util** | `internal/auth` | JWT sign/verify, context helpers | 🛠 WIP |
|
| **Util** | `internal/auth` | JWT sign/verify (HS256), token type discrimination (access/refresh), password hashing (bcrypt), app passkey tokens | ✅ |
|
||||||
| | `internal/api` | Error body helpers | 🛠 WIP |
|
| | `internal/api` | Unified JSON error response helpers | ✅ |
|
||||||
|
|
||||||
## API Routes (v0)
|
## API Routes (v0)
|
||||||
|
|
||||||
@@ -76,7 +76,8 @@ Applied to protected groups: auth (JWT validation, inject user into gin.Context)
|
|||||||
|
|
||||||
## Server Responsibilities
|
## Server Responsibilities
|
||||||
|
|
||||||
- `cmd/serve.go` loads config, creates `app.WebApp`, builds the router, and starts the HTTP server.
|
- `cmd/serve.go` loads config, calls `app.Bootstrap` to initialize DB + services, builds the router, and starts the HTTP server.
|
||||||
- `app.WebApp` carries runtime dependencies and build metadata needed to assemble handlers.
|
- `app.WebApp` carries runtime dependencies and build metadata needed to assemble handlers.
|
||||||
- `internal/server` owns Gin router setup (`router.go`), route registration split into `routes_public.go` and `routes_protected.go`, and HTTP server lifecycle.
|
- `internal/server` owns Gin router setup (`router.go`), route registration split into `routes_public.go` (public auth) and `routes_protected.go` (JWT-protected account).
|
||||||
|
- Each route group creates its own handler instance: `routes_public.go` creates `AuthHandler`, `routes_protected.go` creates `AccountHandler` — no shared handler state between public and protected routes.
|
||||||
- `RunWithGracefulShutdown` stops accepting new requests on termination and gives in-flight requests time to finish.
|
- `RunWithGracefulShutdown` stops accepting new requests on termination and gives in-flight requests time to finish.
|
||||||
|
|||||||
@@ -48,3 +48,20 @@
|
|||||||
- Version is build metadata from `internal/app/version.go`, not a config-file field.
|
- Version is build metadata from `internal/app/version.go`, not a config-file field.
|
||||||
- `app.WebApp` is the place to add future services, repositories, storage, and app metadata incrementally.
|
- `app.WebApp` is the place to add future services, repositories, storage, and app metadata incrementally.
|
||||||
- Request ID middleware is not part of the current foundation; add it only with a logging/tracing/error-correlation design.
|
- Request ID middleware is not part of the current foundation; add it only with a logging/tracing/error-correlation design.
|
||||||
|
|
||||||
|
## 2026-04-29: Auth Refinements
|
||||||
|
|
||||||
|
**Context**: Auth layer had three structural weaknesses — handler duplication, indistinguishable token types, and fragile config duration parsing.
|
||||||
|
|
||||||
|
**Decisions**:
|
||||||
|
|
||||||
|
| Decision | Guidance |
|
||||||
|
|----------|----------|
|
||||||
|
| One handler per route group | `AuthHandler` owns `/auth/*` (public); `AccountHandler` owns `/account/*` (protected). A route group maps 1:1 to a handler type. |
|
||||||
|
| JWT `type` claim | `Claims.Type` distinguishes access from refresh tokens. Middleware and service enforce the correct type at their respective boundaries. `ParseToken` does no type check — it verifies cryptographic validity only. |
|
||||||
|
| `time.Duration` in config structs | Config fields representing durations use `time.Duration` directly. Viper's built-in `StringToTimeDurationHookFunc` handles string→Duration conversion at unmarshal time. No accessor methods, no runtime parsing. Invalid values fail at startup via `Load()`. |
|
||||||
|
|
||||||
|
**Consequences**:
|
||||||
|
- Handlers are independently extensible (caching, rate limiting scoped per handler).
|
||||||
|
- Refresh tokens cannot authenticate API requests; access tokens cannot be used to issue new token pairs.
|
||||||
|
- New duration config fields require zero boilerplate — declare as `time.Duration` in the struct.
|
||||||
|
|||||||
@@ -26,12 +26,35 @@ go vet ./...
|
|||||||
go fmt ./...
|
go fmt ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go mod tidy # after adding/removing imports
|
||||||
|
```
|
||||||
|
|
||||||
## Config
|
## Config
|
||||||
|
|
||||||
Server config is in `config.yaml` (symlink to `config.example.yaml` in development environment).
|
Server config is loaded via viper from `config.yaml` (defaults in `internal/config/load.go`).
|
||||||
|
|
||||||
```
|
```yaml
|
||||||
server:
|
server:
|
||||||
host: 0.0.0.0
|
host: 0.0.0.0
|
||||||
port: 10086
|
port: 10086
|
||||||
|
|
||||||
|
database:
|
||||||
|
driver: sqlite3
|
||||||
|
sqlite:
|
||||||
|
path: data/mygo.db
|
||||||
|
|
||||||
|
storage:
|
||||||
|
driver: local
|
||||||
|
local:
|
||||||
|
path: data/files
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
secret: changeme-in-production
|
||||||
|
access_ttl: 15m
|
||||||
|
refresh_ttl: 168h
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Environment variables use `MYGO_` prefix with underscore separators: `MYGO_SERVER_PORT=8080`, `MYGO_JWT_SECRET=...`
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
| Feature | Status | Notes |
|
| Feature | Status | Notes |
|
||||||
|---------|--------|-------|
|
|---------|--------|-------|
|
||||||
| CLI config management | ✅ | |
|
| CLI config management | ✅ | Viper YAML + env + flags, typed Duration config |
|
||||||
| JWT authentication | ✅ | access + refresh tokens, refresh token in DB, app passkey support |
|
| JWT authentication | ✅ | access + refresh tokens, refresh token in DB, app passkey support |
|
||||||
| Web API foundation | ✅ | WebApp composition, Gin router, graceful shutdown, `GET /api/v1/version` |
|
| Web API foundation | ✅ | WebApp composition, Gin router, graceful shutdown, `GET /api/v1/version` |
|
||||||
| File upload/download/manage APIs | 🛠 WIP | REST API via Gin |
|
| File upload/download/manage APIs | 🛠 WIP | REST API via Gin |
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
Package-level implementation order (each task includes unit tests):
|
Package-level implementation order (each task includes unit tests):
|
||||||
|
|
||||||
1. `internal/config` — Viper loader, config struct
|
1. `internal/config` — Viper loader, config struct ✅
|
||||||
2. `internal/app` — runtime dependency container ✅
|
2. `internal/app` — runtime dependency container ✅
|
||||||
3. `internal/model` — domain types, error codes ✅
|
3. `internal/model` — domain types, error codes ✅
|
||||||
4. `internal/api` — error response helpers ✅
|
4. `internal/api` — error response helpers ✅
|
||||||
@@ -24,7 +24,7 @@ Package-level implementation order (each task includes unit tests):
|
|||||||
7. `internal/repository` — interfaces + GORM/SQLite impl ✅
|
7. `internal/repository` — interfaces + GORM/SQLite impl ✅
|
||||||
8. `internal/service` — auth, file, admin services ✅ (auth done)
|
8. `internal/service` — auth, file, admin services ✅ (auth done)
|
||||||
9. `internal/middleware` — logger, cors, auth ✅ (auth done)
|
9. `internal/middleware` — logger, cors, auth ✅ (auth done)
|
||||||
10. `internal/handler` — auth, file, admin handlers ✅ (auth done)
|
10. `internal/handler` — auth, account, file, admin handlers 🛠 (auth + account done)
|
||||||
11. `internal/server` — Gin router, route registration, graceful shutdown ✅
|
11. `internal/server` — Gin router, route registration, graceful shutdown ✅
|
||||||
12. `cmd/serve.go`, `cmd/config.go`, `cmd/status.go` ✅ (serve done)
|
12. `cmd/serve.go`, `cmd/config.go`, `cmd/status.go` ✅ (serve done)
|
||||||
13. Integration tests
|
13. Integration tests
|
||||||
|
|||||||
107
internal/handler/account.go
Normal file
107
internal/handler/account.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/dhao2001/mygo/internal/api"
|
||||||
|
"github.com/dhao2001/mygo/internal/middleware"
|
||||||
|
"github.com/dhao2001/mygo/internal/model"
|
||||||
|
"github.com/dhao2001/mygo/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AccountHandler handles authenticated account endpoints.
|
||||||
|
type AccountHandler struct {
|
||||||
|
authService *service.AuthService
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAccountHandler creates an AccountHandler.
|
||||||
|
func NewAccountHandler(authService *service.AuthService) *AccountHandler {
|
||||||
|
return &AccountHandler{authService: authService}
|
||||||
|
}
|
||||||
|
|
||||||
|
type createPasskeyRequest struct {
|
||||||
|
Label string `json:"label" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAccount handles GET /api/v1/account.
|
||||||
|
func (h *AccountHandler) GetAccount(c *gin.Context) {
|
||||||
|
userID := middleware.GetUserID(c)
|
||||||
|
if userID == "" {
|
||||||
|
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"user_id": userID})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPasskeys handles GET /api/v1/account/passkeys.
|
||||||
|
func (h *AccountHandler) ListPasskeys(c *gin.Context) {
|
||||||
|
userID := middleware.GetUserID(c)
|
||||||
|
if userID == "" {
|
||||||
|
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
creds, err := h.authService.ListPasskeys(c.Request.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
api.Error(c, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if creds == nil {
|
||||||
|
creds = []model.Credential{}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, creds)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreatePasskey handles POST /api/v1/account/passkeys.
|
||||||
|
func (h *AccountHandler) CreatePasskey(c *gin.Context) {
|
||||||
|
userID := middleware.GetUserID(c)
|
||||||
|
if userID == "" {
|
||||||
|
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req createPasskeyRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pk, err := h.authService.CreatePasskey(c.Request.Context(), userID, req.Label)
|
||||||
|
if err != nil {
|
||||||
|
api.Error(c, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, pk)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokePasskey handles DELETE /api/v1/account/passkeys/:id.
|
||||||
|
func (h *AccountHandler) RevokePasskey(c *gin.Context) {
|
||||||
|
userID := middleware.GetUserID(c)
|
||||||
|
if userID == "" {
|
||||||
|
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
passkeyID := c.Param("id")
|
||||||
|
if passkeyID == "" {
|
||||||
|
api.Error(c, http.StatusBadRequest, "missing passkey id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.authService.RevokePasskey(c.Request.Context(), userID, passkeyID); err != nil {
|
||||||
|
if err == model.ErrForbidden {
|
||||||
|
api.Error(c, http.StatusForbidden, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
api.Error(c, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
157
internal/handler/account_test.go
Normal file
157
internal/handler/account_test.go
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/dhao2001/mygo/internal/middleware"
|
||||||
|
"github.com/dhao2001/mygo/internal/model"
|
||||||
|
"github.com/dhao2001/mygo/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupAccountHandler(t *testing.T) (*AccountHandler, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
svc, secret := setupTestAuthService(t)
|
||||||
|
return NewAccountHandler(svc), secret
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupAccountRouter(t *testing.T) (*gin.Engine, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
svc, secret := setupTestAuthService(t)
|
||||||
|
authHandler := NewAuthHandler(svc)
|
||||||
|
accountHandler := NewAccountHandler(svc)
|
||||||
|
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
r := gin.New()
|
||||||
|
|
||||||
|
auth := r.Group("/api/v1/auth")
|
||||||
|
{
|
||||||
|
auth.POST("/register", authHandler.Register)
|
||||||
|
auth.POST("/login", authHandler.Login)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected := r.Group("/api/v1")
|
||||||
|
protected.Use(middleware.AuthRequired(secret))
|
||||||
|
{
|
||||||
|
account := protected.Group("/account")
|
||||||
|
{
|
||||||
|
account.GET("", accountHandler.GetAccount)
|
||||||
|
|
||||||
|
passkeys := account.Group("/passkeys")
|
||||||
|
{
|
||||||
|
passkeys.GET("", accountHandler.ListPasskeys)
|
||||||
|
passkeys.POST("", accountHandler.CreatePasskey)
|
||||||
|
passkeys.DELETE("/:id", accountHandler.RevokePasskey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, secret
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccountEndpoint(t *testing.T) {
|
||||||
|
r, _ := setupAccountRouter(t)
|
||||||
|
|
||||||
|
// Register + Login
|
||||||
|
body, _ := json.Marshal(gin.H{"username": "alice", "email": "alice@example.com", "password": "password123"})
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
loginBody, _ := json.Marshal(gin.H{"email": "alice@example.com", "password": "password123"})
|
||||||
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(loginBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
var pair service.TokenPair
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &pair)
|
||||||
|
|
||||||
|
// Get /account
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/v1/account", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+pair.AccessToken)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccountEndpointUnauthorized(t *testing.T) {
|
||||||
|
r, _ := setupAccountRouter(t)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/account", nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasskeyCRUD(t *testing.T) {
|
||||||
|
r, _ := setupAccountRouter(t)
|
||||||
|
|
||||||
|
// Register + Login
|
||||||
|
body, _ := json.Marshal(gin.H{"username": "alice", "email": "alice@example.com", "password": "password123"})
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
loginBody, _ := json.Marshal(gin.H{"email": "alice@example.com", "password": "password123"})
|
||||||
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(loginBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
var pair service.TokenPair
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &pair)
|
||||||
|
authHeader := "Bearer " + pair.AccessToken
|
||||||
|
|
||||||
|
// Create passkey
|
||||||
|
pkBody, _ := json.Marshal(gin.H{"label": "My Phone"})
|
||||||
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/passkeys", bytes.NewReader(pkBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", authHeader)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create passkey: status = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// List passkeys
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/v1/account/passkeys", nil)
|
||||||
|
req.Header.Set("Authorization", authHeader)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("list passkeys: status = %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke passkey
|
||||||
|
var creds []model.Credential
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &creds)
|
||||||
|
if len(creds) != 1 {
|
||||||
|
t.Fatalf("expected 1 passkey, got %d", len(creds))
|
||||||
|
}
|
||||||
|
|
||||||
|
req = httptest.NewRequest(http.MethodDelete, "/api/v1/account/passkeys/"+creds[0].ID, nil)
|
||||||
|
req.Header.Set("Authorization", authHeader)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Errorf("revoke passkey: status = %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,8 +6,6 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
"github.com/dhao2001/mygo/internal/api"
|
"github.com/dhao2001/mygo/internal/api"
|
||||||
"github.com/dhao2001/mygo/internal/middleware"
|
|
||||||
"github.com/dhao2001/mygo/internal/model"
|
|
||||||
"github.com/dhao2001/mygo/internal/service"
|
"github.com/dhao2001/mygo/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -102,88 +100,3 @@ func (h *AuthHandler) Logout(c *gin.Context) {
|
|||||||
|
|
||||||
c.Status(http.StatusOK)
|
c.Status(http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAccount handles GET /api/v1/account.
|
|
||||||
func (h *AuthHandler) GetAccount(c *gin.Context) {
|
|
||||||
userID := middleware.GetUserID(c)
|
|
||||||
if userID == "" {
|
|
||||||
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"user_id": userID})
|
|
||||||
}
|
|
||||||
|
|
||||||
type createPasskeyRequest struct {
|
|
||||||
Label string `json:"label" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPasskeys handles GET /api/v1/users/me/passkeys.
|
|
||||||
func (h *AuthHandler) ListPasskeys(c *gin.Context) {
|
|
||||||
userID := middleware.GetUserID(c)
|
|
||||||
if userID == "" {
|
|
||||||
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
creds, err := h.authService.ListPasskeys(c.Request.Context(), userID)
|
|
||||||
if err != nil {
|
|
||||||
api.Error(c, http.StatusInternalServerError, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if creds == nil {
|
|
||||||
creds = []model.Credential{}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, creds)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreatePasskey handles POST /api/v1/users/me/passkeys.
|
|
||||||
func (h *AuthHandler) CreatePasskey(c *gin.Context) {
|
|
||||||
userID := middleware.GetUserID(c)
|
|
||||||
if userID == "" {
|
|
||||||
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var req createPasskeyRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
pk, err := h.authService.CreatePasskey(c.Request.Context(), userID, req.Label)
|
|
||||||
if err != nil {
|
|
||||||
api.Error(c, http.StatusInternalServerError, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, pk)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RevokePasskey handles DELETE /api/v1/users/me/passkeys/:id.
|
|
||||||
func (h *AuthHandler) RevokePasskey(c *gin.Context) {
|
|
||||||
userID := middleware.GetUserID(c)
|
|
||||||
if userID == "" {
|
|
||||||
api.Error(c, http.StatusUnauthorized, "unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
passkeyID := c.Param("id")
|
|
||||||
if passkeyID == "" {
|
|
||||||
api.Error(c, http.StatusBadRequest, "missing passkey id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.authService.RevokePasskey(c.Request.Context(), userID, passkeyID); err != nil {
|
|
||||||
if err == model.ErrForbidden {
|
|
||||||
api.Error(c, http.StatusForbidden, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
api.Error(c, http.StatusInternalServerError, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Status(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -12,13 +12,12 @@ import (
|
|||||||
"gorm.io/driver/sqlite"
|
"gorm.io/driver/sqlite"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
|
||||||
"github.com/dhao2001/mygo/internal/middleware"
|
|
||||||
"github.com/dhao2001/mygo/internal/model"
|
"github.com/dhao2001/mygo/internal/model"
|
||||||
"github.com/dhao2001/mygo/internal/repository"
|
"github.com/dhao2001/mygo/internal/repository"
|
||||||
"github.com/dhao2001/mygo/internal/service"
|
"github.com/dhao2001/mygo/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupAuthHandler(t *testing.T) (*AuthHandler, []byte) {
|
func setupTestAuthService(t *testing.T) (*service.AuthService, []byte) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
@@ -39,7 +38,13 @@ func setupAuthHandler(t *testing.T) (*AuthHandler, []byte) {
|
|||||||
7*24*time.Hour,
|
7*24*time.Hour,
|
||||||
)
|
)
|
||||||
|
|
||||||
return NewAuthHandler(authService), secret
|
return authService, secret
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupAuthHandler(t *testing.T) (*AuthHandler, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
svc, secret := setupTestAuthService(t)
|
||||||
|
return NewAuthHandler(svc), secret
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupAuthRouter(t *testing.T) (*gin.Engine, []byte) {
|
func setupAuthRouter(t *testing.T) (*gin.Engine, []byte) {
|
||||||
@@ -58,22 +63,6 @@ func setupAuthRouter(t *testing.T) (*gin.Engine, []byte) {
|
|||||||
auth.POST("/logout", handler.Logout)
|
auth.POST("/logout", handler.Logout)
|
||||||
}
|
}
|
||||||
|
|
||||||
protected := r.Group("/api/v1")
|
|
||||||
protected.Use(middleware.AuthRequired(secret))
|
|
||||||
{
|
|
||||||
account := protected.Group("/account")
|
|
||||||
{
|
|
||||||
account.GET("", handler.GetAccount)
|
|
||||||
|
|
||||||
passkeys := account.Group("/passkeys")
|
|
||||||
{
|
|
||||||
passkeys.GET("", handler.ListPasskeys)
|
|
||||||
passkeys.POST("", handler.CreatePasskey)
|
|
||||||
passkeys.DELETE("/:id", handler.RevokePasskey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return r, secret
|
return r, secret
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,7 +187,6 @@ func TestRefreshHandler(t *testing.T) {
|
|||||||
})
|
})
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
httptest.NewRecorder().Body = nil
|
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
r.ServeHTTP(rec, req)
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
@@ -222,104 +210,3 @@ func TestRefreshHandler(t *testing.T) {
|
|||||||
t.Errorf("status = %d, want %d; body = %s", rec.Code, http.StatusOK, rec.Body.String())
|
t.Errorf("status = %d, want %d; body = %s", rec.Code, http.StatusOK, rec.Body.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountEndpoint(t *testing.T) {
|
|
||||||
r, _ := setupAuthRouter(t)
|
|
||||||
|
|
||||||
// Register + Login
|
|
||||||
body, _ := json.Marshal(gin.H{"username": "alice", "email": "alice@example.com", "password": "password123"})
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
loginBody, _ := json.Marshal(gin.H{"email": "alice@example.com", "password": "password123"})
|
|
||||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(loginBody))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
var pair service.TokenPair
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &pair)
|
|
||||||
|
|
||||||
// Get /account
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/api/v1/account", nil)
|
|
||||||
req.Header.Set("Authorization", "Bearer "+pair.AccessToken)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAccountEndpointUnauthorized(t *testing.T) {
|
|
||||||
r, _ := setupAuthRouter(t)
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/account", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPasskeyCRUD(t *testing.T) {
|
|
||||||
r, _ := setupAuthRouter(t)
|
|
||||||
|
|
||||||
// Register + Login
|
|
||||||
body, _ := json.Marshal(gin.H{"username": "alice", "email": "alice@example.com", "password": "password123"})
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", bytes.NewReader(body))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
loginBody, _ := json.Marshal(gin.H{"email": "alice@example.com", "password": "password123"})
|
|
||||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(loginBody))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
var pair service.TokenPair
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &pair)
|
|
||||||
authHeader := "Bearer " + pair.AccessToken
|
|
||||||
|
|
||||||
// Create passkey
|
|
||||||
pkBody, _ := json.Marshal(gin.H{"label": "My Phone"})
|
|
||||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/passkeys", bytes.NewReader(pkBody))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
req.Header.Set("Authorization", authHeader)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusCreated {
|
|
||||||
t.Fatalf("create passkey: status = %d, body = %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// List passkeys
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/api/v1/account/passkeys", nil)
|
|
||||||
req.Header.Set("Authorization", authHeader)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("list passkeys: status = %d", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Revoke passkey
|
|
||||||
var creds []model.Credential
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &creds)
|
|
||||||
if len(creds) != 1 {
|
|
||||||
t.Fatalf("expected 1 passkey, got %d", len(creds))
|
|
||||||
}
|
|
||||||
|
|
||||||
req = httptest.NewRequest(http.MethodDelete, "/api/v1/account/passkeys/"+creds[0].ID, nil)
|
|
||||||
req.Header.Set("Authorization", authHeader)
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Errorf("revoke passkey: status = %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,19 +10,19 @@ import (
|
|||||||
|
|
||||||
func setupProtectedRoutes(rg *gin.RouterGroup, webApp *app.WebApp) {
|
func setupProtectedRoutes(rg *gin.RouterGroup, webApp *app.WebApp) {
|
||||||
jwtSecret := []byte(webApp.Config.JWT.Secret)
|
jwtSecret := []byte(webApp.Config.JWT.Secret)
|
||||||
authHandler := handler.NewAuthHandler(webApp.AuthService)
|
accountHandler := handler.NewAccountHandler(webApp.AuthService)
|
||||||
|
|
||||||
rg.Use(middleware.AuthRequired(jwtSecret))
|
rg.Use(middleware.AuthRequired(jwtSecret))
|
||||||
|
|
||||||
account := rg.Group("/account")
|
account := rg.Group("/account")
|
||||||
{
|
{
|
||||||
account.GET("", authHandler.GetAccount)
|
account.GET("", accountHandler.GetAccount)
|
||||||
|
|
||||||
passkeys := account.Group("/passkeys")
|
passkeys := account.Group("/passkeys")
|
||||||
{
|
{
|
||||||
passkeys.GET("", authHandler.ListPasskeys)
|
passkeys.GET("", accountHandler.ListPasskeys)
|
||||||
passkeys.POST("", authHandler.CreatePasskey)
|
passkeys.POST("", accountHandler.CreatePasskey)
|
||||||
passkeys.DELETE("/:id", authHandler.RevokePasskey)
|
passkeys.DELETE("/:id", accountHandler.RevokePasskey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user