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/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) type Server struct { cfg config.API log *slog.Logger db *tenant.DB rdb redis.UniversalClient keys *sealed.Keyring sessions *auth.Sessions limiter *auth.Limiter totp *auth.TOTPVerifier } func New(cfg config.API, log *slog.Logger, db *tenant.DB, rdb redis.UniversalClient, keys *sealed.Keyring) *Server { return &Server{ cfg: cfg, log: log, db: db, rdb: rdb, keys: keys, sessions: auth.NewSessions(rdb, cfg.SessionIdle, cfg.SessionAbsolute), limiter: auth.NewLimiter(rdb), totp: auth.NewTOTPVerifier(rdb), } } func (s *Server) Sessions() *auth.Sessions { return s.sessions } // Register mounts the JSON API. The caller must already have installed // Sessions().Load() and auth.CSRF() on the engine. func (s *Server) Register(r gin.IRouter) { v1 := r.Group("/api/v1") 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) } type apiError struct { Error string `json:"error"` Message string `json:"message"` Fields map[string]string `json:"fields,omitempty"` } func fail(c *gin.Context, status int, code, msg string) { c.AbortWithStatusJSON(status, apiError{Error: code, Message: msg}) } func internalError(c *gin.Context, err error) { _ = c.Error(err) c.AbortWithStatusJSON(http.StatusInternalServerError, apiError{Error: "internal", Message: "Interner Fehler."}) } func bind(c *gin.Context, dst any) bool { if err := c.ShouldBindJSON(dst); err != nil { e := apiError{Error: "invalid_input", Message: "Eingaben prüfen."} 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 } return true } 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 randomToken() string { return auth.RandomToken() }