Skip to content

2. Authentication with Limen ​

GoForge secures your backend in two complementary layers:

  1. Application Boundary (X-App-Key) — Built into boot/server/middleware/auth.go. Every HTTP request (and gRPC call via x-app-key metadata) must present the constant-time-validated APP_KEY.
  2. User Identity (Limen Sessions) — Provided by github.com/thecodearcher/limen using the built-in .agent/skills/limen-auth/ pattern: bcrypt password hashing, server-side sessions, HTTP cookies, and /api/auth/{register,login,me,logout} endpoints.

In this chapter, we follow GoForge's limen-auth skill and wire it cleanly into GoForge's DI container (core/di) so models, database initialization, and cross-service auth middleware require zero manual hacks in internal/services/kernel.go.


2.1 Install Limen Dependencies ​

Run the skill's install script or install the packages directly:

bash
go get github.com/thecodearcher/limen
go get github.com/thecodearcher/limen/adapters/gorm
go get github.com/thecodearcher/limen/plugins/credential-password

2.2 Scaffold the auth Service ​

Use goforge gen:service to create internal/services/auth/ and register it in internal/services/kernel.go:

bash
goforge gen:service auth

Because Limen owns the /api/auth/* HTTP handlers and does not use gRPC, remove the unused generated files:

bash
rm -f internal/services/auth/handler.go internal/services/auth/grpc.go
rm -rf internal/proto/auth

(We keep internal/services/auth/docs.go — we'll add full OpenAPI 3.1 documentation for the auth endpoints in Chapter 6.)

Shortcut Script

The template also ships .agent/skills/limen-auth/scaffold.sh, which automates gen:service auth, removes unused files, and runs install-deps.sh.


2.3 Define Limen Models (internal/services/auth/model.go) ​

Limen stores users, sessions, email verifications, and OAuth accounts across four GORM models. Notice Password *string uses json:"-" so hashes can never leak in JSON responses, and User uses gorm.DeletedAt for foreign-key safety:

go
package auth

import (
	"time"

	"gorm.io/gorm"
)

// User represents the core user identity within Limen.
type User struct {
	ID              uint64         `gorm:"primaryKey;autoIncrement" json:"id"`
	Email           string         `gorm:"uniqueIndex;not null" json:"email"`
	Password        *string        `json:"-"`
	EmailVerifiedAt *time.Time     `json:"email_verified_at"`
	FirstName       string         `json:"first_name"`
	LastName        string         `json:"last_name"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `gorm:"index" json:"deleted_at"`
}

// Session tracks an active authenticated session for a User.
type Session struct {
	ID         string    `gorm:"primaryKey" json:"id"`
	Token      string    `gorm:"uniqueIndex;not null" json:"token"`
	UserID     uint64    `gorm:"index;not null" json:"user_id"`
	CreatedAt  time.Time `json:"created_at"`
	ExpiresAt  time.Time `json:"expires_at"`
	LastAccess time.Time `json:"last_access"`
	Metadata   string    `json:"metadata"`
}

// Verification handles one-time tokens (e.g., email verification or password resets).
type Verification struct {
	ID        uint64    `gorm:"primaryKey;autoIncrement" json:"id"`
	Identifier string   `gorm:"index;not null" json:"identifier"`
	Value     string    `gorm:"not null" json:"value"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// Account supports linked OAuth / external SSO providers.
type Account struct {
	ID                    uint64     `gorm:"primaryKey;autoIncrement" json:"id"`
	UserID                uint64     `gorm:"index;not null" json:"user_id"`
	Provider              string     `gorm:"not null" json:"provider"`
	ProviderAccountID     string     `gorm:"not null" json:"provider_account_id"`
	AccessToken           *string    `json:"access_token"`
	RefreshToken          *string    `json:"refresh_token"`
	AccessTokenExpiresAt  *time.Time `json:"access_token_expires_at"`
	Scope                 *string    `json:"scope"`
	IDToken               *string    `json:"id_token"`
	CreatedAt             time.Time  `json:"created_at"`
	UpdatedAt             time.Time  `json:"updated_at"`
}

2.4 Create the DI-Managed AuthService (internal/services/auth/service.go) ​

In GoForge's DI architecture, NewAuthService receives *database.Database and *config.AllConfig directly from the container, initializes the Limen singleton once, and fails fast if APP_KEY or the DB pool is unavailable:

go
package auth

import (
	"errors"
	"net/http"

	"github.com/acme/taskforge/core/config"
	"github.com/acme/taskforge/core/database"
	"github.com/thecodearcher/limen"
	limengorm "github.com/thecodearcher/limen/adapters/gorm"
	credentialpassword "github.com/thecodearcher/limen/plugins/credential-password"
)

// Auth is exposed as a convenience singleton initialized once by DI.
var Auth *limen.Limen

// AuthService wraps the Limen authentication engine.
type AuthService struct {
	engine *limen.Limen
}

// NewAuthService initializes Limen using the application's GORM DB and APP_KEY.
func NewAuthService(db *database.Database, cfg *config.AllConfig) (*AuthService, error) {
	if cfg == nil || cfg.App.Key == "" {
		return nil, errors.New("auth: APP_KEY must be configured before initializing Limen")
	}

	gormDB, err := db.GetGorm()
	if err != nil {
		return nil, err
	}

	engine, err := limen.New(&limen.Config{
		Secret:   []byte(cfg.App.Key),
		Database: limengorm.New(gormDB),
		Plugins: []limen.Plugin{
			credentialpassword.New(),
		},
	})
	if err != nil {
		return nil, err
	}

	Auth = engine
	return &AuthService{engine: engine}, nil
}

// Engine returns the underlying Limen instance.
func (s *AuthService) Engine() *limen.Limen {
	return s.engine
}

// SessionFromRequest extracts and validates the active session from an HTTP request.
func (s *AuthService) SessionFromRequest(r *http.Request) (*limen.Session, error) {
	return s.engine.SessionFromRequest(r)
}

2.5 Create the Reusable AuthMiddleware (internal/services/auth/middleware.go) ​

Other services (like task in the next chapter) will inject *auth.AuthMiddleware via DI to protect their routes and read the authenticated userID:

go
package auth

import (
	"strconv"

	apperrors "github.com/acme/taskforge/core/errors"
	"github.com/gin-gonic/gin"
)

const contextUserIDKey = "auth_user_id"

// AuthMiddleware validates Limen session cookies on protected routes.
type AuthMiddleware struct {
	svc *AuthService
}

// NewAuthMiddleware constructs an AuthMiddleware for DI.
func NewAuthMiddleware(svc *AuthService) *AuthMiddleware {
	return &AuthMiddleware{svc: svc}
}

// RequireAuth verifies the Limen session cookie and stores the user ID in Gin's context.
func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		session, err := m.svc.SessionFromRequest(c.Request)
		if err != nil || session == nil {
			_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
			c.Abort()
			return
		}

		c.Set(contextUserIDKey, session.UserID)
		c.Next()
	}
}

// UserIDFromContext extracts the authenticated uint64 user ID from Gin's context.
func UserIDFromContext(c *gin.Context) (uint64, bool) {
	val, exists := c.Get(contextUserIDKey)
	if !exists {
		return 0, false
	}

	switch v := val.(type) {
	case uint64:
		return v, v > 0
	case string:
		id, err := strconv.ParseUint(v, 10, 64)
		return id, err == nil && id > 0
	default:
		return 0, false
	}
}

2.6 Mount Limen Routes (internal/services/auth/routes.go) ​

Use engine.Any("/api/auth/*action", gin.WrapH(...)) so Limen handles /register, /login, /me, and /logout:

go
package auth

import "github.com/gin-gonic/gin"

// AuthRoutes mounts Limen's HTTP handler onto Gin.
type AuthRoutes struct {
	svc *AuthService
}

// NewAuthRoutes constructs AuthRoutes for DI auto-collection as server.Router.
func NewAuthRoutes(svc *AuthService) *AuthRoutes {
	return &AuthRoutes{svc: svc}
}

// Register attaches the Limen handler at /api/auth/*action.
func (r *AuthRoutes) Register(engine *gin.Engine) {
	engine.Any("/api/auth/*action", gin.WrapH(r.svc.Engine().Handler()))
}

2.7 Wire module.go (internal/services/auth/module.go) ​

Declare all providers and all four Limen models inside Module(). Because boot.NewWithConfig runs di.CollectModels(services.Modules()...), internal/services/kernel.go automatically picks up User, Session, Verification, and Account with no manual edits:

go
package auth

import "github.com/acme/taskforge/core/di"

// Module returns the DI module for the auth service.
func Module() di.Module {
	return di.Module{
		Name: "auth",
		Providers: []any{
			NewAuthService,
			NewAuthMiddleware,
			NewAuthRoutes,
			NewAuthDocs,
		},
		Models: []any{
			&User{},
			&Session{},
			&Verification{},
			&Account{},
		},
	}
}

(For now, keep internal/services/auth/docs.go as the generated stub — we will expand it in Chapter 6.)


2.8 Migrate and Smoke-Test Limen Auth ​

Run migrations (using GORM AutoMigrate for a quick check, or Atlas as shown in Chapter 4) and start the server:

bash
DB_MIGRATOR=gorm goforge migrate
goforge app serve --no-tui

In a second terminal, test the full Limen lifecycle (passing -H "X-App-Key: $APP_KEY"):

bash
export APP_KEY=$(grep '^APP_KEY=' .env | cut -d= -f2-)

# 1. Register
curl -s -X POST http://127.0.0.1:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -H "X-App-Key: $APP_KEY" \
  -d '{"email":"alice@taskforge.dev","password":"StrongPassword123!","first_name":"Alice","last_name":"Dev"}'

# 2. Login (saves session cookie to cookies.txt)
curl -s -X POST http://127.0.0.1:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -H "X-App-Key: $APP_KEY" \
  -c cookies.txt \
  -d '{"email":"alice@taskforge.dev","password":"StrongPassword123!"}'

# 3. Current user (/me)
curl -s http://127.0.0.1:3000/api/auth/me \
  -H "X-App-Key: $APP_KEY" \
  -b cookies.txt

# 4. Logout
curl -s -X POST http://127.0.0.1:3000/api/auth/logout \
  -H "X-App-Key: $APP_KEY" \
  -b cookies.txt

Notice that password is never returned in any JSON payload, and calling /api/auth/me after logout returns 401 Unauthorized.


Next: 3. Protected CRUD Service (task) →

Released under the Apache-2.0 License.