feat: V2 microservices stack — backend services, gateway, JWT auth

Add full V2 architecture: identity, content, studio (.NET 10) and file,
render, notification, gateway (Go) services with vendored deps, plus DB
migrations, event/API contracts, and an init-db script.

Wire the Next.js frontend to the gateway: server-side JWT auth routes
(login/register/refresh/logout/me), gateway fetch helper, and session/
cookie/jwt helpers under src/lib.

Containerize the stack via docker-compose.v2.yml and per-service
Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and
MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via
next/font/local to avoid Google Fonts (geo-blocked).

Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-05-29 23:29:31 +03:30
parent 53ea78a00d
commit 90ac0b81d1
7636 changed files with 3707504 additions and 240 deletions
@@ -0,0 +1,136 @@
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
const (
HeaderUserID = "X-User-ID"
HeaderTenantID = "X-Tenant-ID"
HeaderIsAdmin = "X-Is-Admin"
HeaderRole = "X-Role"
CtxUserID = "user_id"
CtxTenantID = "tenant_id"
CtxIsAdmin = "is_admin"
CtxRole = "role"
)
type ErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
}
// JWTAuth validates the bearer token and injects claims into both gin context and upstream request headers.
func JWTAuth(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
if validateAndInject(c, secret) {
c.Next()
}
}
}
// JWTAuthSkip behaves like JWTAuth but skips authentication entirely when skip(c)
// returns true. Used for catch-all routes that mix public and protected sub-paths
// (e.g. /payments/* where /callback/* and /webhook/* must stay public) — gin forbids
// registering a catch-all alongside static child segments, so the branch lives here.
func JWTAuthSkip(secret string, skip func(*gin.Context) bool) gin.HandlerFunc {
return func(c *gin.Context) {
if skip(c) {
c.Next()
return
}
if validateAndInject(c, secret) {
c.Next()
}
}
}
// validateAndInject validates the bearer token and injects claims into the gin context
// and upstream request headers. On failure it aborts with 401 and returns false.
// It does NOT call c.Next() — the caller decides whether to continue the chain.
func validateAndInject(c *gin.Context, secret string) bool {
hdr := c.GetHeader("Authorization")
if !strings.HasPrefix(hdr, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Code: "unauthorized", Message: "missing bearer token"})
return false
}
tokenStr := hdr[7:]
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(secret), nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorResponse{Code: "unauthorized", Message: "invalid or expired token"})
return false
}
claims, _ := token.Claims.(jwt.MapClaims)
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
tenantID, _ := uuid.Parse(fmt.Sprintf("%v", claims["tenant_id"]))
isAdmin, _ := claims["is_admin"].(bool)
role, _ := claims["role"].(string)
c.Set(CtxUserID, userID)
c.Set(CtxTenantID, tenantID)
c.Set(CtxIsAdmin, isAdmin)
c.Set(CtxRole, role)
// Inject for upstream services
c.Request.Header.Set(HeaderUserID, userID.String())
c.Request.Header.Set(HeaderTenantID, tenantID.String())
if isAdmin {
c.Request.Header.Set(HeaderIsAdmin, "true")
}
if role != "" {
c.Request.Header.Set(HeaderRole, role)
}
return true
}
// OptionalJWTAuth parses the token if present but does not abort on missing/invalid token.
func OptionalJWTAuth(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
hdr := c.GetHeader("Authorization")
if !strings.HasPrefix(hdr, "Bearer ") {
c.Next()
return
}
token, err := jwt.Parse(hdr[7:], func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(secret), nil
})
if err != nil || !token.Valid {
c.Next()
return
}
claims, _ := token.Claims.(jwt.MapClaims)
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
tenantID, _ := uuid.Parse(fmt.Sprintf("%v", claims["tenant_id"]))
isAdmin, _ := claims["is_admin"].(bool)
c.Request.Header.Set(HeaderUserID, userID.String())
c.Request.Header.Set(HeaderTenantID, tenantID.String())
if isAdmin {
c.Request.Header.Set(HeaderIsAdmin, "true")
}
c.Next()
}
}
func GetUserID(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get(CtxUserID)
if !ok {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok && id != uuid.Nil
}
@@ -0,0 +1,94 @@
package middleware
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// ipBucket is a per-IP sliding-window counter.
type ipBucket struct {
mu sync.Mutex
times []time.Time
limit int
window time.Duration
}
func (b *ipBucket) allow() bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
cutoff := now.Add(-b.window)
// Evict timestamps outside the window
valid := b.times[:0]
for _, t := range b.times {
if t.After(cutoff) {
valid = append(valid, t)
}
}
b.times = valid
if len(b.times) >= b.limit {
return false
}
b.times = append(b.times, now)
return true
}
// RateLimiter is a per-IP sliding-window rate limiter backed by sync.Map.
// It is safe for concurrent use and cleans up idle buckets automatically.
type RateLimiter struct {
buckets sync.Map // string(ip) → *ipBucket
limit int
window time.Duration
}
// NewRateLimiter creates a limiter that allows up to limit requests per window
// per IP address.
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
rl := &RateLimiter{limit: limit, window: window}
go rl.gc()
return rl
}
// gc periodically removes buckets that have had no activity for one full window.
func (rl *RateLimiter) gc() {
ticker := time.NewTicker(rl.window)
defer ticker.Stop()
for range ticker.C {
rl.buckets.Range(func(k, v any) bool {
b := v.(*ipBucket)
b.mu.Lock()
if len(b.times) == 0 {
rl.buckets.Delete(k)
}
b.mu.Unlock()
return true
})
}
}
// Middleware returns a gin.HandlerFunc that enforces the rate limit.
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
v, _ := rl.buckets.LoadOrStore(ip, &ipBucket{
times: make([]time.Time, 0, rl.limit),
limit: rl.limit,
window: rl.window,
})
b := v.(*ipBucket)
if !b.allow() {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
"code": "rate_limited",
"message": "too many requests — slow down",
})
return
}
c.Next()
}
}