The language comes from the user setting, then the lang cookie, then Accept-Language, falling back to English. Errors keep a stable code and carry a translated message. Closes #42 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
185 lines
4.9 KiB
Go
185 lines
4.9 KiB
Go
// Package api serves the management JSON API under /api/v1 and the
|
|
// server-rendered console pages that call it.
|
|
package api
|
|
|
|
import (
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
|
)
|
|
|
|
const localeCookie = "lang"
|
|
|
|
// Server holds the dependencies shared by all handlers.
|
|
type Server struct {
|
|
cfg config.API
|
|
log *slog.Logger
|
|
db *tenant.DB
|
|
rdb redis.UniversalClient
|
|
keys *sealed.Keyring
|
|
catalog *i18n.Catalog
|
|
sessions *auth.Sessions
|
|
limiter *auth.Limiter
|
|
totp *auth.TOTPVerifier
|
|
}
|
|
|
|
// Deps are the external resources a Server needs.
|
|
type Deps struct {
|
|
Log *slog.Logger
|
|
DB *tenant.DB
|
|
Redis redis.UniversalClient
|
|
Keys *sealed.Keyring
|
|
Catalog *i18n.Catalog
|
|
}
|
|
|
|
// New returns a Server. It does not register any routes; see Mount.
|
|
func New(cfg config.API, d Deps) *Server {
|
|
return &Server{
|
|
cfg: cfg,
|
|
log: d.Log,
|
|
db: d.DB,
|
|
rdb: d.Redis,
|
|
keys: d.Keys,
|
|
catalog: d.Catalog,
|
|
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
|
|
limiter: auth.NewLimiter(d.Redis),
|
|
totp: auth.NewTOTPVerifier(d.Redis),
|
|
}
|
|
}
|
|
|
|
// Mount installs session loading, locale resolution and CSRF protection and
|
|
// registers the JSON API and the console pages below them.
|
|
func (s *Server) Mount(r gin.IRouter) {
|
|
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF())
|
|
|
|
v1 := g.Group("/api/v1")
|
|
v1.POST("/locale", s.setLocale)
|
|
|
|
a := v1.Group("/auth")
|
|
a.POST("/signup", s.signup)
|
|
a.POST("/login", s.login)
|
|
a.POST("/login/totp", s.loginTOTP)
|
|
a.POST("/logout", s.logout)
|
|
|
|
me := v1.Group("/me", auth.Require())
|
|
me.GET("", s.me)
|
|
me.POST("/org", s.switchOrg)
|
|
me.POST("/totp/setup", s.totpSetup)
|
|
me.POST("/totp/enable", s.totpEnable)
|
|
me.POST("/totp/disable", s.totpDisable)
|
|
|
|
s.registerPages(g)
|
|
}
|
|
|
|
// localize resolves the language from, in order: the signed-in user's
|
|
// setting, the lang cookie, and Accept-Language.
|
|
func (s *Server) localize() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
var pref string
|
|
if sess := auth.Current(c); sess != nil {
|
|
pref = sess.Locale
|
|
}
|
|
cookie, _ := c.Cookie(localeCookie)
|
|
l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language"))
|
|
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
|
c.Header("Content-Language", l.Lang())
|
|
c.Header("Vary", "Accept-Language, Cookie")
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
type localeRequest struct {
|
|
Locale string `json:"locale" binding:"required,max=10"`
|
|
}
|
|
|
|
func (s *Server) setLocale(c *gin.Context) {
|
|
var req localeRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
if !s.catalog.IsSupported(req.Locale) {
|
|
fail(c, http.StatusUnprocessableEntity, "unsupported_locale")
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
if sess := auth.Current(c); sess != nil {
|
|
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
|
return q.SetUserLocale(ctx, store.SetUserLocaleParams{ID: sess.UserID, Locale: &req.Locale})
|
|
})
|
|
if err == nil {
|
|
err = s.sessions.SetLocale(ctx, sess, req.Locale)
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
}
|
|
setCookie(c, localeCookie, req.Locale, 365*24*3600)
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
type apiError struct {
|
|
Error string `json:"error"`
|
|
Message string `json:"message"`
|
|
Fields map[string]string `json:"fields,omitempty"`
|
|
}
|
|
|
|
// fail aborts with a machine-readable code and a message translated from
|
|
// the catalog entry "error.<code>". kv fills placeholders in that message.
|
|
func fail(c *gin.Context, status int, code string, kv ...any) {
|
|
c.AbortWithStatusJSON(status, apiError{
|
|
Error: code,
|
|
Message: i18n.T(c.Request.Context(), "error."+code, kv...),
|
|
})
|
|
}
|
|
|
|
func internalError(c *gin.Context, err error) {
|
|
_ = c.Error(err)
|
|
fail(c, http.StatusInternalServerError, "internal")
|
|
}
|
|
|
|
func bind(c *gin.Context, dst any) bool {
|
|
err := c.ShouldBindJSON(dst)
|
|
if err == nil {
|
|
return true
|
|
}
|
|
e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")}
|
|
var ve validator.ValidationErrors
|
|
if errors.As(err, &ve) {
|
|
e.Fields = map[string]string{}
|
|
for _, f := range ve {
|
|
e.Fields[f.Field()] = f.Tag()
|
|
}
|
|
}
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, e)
|
|
return false
|
|
}
|
|
|
|
func setCookie(c *gin.Context, name, value string, maxAge int) {
|
|
http.SetCookie(c.Writer, &http.Cookie{
|
|
Name: name, Value: value, Path: "/", MaxAge: maxAge,
|
|
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
|
})
|
|
}
|
|
|
|
func ptr[T any](v T) *T { return &v }
|
|
|
|
func deref[T any](p *T) T {
|
|
var zero T
|
|
if p == nil {
|
|
return zero
|
|
}
|
|
return *p
|
|
}
|