A continuation of HomeBox the inventory and organization system built for the Home User
feat: password reset (#1488)
Matt616377309268
diff --git a/backend/app/api/cli_reset_password.go b/backend/app/api/cli_reset_password.gonew file mode 100644index 00000000..b9cbe8c3--- /dev/null+++ b/backend/app/api/cli_reset_password.go@@ -0,0 +1,141 @@+package main++import (+ "context"+ "database/sql"+ "errors"+ "flag"+ "fmt"+ "os"+ "strings"++ "entgo.io/ent/dialect"+ entsql "entgo.io/ent/dialect/sql"+ "github.com/pressly/goose/v3"+ "github.com/sysadminsmedia/homebox/backend/internal/core/services"+ "github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/migrations"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"+)++// runResetPasswordCLI handles `homebox reset-password --email=...`. It mints a+// one-time reset link and prints it to stdout. This is the escape hatch for+// installations without SMTP, or for debugging the password matching path+// itself — the cases where the email-based flow can't help.+//+// Returns true when it consumed the command (and the caller should exit), so+// `homebox` with no subcommand still falls through to the server.+func runResetPasswordCLI(args []string) (handled bool, exitCode int) {+ if len(args) < 2 || args[1] != "reset-password" {+ return false, 0+ }++ fs := flag.NewFlagSet("reset-password", flag.ContinueOnError)+ email := fs.String("email", "", "Email address of the account to reset")+ fs.Usage = func() {+ fmt.Fprintln(os.Stderr, "Usage: homebox reset-password --email=<address>")+ fmt.Fprintln(os.Stderr)+ fmt.Fprintln(os.Stderr, "Generates a one-time password reset link for the given account and")+ fmt.Fprintln(os.Stderr, "prints it to stdout. The link expires in one hour and can be used once.")+ fmt.Fprintln(os.Stderr)+ fmt.Fprintln(os.Stderr, "All HBOX_* environment variables (database, hostname) are honored.")+ fs.PrintDefaults()+ }+ if err := fs.Parse(args[2:]); err != nil {+ return true, 2+ }+ trimmedEmail := strings.TrimSpace(*email)+ if trimmedEmail == "" {+ fs.Usage()+ return true, 2+ }++ cfg, err := config.New(build(), "Homebox inventory management system")+ if err != nil {+ fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)+ return true, 1+ }++ link, err := generateResetLinkOffline(cfg, trimmedEmail)+ if err != nil {+ if ent.IsNotFound(err) {+ fmt.Fprintf(os.Stderr, "no account found for %s\n", trimmedEmail)+ return true, 1+ }+ fmt.Fprintf(os.Stderr, "failed to generate reset link: %v\n", err)+ return true, 1+ }++ fmt.Println(link)+ return true, 0+}++// generateResetLinkOffline opens the database, runs migrations if needed, and+// mints a token without starting the HTTP server. The returned link uses+// HBOX_OPTIONS_HOSTNAME if set; otherwise it's emitted as a path the operator+// can append to whatever URL their instance is reachable at.+func generateResetLinkOffline(cfg *config.Config, email string) (string, error) {+ databaseURL, err := setupDatabaseURL(cfg)+ if err != nil {+ return "", fmt.Errorf("setup database url: %w", err)+ }++ driver := strings.ToLower(cfg.Database.Driver)+ var driverName, dialectName string+ switch driver {+ case config.DriverPostgres:+ driverName = "pgx"+ dialectName = dialect.Postgres+ case config.DriverSqlite3, "sqlite":+ driverName = "sqlite3"+ dialectName = dialect.SQLite+ default:+ return "", fmt.Errorf("unsupported driver: %s", driver)+ }++ db, err := sql.Open(driverName, databaseURL)+ if err != nil {+ return "", fmt.Errorf("open db: %w", err)+ }+ defer func() { _ = db.Close() }()++ drv := entsql.OpenDB(dialectName, db)+ c := ent.NewClient(ent.Driver(drv))+ defer func() { _ = c.Close() }()++ migrationsFs, err := migrations.Migrations(driver)+ if err != nil {+ return "", fmt.Errorf("load migrations: %w", err)+ }+ goose.SetBaseFS(migrationsFs)+ if err := goose.SetDialect(driver); err != nil {+ return "", fmt.Errorf("set dialect: %w", err)+ }+ if err := goose.Up(c.Sql(), driver); err != nil {+ return "", fmt.Errorf("apply migrations: %w", err)+ }++ bus := eventbus.New()+ repos := repo.New(c, bus, cfg.Storage, cfg.Database.PubSubConnString, cfg.Thumbnail)+ svc := services.New(repos)++ baseURL := strings.TrimSuffix(cfg.Options.Hostname, "/")+ if baseURL != "" && !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {+ // Hostname without a scheme: assume https. The CLI has no request to+ // inspect for r.TLS, and https is the safer default to print.+ baseURL = "https://" + baseURL+ }++ link, err := svc.User.GenerateResetLink(context.Background(), email, baseURL)+ if err != nil {+ if errors.Is(err, services.ErrorMailerNotConfigured) {+ // Should never happen here; GenerateResetLink doesn't touch the+ // mailer. Defensive in case future refactors reorder things.+ return "", err+ }+ return "", err+ }+ return link, nil+}diff --git a/backend/app/api/handlers/v1/helpers.go b/backend/app/api/handlers/v1/helpers.goindex aba003a4..68302524 100644--- a/backend/app/api/handlers/v1/helpers.go+++ b/backend/app/api/handlers/v1/helpers.go@@ -56,14 +56,94 @@ func ensureScheme(hostname string, r *http.Request, trustProxy bool) string {// getScheme determines the appropriate URL scheme based on request and proxy settingsfunc getScheme(r *http.Request, trustProxy bool) string {if r.TLS != nil {- return "https"+ return schemeHTTPS}- if trustProxy && r.Header.Get("X-Forwarded-Proto") == "https" {- return "https"+ if trustProxy {+ // X-Forwarded-Proto may be a comma-separated list (one entry per hop);+ // the leftmost entry is the original client-facing protocol — that's+ // what we want for user-facing URL construction. A literal equality+ // check fails on legitimate "https, http" multi-hop values.+ proto := strings.ToLower(firstHeaderValue(r.Header.Get("X-Forwarded-Proto")))+ if proto == schemeHTTPS {+ return schemeHTTPS+ }}return "http"}+// firstHeaderValue returns the first comma-separated value from a header+// field, trimmed. RFC 7230 §3.2.2 allows multiple instances of a field to+// be combined with commas; net/http's Header.Get returns only the first+// occurrence but does NOT split combined values, so a header like+// `X-Forwarded-Host: a, b` would otherwise be embedded verbatim into URLs.+func firstHeaderValue(v string) string {+ if i := strings.IndexByte(v, ','); i >= 0 {+ v = v[:i]+ }+ return strings.TrimSpace(v)+}++// validProxyHost reports whether s is a syntactically valid host:port (or+// host) value, with no scheme, path, query, fragment, whitespace, or control+// characters. Callers building URLs from untrusted X-Forwarded-Host must run+// this check — without it, a misconfigured proxy that forwards client-set+// headers could let an attacker inject path/CRLF/full-URL payloads into a+// password-reset email link.+func validProxyHost(s string) bool {+ if s == "" {+ return false+ }+ // Reject control characters, whitespace, and structural URL characters+ // outright. Hosts legitimately include letters, digits, dot, dash, colon+ // (port separator), and brackets (IPv6).+ for _, r := range s {+ if r < 0x20 || r == 0x7f {+ return false+ }+ }+ if strings.ContainsAny(s, " \t/?#\\") {+ return false+ }+ if strings.Contains(s, "://") {+ return false+ }+ // Final structural check: url.Parse should round-trip the string as the+ // authority component. If it doesn't, something funny is going on.+ u, err := url.Parse("http://" + s)+ if err != nil || u.Host != s || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {+ return false+ }+ return true+}++// SecureBaseURL returns a base URL safe to embed in security-sensitive emails+// (password reset, etc.). Unlike GetHBURL it deliberately omits the Referer+// fallback, since Referer is unauthenticated client input — an attacker who+// can reach /forgot-password could otherwise poison the link in the victim's+// reset email and phish the new password.+//+// X-Forwarded-Host is honored only when the operator has opted into+// TrustProxy. Even then, the value is parsed via firstHeaderValue (multi-hop+// safe) and validated via validProxyHost so a misconfigured proxy that+// forwards client-supplied headers can't inject schemes, paths, CRLF, or+// extra hosts into the link.+//+// Returns "" when no trusted source is available; callers must refuse the+// operation in that case.+func SecureBaseURL(r *http.Request, options *config.Options) string {+ if options.Hostname != "" {+ return ensureScheme(options.Hostname, r, options.TrustProxy)+ }+ if options.TrustProxy {+ host := firstHeaderValue(r.Header.Get("X-Forwarded-Host"))+ if !validProxyHost(host) {+ return ""+ }+ return getScheme(r, options.TrustProxy) + "://" + host+ }+ return ""+}+// stripPathFromURL removes the path from a URL.// ex. https://example.com/tools -> https://example.comfunc stripPathFromURL(rawURL string) string {diff --git a/backend/app/api/handlers/v1/helpers_test.go b/backend/app/api/handlers/v1/helpers_test.gonew file mode 100644index 00000000..d61bcd7e--- /dev/null+++ b/backend/app/api/handlers/v1/helpers_test.go@@ -0,0 +1,219 @@+package v1++import (+ "net/http/httptest"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"+)++// fixtureAppURL is the canonical URL used across SecureBaseURL test cases.+// Extracted to satisfy goconst.+const fixtureAppURL = "https://app.example.com"++func TestSecureBaseURL(t *testing.T) {+ cases := []struct {+ name string+ hostname string+ trustProxy bool+ xfHost string+ xfProto string+ expectURL string+ expectEmpty bool+ }{+ {+ name: "Hostname configured wins outright",+ hostname: fixtureAppURL,+ expectURL: fixtureAppURL,+ },+ {+ name: "no hostname, no trust proxy → refuse",+ expectEmpty: true,+ },+ {+ name: "trust proxy but no XF-Host → refuse",+ trustProxy: true,+ expectEmpty: true,+ },+ {+ name: "trust proxy + XF-Host (https)",+ trustProxy: true,+ xfHost: "app.example.com",+ xfProto: schemeHTTPS,+ expectURL: fixtureAppURL,+ },+ {+ name: "trust proxy + XF-Host with port",+ trustProxy: true,+ xfHost: "app.example.com:8443",+ xfProto: schemeHTTPS,+ expectURL: "https://app.example.com:8443",+ },+ {+ name: "trust proxy + IPv6 XF-Host",+ trustProxy: true,+ xfHost: "[2001:db8::1]:8443",+ xfProto: schemeHTTPS,+ expectURL: "https://[2001:db8::1]:8443",+ },++ // Multi-hop / multi-value handling: take the first comma-separated+ // value, mirroring the leftmost-is-original convention used by+ // reverse proxies.+ {+ name: "comma-separated XF-Host: take first",+ trustProxy: true,+ xfHost: "app.example.com, internal.example.com",+ xfProto: schemeHTTPS,+ expectURL: fixtureAppURL,+ },+ {+ name: "comma-separated XF-Proto: take first",+ trustProxy: true,+ xfHost: "app.example.com",+ xfProto: "https, http",+ expectURL: fixtureAppURL,+ },++ // Validation rejections — these are the attack-relevant cases. A+ // misconfigured proxy that forwards client-supplied X-Forwarded-Host+ // without overwriting could otherwise let an attacker plant any of+ // these into the password-reset link.+ {+ name: "XF-Host with embedded scheme is rejected",+ trustProxy: true,+ xfHost: "https://evil.com",+ expectEmpty: true,+ },+ {+ name: "XF-Host with path is rejected",+ trustProxy: true,+ xfHost: "evil.com/path",+ expectEmpty: true,+ },+ {+ name: "XF-Host with query is rejected",+ trustProxy: true,+ xfHost: "evil.com?x=1",+ expectEmpty: true,+ },+ {+ name: "XF-Host with fragment is rejected",+ trustProxy: true,+ xfHost: "evil.com#frag",+ expectEmpty: true,+ },+ {+ name: "XF-Host with whitespace is rejected",+ trustProxy: true,+ xfHost: "evil .com",+ expectEmpty: true,+ },+ {+ name: "XF-Host with backslash is rejected",+ trustProxy: true,+ xfHost: `evil.com\foo`,+ expectEmpty: true,+ },+ {+ name: "XF-Host with embedded CR is rejected",+ trustProxy: true,+ xfHost: "evil.com\rfoo",+ expectEmpty: true,+ },+ {+ name: "empty XF-Host is rejected",+ trustProxy: true,+ xfHost: "",+ expectEmpty: true,+ },++ // Without TrustProxy, even legitimately-set XF-Host is ignored.+ {+ name: "untrusted proxy headers are ignored",+ trustProxy: false,+ xfHost: "app.example.com",+ xfProto: schemeHTTPS,+ expectEmpty: true,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest("POST", "/api/v1/users/forgot-password", nil)+ if tc.xfHost != "" {+ req.Header.Set("X-Forwarded-Host", tc.xfHost)+ }+ if tc.xfProto != "" {+ req.Header.Set("X-Forwarded-Proto", tc.xfProto)+ }++ opts := &config.Options{+ Hostname: tc.hostname,+ TrustProxy: tc.trustProxy,+ }++ got := SecureBaseURL(req, opts)+ if tc.expectEmpty {+ assert.Empty(t, got, "expected empty (refuse), got %q", got)+ return+ }+ assert.Equal(t, tc.expectURL, got)+ })+ }+}++func TestValidProxyHost(t *testing.T) {+ good := []string{+ "example.com",+ "example.com:8080",+ "sub.example.com",+ "127.0.0.1",+ "127.0.0.1:8080",+ "[::1]",+ "[::1]:8080",+ "[2001:db8::1]:8443",+ }+ for _, h := range good {+ t.Run("good/"+h, func(t *testing.T) {+ assert.True(t, validProxyHost(h), "expected valid: %q", h)+ })+ }++ bad := []string{+ "",+ "https://example.com",+ "example.com/path",+ "example.com?q=1",+ "example.com#frag",+ "example .com",+ "example.com\r\nX-Other: foo",+ "example.com\n",+ "foo\\bar",+ "example.com:abc:8080:more", // malformed+ }+ for _, h := range bad {+ t.Run("bad/"+h, func(t *testing.T) {+ assert.False(t, validProxyHost(h), "expected invalid: %q", h)+ })+ }+}++func TestFirstHeaderValue(t *testing.T) {+ cases := []struct {+ in, want string+ }{+ {"", ""},+ {"foo", "foo"},+ {"foo, bar", "foo"},+ {"foo,bar", "foo"},+ {" foo , bar", "foo"},+ {"https, http", schemeHTTPS},+ }+ for _, c := range cases {+ t.Run(c.in, func(t *testing.T) {+ assert.Equal(t, c.want, firstHeaderValue(c.in))+ })+ }+}diff --git a/backend/app/api/handlers/v1/v1_ctrl_auth.go b/backend/app/api/handlers/v1/v1_ctrl_auth.goindex 89e2247e..0d4a341f 100644--- a/backend/app/api/handlers/v1/v1_ctrl_auth.go+++ b/backend/app/api/handlers/v1/v1_ctrl_auth.go@@ -143,6 +143,174 @@ func (ctrl *V1Controller) HandleAuthLogin(ps ...AuthProvider) errchain.HandlerFu}}+type (+ ForgotPasswordRequest struct {+ Email string `json:"email" validate:"required" example:"[email protected]"`+ }++ // ResetPasswordRequest carries the token from the email link and the new+ // password. The constraints below feed the OpenAPI spec via swaggo and+ // are also enforced by the handler so the spec doesn't over-promise.+ //+ // password min=6 matches the frontend's PASSWORD_MIN_LENGTH. No max:+ // argon2id has no practical input limit, and the inbound body is already+ // bounded by mid.MaxBodySize. Token min=20 fits the 26-char base32 output+ // of hasher.GenerateToken with a little slack; it's spec-only since the+ // lookup itself rejects anything that doesn't match a stored hash.+ ResetPasswordRequest struct {+ Token string `json:"token" validate:"required,min=20"`+ NewPassword string `json:"password" validate:"required,min=6"`+ }+)++// resetPasswordMinLength is enforced server-side to keep the OpenAPI spec+// honest about its minLength constraint.+const resetPasswordMinLength = 6++// HandleForgotPassword godoc+//+// @Summary Request Password Reset+// @Description Sends a password reset email if the address is associated with a local account.+// @Description Always returns 204 on success to avoid leaking whether the email is registered.+// @Tags Authentication+// @Accept application/json+// @Produce json+// @Param payload body ForgotPasswordRequest true "Email"+// @Success 204+// @Failure 400 {string} string "missing or invalid request body, or empty email field"+// @Failure 403 {string} string "demo mode is enabled or local login is disabled"+// @Failure 500 {string} string "internal error while processing the request"+// @Router /v1/users/forgot-password [POST]+func (ctrl *V1Controller) HandleForgotPassword() errchain.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) error {+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleForgotPassword")+ defer span.End()++ if ctrl.isDemo {+ span.SetAttributes(attribute.String("forgot.outcome", "demo_blocked"))+ return validate.NewRequestError(nil, http.StatusForbidden)+ }++ if !ctrl.config.Options.AllowLocalLogin {+ span.SetAttributes(attribute.String("forgot.outcome", "local_login_disabled"))+ return validate.NewRequestError(errors.New("local login is not enabled"), http.StatusForbidden)+ }++ var body ForgotPasswordRequest+ if err := server.Decode(r, &body); err != nil {+ span.SetAttributes(attribute.String("forgot.outcome", "decode_failed"))+ return validate.NewRequestError(err, http.StatusBadRequest)+ }+ body.Email = strings.TrimSpace(body.Email)+ span.SetAttributes(attribute.Int("user.email.length", len(body.Email)))+ if body.Email == "" {+ span.SetAttributes(attribute.String("forgot.outcome", "missing_email"))+ return validate.NewRequestError(errors.New("email is required"), http.StatusBadRequest)+ }++ // SECURITY: The two configuration failures below (SMTP not ready,+ // no safe base URL) MUST NOT be reported to the client. The whole+ // point of the "always 204" response is that an unauthenticated+ // caller can't probe the server for state — including configuration+ // state. Returning 503 here would let an attacker fingerprint+ // whether the instance has SMTP configured or what HBOX_OPTIONS_*+ // values are set, which is reconnaissance info we deliberately+ // withhold. Operators discover these via server logs instead.+ if !ctrl.svc.User.MailerReady() {+ span.SetAttributes(attribute.String("forgot.outcome", "mailer_not_configured"))+ log.Warn().Msg("forgot-password requested but SMTP mailer is not configured; no email will be sent")+ return server.JSON(w, http.StatusNoContent, nil)+ }++ // SecureBaseURL refuses Referer-based fallback so an attacker can't+ // poison the link in the victim's email by sending a forged Referer.+ baseURL := SecureBaseURL(r, &ctrl.config.Options)+ if baseURL == "" {+ span.SetAttributes(attribute.String("forgot.outcome", "no_safe_base_url"))+ log.Warn().Msg("forgot-password requested but no safe base URL is available; set HBOX_OPTIONS_HOSTNAME to enable")+ return server.JSON(w, http.StatusNoContent, nil)+ }++ if err := ctrl.svc.User.RequestPasswordReset(spanCtx, body.Email, baseURL); err != nil {+ recordCtrlSpanError(span, err)+ span.SetAttributes(attribute.String("forgot.outcome", "service_failed"))+ log.Err(err).Msg("password reset request failed")+ // Don't leak the underlying error to the client; respond with 500+ // but no details.+ return validate.NewRequestError(errors.New("internal error"), http.StatusInternalServerError)+ }++ span.SetAttributes(attribute.String("forgot.outcome", "ok"))+ return server.JSON(w, http.StatusNoContent, nil)+ }+}++// HandleResetPassword godoc+//+// @Summary Reset Password+// @Description Consumes a single-use reset token and changes the user's password.+// @Description On success, all existing sessions for the user are revoked.+// @Tags Authentication+// @Accept application/json+// @Produce json+// @Param payload body ResetPasswordRequest true "Token + new password"+// @Success 204+// @Failure 400 {string} string "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used"+// @Failure 403 {string} string "demo mode is enabled or local login is disabled"+// @Failure 500 {string} string "internal error while processing the request"+// @Router /v1/users/reset-password [POST]+func (ctrl *V1Controller) HandleResetPassword() errchain.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) error {+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleResetPassword")+ defer span.End()++ if ctrl.isDemo {+ span.SetAttributes(attribute.String("reset.outcome", "demo_blocked"))+ return validate.NewRequestError(nil, http.StatusForbidden)+ }++ if !ctrl.config.Options.AllowLocalLogin {+ span.SetAttributes(attribute.String("reset.outcome", "local_login_disabled"))+ return validate.NewRequestError(errors.New("local login is not enabled"), http.StatusForbidden)+ }++ var body ResetPasswordRequest+ if err := server.Decode(r, &body); err != nil {+ span.SetAttributes(attribute.String("reset.outcome", "decode_failed"))+ return validate.NewRequestError(err, http.StatusBadRequest)+ }+ span.SetAttributes(+ attribute.Int("token.length", len(body.Token)),+ attribute.Int("password.new.length", len(body.NewPassword)),+ )++ // Enforce the documented minimum so the OpenAPI spec's minLength on+ // `password` is honored. Token bounds are spec-only (the hash lookup+ // naturally rejects bad tokens), so we don't re-check them here.+ if len(body.NewPassword) < resetPasswordMinLength {+ span.SetAttributes(attribute.String("reset.outcome", "password_too_short"))+ return validate.NewRequestError(+ fmt.Errorf("password must be at least %d characters", resetPasswordMinLength),+ http.StatusBadRequest,+ )+ }++ if err := ctrl.svc.User.ResetPassword(spanCtx, body.Token, body.NewPassword); err != nil {+ if errors.Is(err, services.ErrorPasswordResetInvalid) {+ span.SetAttributes(attribute.String("reset.outcome", "token_invalid"))+ return validate.NewRequestError(err, http.StatusBadRequest)+ }+ recordCtrlSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "service_failed"))+ log.Err(err).Msg("password reset failed")+ return validate.NewRequestError(errors.New("internal error"), http.StatusInternalServerError)+ }++ span.SetAttributes(attribute.String("reset.outcome", "success"))+ return server.JSON(w, http.StatusNoContent, nil)+ }+}+// HandleAuthLogout godoc//// @Summary User Logoutdiff --git a/backend/app/api/main.go b/backend/app/api/main.goindex 50659af7..d45cdf48 100644--- a/backend/app/api/main.go+++ b/backend/app/api/main.go@@ -5,6 +5,7 @@ import ("errors""fmt""net/http"+ "os""runtime""strings""time"@@ -14,7 +15,6 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/core/services""github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus""github.com/sysadminsmedia/homebox/backend/internal/data/ent"- "github.com/sysadminsmedia/homebox/backend/internal/data/migrations""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/sys/analytics""github.com/sysadminsmedia/homebox/backend/internal/sys/config"@@ -26,7 +26,6 @@ import ("github.com/go-chi/chi/v5/middleware""github.com/hay-kot/httpkit/errchain""github.com/hay-kot/httpkit/graceful"- "github.com/pressly/goose/v3""github.com/riandyrn/otelchi"otelchimetric "github.com/riandyrn/otelchi/metric""github.com/rs/zerolog"@@ -34,9 +33,6 @@ import ("github.com/rs/zerolog/pkgerrors""go.balki.me/anyhttp"- "entgo.io/ent/dialect"- entsql "entgo.io/ent/dialect/sql"-_ "github.com/jackc/pgx/v5/stdlib"_ "github.com/sysadminsmedia/homebox/backend/internal/data/migrations/postgres"_ "github.com/sysadminsmedia/homebox/backend/internal/data/migrations/sqlite3"@@ -95,6 +91,12 @@ func validatePostgresSSLMode(sslMode string) bool {func main() {zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack+ // Subcommand dispatch happens before config.New so the conf package never+ // sees positional args (which it would treat as an error).+ if handled, code := runResetPasswordCLI(os.Args); handled {+ os.Exit(code)+ }+cfg, err := config.New(build(), "Homebox inventory management system")if err != nil {panic(err)@@ -134,56 +136,10 @@ func run(cfg *config.Config) error {// =========================================================================// Initialize Database & Repos- err = setupStorageDir(cfg)+ c, err := setupDatabase(cfg, otelProvider)if err != nil {return err}-- if strings.ToLower(cfg.Database.Driver) == config.DriverPostgres {- if !validatePostgresSSLMode(cfg.Database.SslMode) {- log.Error().Str("sslmode", cfg.Database.SslMode).Msg("invalid sslmode")- return fmt.Errorf("invalid sslmode: %s", cfg.Database.SslMode)- }- }-- databaseURL, err := setupDatabaseURL(cfg)- if err != nil {- return err- }-- sqlDriver := strings.ToLower(cfg.Database.Driver)- var driverName string- switch sqlDriver {- case config.DriverPostgres:- driverName = "pgx"- sqlDriver = dialect.Postgres- case config.DriverSqlite3, "sqlite":- driverName = "sqlite3"- sqlDriver = dialect.SQLite- default:- return fmt.Errorf("unsupported driver: %s", sqlDriver)- }-- db, err := otelProvider.OpenDatabase(driverName, databaseURL)- if err != nil {- log.Error().- Err(err).- Str("driver", strings.ToLower(cfg.Database.Driver)).- Str("host", cfg.Database.Host).- Str("port", cfg.Database.Port).- Str("database", cfg.Database.Database).- Msg("failed opening connection to {driver} database at {host}:{port}/{database}")- return fmt.Errorf("failed opening connection to %s database at %s:%s/%s: %w",- strings.ToLower(cfg.Database.Driver),- cfg.Database.Host,- cfg.Database.Port,- cfg.Database.Database,- err,- )- }-- drv := entsql.OpenDB(sqlDriver, db)- c := ent.NewClient(ent.Driver(drv))defer func(c *ent.Client) {err := c.Close()if err != nil {@@ -191,24 +147,6 @@ func run(cfg *config.Config) error {}}(c)- migrationsFs, err := migrations.Migrations(strings.ToLower(cfg.Database.Driver))- if err != nil {- return fmt.Errorf("failed to get migrations for %s: %w", strings.ToLower(cfg.Database.Driver), err)- }-- goose.SetBaseFS(migrationsFs)- err = goose.SetDialect(strings.ToLower(cfg.Database.Driver))- if err != nil {- log.Error().Str("driver", cfg.Database.Driver).Msg("unsupported database driver")- return fmt.Errorf("unsupported database driver: %s", cfg.Database.Driver)- }-- err = goose.Up(c.Sql(), strings.ToLower(cfg.Database.Driver))- if err != nil {- log.Error().Err(err).Msg("failed to migrate database")- return err- }-collectFuncs, err := loadCurrencies(cfg)if err != nil {return err@@ -240,6 +178,7 @@ func run(cfg *config.Config) error {services.WithAutoIncrementAssetID(cfg.Options.AutoIncrementAssetID),services.WithCurrencies(currencyData),services.WithNotifierConfig(&cfg.Notifier),+ services.WithMailer(&app.mailer),)ensureAssetIDs(app)@@ -255,8 +194,8 @@ func run(cfg *config.Config) error {otelChiBaseCfg := otelchimetric.NewBaseConfig(cfg.Otel.ServiceName, otelchimetric.WithMeterProvider(otelProvider.MeterProvider()))router.Use(otelchi.Middleware(cfg.Otel.ServiceName, otelchi.WithChiRoutes(router)),- otelchimetric.NewResponseSizeBytes(otelChiBaseCfg),- otelchimetric.NewRequestInFlight(otelChiBaseCfg),+ otelchimetric.NewServerResponseBodySize(otelChiBaseCfg),+ otelchimetric.NewServerActiveRequests(otelChiBaseCfg),)}diff --git a/backend/app/api/middleware_ratelimit_test.go b/backend/app/api/middleware_ratelimit_test.goindex 1503e6b0..0f7733c4 100644--- a/backend/app/api/middleware_ratelimit_test.go+++ b/backend/app/api/middleware_ratelimit_test.go@@ -10,7 +10,12 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/sys/config")-const proxyRemoteAddr = "10.0.0.1:1234"+const (+ proxyRemoteAddr = "10.0.0.1:1234"+ caseDirectConn = "DirectConnection"+ caseProxyXRealIP = "ProxyXRealIP"+ testClientIPAddress = "192.168.1.1"+)func TestSimpleRateLimiter(t *testing.T) {type testCase struct {@@ -21,12 +26,12 @@ func TestSimpleRateLimiter(t *testing.T) {tests := []testCase{{- name: "DirectConnection",+ name: caseDirectConn,trustProxy: false,setupReq: func(r *http.Request, ip string) { r.RemoteAddr = ip + ":1234" },},{- name: "ProxyXRealIP",+ name: caseProxyXRealIP,trustProxy: true,setupReq: func(r *http.Request, ip string) {r.RemoteAddr = proxyRemoteAddr // Proxy IP@@ -48,7 +53,7 @@ func TestSimpleRateLimiter(t *testing.T) {// Create a rate limiter that allows 3 requests per 10 secondslimiter := newSimpleRateLimiter(3, 10*time.Second, tc.trustProxy)t.Cleanup(func() { limiter.Stop() })- clientIP := "192.168.1.1"+ clientIP := testClientIPAddress// Helper to get IPgetIP := func(ip string) string {@@ -96,12 +101,12 @@ func TestSimpleRateLimiterRefill(t *testing.T) {tests := []testCase{{- name: "DirectConnection",+ name: caseDirectConn,trustProxy: false,setupReq: func(r *http.Request, ip string) { r.RemoteAddr = ip + ":1234" },},{- name: "ProxyXRealIP",+ name: caseProxyXRealIP,trustProxy: true,setupReq: func(r *http.Request, ip string) {r.RemoteAddr = proxyRemoteAddr // Proxy IP@@ -115,7 +120,7 @@ func TestSimpleRateLimiterRefill(t *testing.T) {// Create a rate limiter that allows 2 requests per 100mslimiter := newSimpleRateLimiter(2, 100*time.Millisecond, tc.trustProxy)t.Cleanup(func() { limiter.Stop() })- clientIP := "192.168.1.1"+ clientIP := testClientIPAddress// Helper to get IPgetIP := func(ip string) string {@@ -157,12 +162,12 @@ func TestSimpleRateLimiterConcurrent(t *testing.T) {tests := []testCase{{- name: "DirectConnection",+ name: caseDirectConn,trustProxy: false,setupReq: func(r *http.Request, ip string) { r.RemoteAddr = ip + ":1234" },},{- name: "ProxyXRealIP",+ name: caseProxyXRealIP,trustProxy: true,setupReq: func(r *http.Request, ip string) {r.RemoteAddr = proxyRemoteAddr // Proxy IP@@ -175,7 +180,7 @@ func TestSimpleRateLimiterConcurrent(t *testing.T) {t.Run(tc.name, func(t *testing.T) {limiter := newSimpleRateLimiter(10, time.Second, tc.trustProxy)t.Cleanup(func() { limiter.Stop() })- clientIP := "192.168.1.1"+ clientIP := testClientIPAddress// Helper to get IPgetIP := func(ip string) string {@@ -222,12 +227,12 @@ func TestSimpleRateLimiterCleanup(t *testing.T) {tests := []testCase{{- name: "DirectConnection",+ name: caseDirectConn,trustProxy: false,setupReq: func(r *http.Request, ip string) { r.RemoteAddr = ip + ":1234" },},{- name: "ProxyXRealIP",+ name: caseProxyXRealIP,trustProxy: true,setupReq: func(r *http.Request, ip string) {r.RemoteAddr = proxyRemoteAddr // Proxy IP@@ -291,12 +296,12 @@ func TestSimpleRateLimiterCleanupPreservesActive(t *testing.T) {tests := []testCase{{- name: "DirectConnection",+ name: caseDirectConn,trustProxy: false,setupReq: func(r *http.Request, ip string) { r.RemoteAddr = ip + ":1234" },},{- name: "ProxyXRealIP",+ name: caseProxyXRealIP,trustProxy: true,setupReq: func(r *http.Request, ip string) {r.RemoteAddr = proxyRemoteAddr // Proxy IPdiff --git a/backend/app/api/recurring.go b/backend/app/api/recurring.goindex 8c276836..4e68b64d 100644--- a/backend/app/api/recurring.go+++ b/backend/app/api/recurring.go@@ -36,6 +36,13 @@ func registerRecurringTasks(app *app, cfg *config.Config, runner *graceful.Runne}}))+ runner.AddPlugin(NewTask("purge-password-reset-tokens", 24*time.Hour, func(ctx context.Context) {+ _, err := app.repos.PasswordResetTokens.PurgeExpired(ctx)+ if err != nil {+ log.Error().Err(err).Msg("failed to purge expired password reset tokens")+ }+ }))+runner.AddPlugin(NewTask("purge-invitations", 24*time.Hour, func(ctx context.Context) {_, err := app.repos.Groups.InvitationPurge(ctx)if err != nil {diff --git a/backend/app/api/routes.go b/backend/app/api/routes.goindex e354e181..87ba33e4 100644--- a/backend/app/api/routes.go+++ b/backend/app/api/routes.go@@ -88,6 +88,8 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllRr.Post("/users/register", chain.ToHandlerFunc(v1Ctrl.HandleUserRegistration()))r.Post("/users/login", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogin(providers...), a.mwAuthRateLimit))+ r.Post("/users/forgot-password", chain.ToHandlerFunc(v1Ctrl.HandleForgotPassword(), a.mwAuthRateLimit))+ r.Post("/users/reset-password", chain.ToHandlerFunc(v1Ctrl.HandleResetPassword(), a.mwAuthRateLimit))if a.conf.OIDC.Enabled {r.Get("/users/login/oidc", chain.ToHandlerFunc(v1Ctrl.HandleOIDCLogin(), a.mwAuthRateLimit))diff --git a/backend/app/api/setup.go b/backend/app/api/setup.goindex 3a38c327..3fb86190 100644--- a/backend/app/api/setup.go+++ b/backend/app/api/setup.go@@ -7,11 +7,98 @@ import ("path/filepath""strings"+ "entgo.io/ent/dialect"+ entsql "entgo.io/ent/dialect/sql"+ "github.com/pressly/goose/v3""github.com/rs/zerolog/log""github.com/sysadminsmedia/homebox/backend/internal/core/currencies"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/migrations""github.com/sysadminsmedia/homebox/backend/internal/sys/config"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/otel")+// setupDatabase prepares the storage directory, validates the driver/SSL+// config, opens the database (through the OTel provider for tracing), runs+// any pending goose migrations, and returns an ent client. Caller owns the+// client and must Close() it. Extracted from run() to keep that function+// under the gocyclo threshold.+func setupDatabase(cfg *config.Config, otelProvider *otel.Provider) (*ent.Client, error) {+ if err := setupStorageDir(cfg); err != nil {+ return nil, err+ }++ driver := strings.ToLower(cfg.Database.Driver)+ if driver == config.DriverPostgres {+ if !validatePostgresSSLMode(cfg.Database.SslMode) {+ log.Error().Str("sslmode", cfg.Database.SslMode).Msg("invalid sslmode")+ return nil, fmt.Errorf("invalid sslmode: %s", cfg.Database.SslMode)+ }+ }++ databaseURL, err := setupDatabaseURL(cfg)+ if err != nil {+ return nil, err+ }++ driverName, dialectName, err := resolveDriver(driver)+ if err != nil {+ return nil, err+ }++ db, err := otelProvider.OpenDatabase(driverName, databaseURL)+ if err != nil {+ log.Error().+ Err(err).+ Str("driver", driver).+ Str("host", cfg.Database.Host).+ Str("port", cfg.Database.Port).+ Str("database", cfg.Database.Database).+ Msg("failed opening connection to {driver} database at {host}:{port}/{database}")+ return nil, fmt.Errorf("failed opening connection to %s database at %s:%s/%s: %w",+ driver, cfg.Database.Host, cfg.Database.Port, cfg.Database.Database, err)+ }++ c := ent.NewClient(ent.Driver(entsql.OpenDB(dialectName, db)))++ if err := runMigrations(c, driver); err != nil {+ _ = c.Close()+ return nil, err+ }+ return c, nil+}++// resolveDriver maps the configured driver name onto the (database/sql, ent+// dialect) pair we use throughout the app.+func resolveDriver(driver string) (sqlDriverName, entDialect string, err error) {+ switch driver {+ case config.DriverPostgres:+ return "pgx", dialect.Postgres, nil+ case config.DriverSqlite3, "sqlite":+ return "sqlite3", dialect.SQLite, nil+ default:+ return "", "", fmt.Errorf("unsupported driver: %s", driver)+ }+}++// runMigrations applies all pending goose migrations for the given driver.+func runMigrations(c *ent.Client, driver string) error {+ migrationsFs, err := migrations.Migrations(driver)+ if err != nil {+ return fmt.Errorf("failed to get migrations for %s: %w", driver, err)+ }+ goose.SetBaseFS(migrationsFs)+ if err := goose.SetDialect(driver); err != nil {+ log.Error().Str("driver", driver).Msg("unsupported database driver")+ return fmt.Errorf("unsupported database driver: %s", driver)+ }+ if err := goose.Up(c.Sql(), driver); err != nil {+ log.Error().Err(err).Msg("failed to migrate database")+ return err+ }+ return nil+}+// setupStorageDir handles the creation and validation of the storage directory.func setupStorageDir(cfg *config.Config) error {if strings.HasPrefix(cfg.Storage.ConnString, "file:///./") {diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.goindex d45a2d10..103f1166 100644--- a/backend/app/api/static/docs/docs.go+++ b/backend/app/api/static/docs/docs.go@@ -1439,36 +1439,6 @@ const docTemplate = `{}}}- },- "post": {- "security": [- {- "Bearer": []- }- ],- "produces": [- "application/json"- ],- "tags": [- "Group"- ],- "summary": "Add User to Group",- "parameters": [- {- "description": "User ID",- "name": "payload",- "in": "body",- "required": true,- "schema": {- "$ref": "#/definitions/v1.GroupMemberAdd"- }- }- ],- "responses": {- "204": {- "description": "No Content"- }- }}},"/v1/groups/members/{user_id}": {@@ -2505,6 +2475,55 @@ const docTemplate = `{}}},+ "/v1/users/forgot-password": {+ "post": {+ "description": "Sends a password reset email if the address is associated with a local account.\nAlways returns 204 on success to avoid leaking whether the email is registered.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Request Password Reset",+ "parameters": [+ {+ "description": "Email",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ForgotPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "missing or invalid request body, or empty email field",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/login": {"post": {"consumes": [@@ -2660,6 +2679,55 @@ const docTemplate = `{}}},+ "/v1/users/reset-password": {+ "post": {+ "description": "Consumes a single-use reset token and changes the user's password.\nOn success, all existing sessions for the user are revoked.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Reset Password",+ "parameters": [+ {+ "description": "Token + new password",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ResetPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/self": {"get": {"security": [@@ -3718,6 +3786,13 @@ const docTemplate = `{"$ref": "#/definitions/ent.Tag"}},+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ },"users": {"description": "Users holds the value of the users edge.","type": "array",@@ -3904,6 +3979,59 @@ const docTemplate = `{}}},+ "ent.PasswordResetTokens": {+ "type": "object",+ "properties": {+ "created_at": {+ "description": "CreatedAt holds the value of the \"created_at\" field.",+ "type": "string"+ },+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the PasswordResetTokensQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.PasswordResetTokensEdges"+ }+ ]+ },+ "expires_at": {+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",+ "type": "string"+ },+ "id": {+ "description": "ID of the ent.",+ "type": "string"+ },+ "token": {+ "description": "Token holds the value of the \"token\" field.",+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "updated_at": {+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",+ "type": "string"+ },+ "used_at": {+ "description": "UsedAt holds the value of the \"used_at\" field.",+ "type": "string"+ }+ }+ },+ "ent.PasswordResetTokensEdges": {+ "type": "object",+ "properties": {+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]+ }+ }+ },"ent.Tag": {"type": "object","properties": {@@ -4097,14 +4225,6 @@ const docTemplate = `{"description": "OidcSubject holds the value of the \"oidc_subject\" field.","type": "string"},- "role": {- "description": "Role holds the value of the \"role\" field.",- "allOf": [- {- "$ref": "#/definitions/user.Role"- }- ]- },"settings": {"description": "Settings holds the value of the \"settings\" field.","type": "object",@@ -4150,6 +4270,70 @@ const docTemplate = `{"items": {"$ref": "#/definitions/ent.Notifier"}+ },+ "password_reset_tokens": {+ "description": "PasswordResetTokens holds the value of the password_reset_tokens edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.PasswordResetTokens"+ }+ },+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ }+ }+ },+ "ent.UserGroup": {+ "type": "object",+ "properties": {+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserGroupQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.UserGroupEdges"+ }+ ]+ },+ "group_id": {+ "description": "GroupID holds the value of the \"group_id\" field.",+ "type": "string"+ },+ "role": {+ "description": "Role holds the value of the \"role\" field.",+ "allOf": [+ {+ "$ref": "#/definitions/usergroup.Role"+ }+ ]+ },+ "user_id": {+ "description": "UserID holds the value of the \"user_id\" field.",+ "type": "string"+ }+ }+ },+ "ent.UserGroupEdges": {+ "type": "object",+ "properties": {+ "group": {+ "description": "Group holds the value of the group edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Group"+ }+ ]+ },+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]}}},@@ -5647,9 +5831,6 @@ const docTemplate = `{"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"isSuperuser": {"type": "boolean"},@@ -5673,9 +5854,6 @@ const docTemplate = `{"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"name": {"type": "string"}@@ -5772,7 +5950,7 @@ const docTemplate = `{"TypeTime"]},- "user.Role": {+ "usergroup.Role": {"type": "string","enum": ["user",@@ -5900,6 +6078,18 @@ const docTemplate = `{}}},+ "v1.ForgotPasswordRequest": {+ "type": "object",+ "required": [+ "email"+ ],+ "properties": {+ "email": {+ "type": "string",+ "example": "[email protected]"+ }+ }+ },"v1.GroupAcceptInvitationResponse": {"type": "object","properties": {@@ -5944,17 +6134,6 @@ const docTemplate = `{}}},- "v1.GroupMemberAdd": {- "type": "object",- "required": [- "userId"- ],- "properties": {- "userId": {- "type": "string"- }- }- },"v1.LoginForm": {"type": "object","properties": {@@ -5988,6 +6167,23 @@ const docTemplate = `{}}},+ "v1.ResetPasswordRequest": {+ "type": "object",+ "required": [+ "password",+ "token"+ ],+ "properties": {+ "password": {+ "type": "string",+ "minLength": 6+ },+ "token": {+ "type": "string",+ "minLength": 20+ }+ }+ },"v1.TelemetryStatus": {"type": "object","properties": {diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.jsonindex f3a2ab32..d5a19e3d 100644--- a/backend/app/api/static/docs/openapi-3.json+++ b/backend/app/api/static/docs/openapi-3.json@@ -1548,33 +1548,6 @@}}}- },- "post": {- "security": [- {- "Bearer": []- }- ],- "tags": [- "Group"- ],- "summary": "Add User to Group",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/v1.GroupMemberAdd"- }- }- },- "description": "User ID",- "required": true- },- "responses": {- "204": {- "description": "No Content"- }- }}},"/v1/groups/members/{user_id}": {@@ -2682,6 +2655,61 @@}}},+ "/v1/users/forgot-password": {+ "post": {+ "description": "Sends a password reset email if the address is associated with a local account.\nAlways returns 204 on success to avoid leaking whether the email is registered.",+ "tags": [+ "Authentication"+ ],+ "summary": "Request Password Reset",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/v1.ForgotPasswordRequest"+ }+ }+ },+ "description": "Email",+ "required": true+ },+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "missing or invalid request body, or empty email field",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/v1/users/login": {"post": {"tags": [@@ -2845,6 +2873,61 @@}}},+ "/v1/users/reset-password": {+ "post": {+ "description": "Consumes a single-use reset token and changes the user's password.\nOn success, all existing sessions for the user are revoked.",+ "tags": [+ "Authentication"+ ],+ "summary": "Reset Password",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/v1.ResetPasswordRequest"+ }+ }+ },+ "description": "Token + new password",+ "required": true+ },+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/v1/users/self": {"get": {"security": [@@ -3922,6 +4005,13 @@"$ref": "#/components/schemas/ent.Tag"}},+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.UserGroup"+ }+ },"users": {"description": "Users holds the value of the users edge.","type": "array",@@ -4108,6 +4198,59 @@}}},+ "ent.PasswordResetTokens": {+ "type": "object",+ "properties": {+ "created_at": {+ "description": "CreatedAt holds the value of the \"created_at\" field.",+ "type": "string"+ },+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the PasswordResetTokensQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.PasswordResetTokensEdges"+ }+ ]+ },+ "expires_at": {+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",+ "type": "string"+ },+ "id": {+ "description": "ID of the ent.",+ "type": "string"+ },+ "token": {+ "description": "Token holds the value of the \"token\" field.",+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "updated_at": {+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",+ "type": "string"+ },+ "used_at": {+ "description": "UsedAt holds the value of the \"used_at\" field.",+ "type": "string"+ }+ }+ },+ "ent.PasswordResetTokensEdges": {+ "type": "object",+ "properties": {+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.User"+ }+ ]+ }+ }+ },"ent.Tag": {"type": "object","properties": {@@ -4301,14 +4444,6 @@"description": "OidcSubject holds the value of the \"oidc_subject\" field.","type": "string"},- "role": {- "description": "Role holds the value of the \"role\" field.",- "allOf": [- {- "$ref": "#/components/schemas/user.Role"- }- ]- },"settings": {"description": "Settings holds the value of the \"settings\" field.","type": "object",@@ -4354,6 +4489,70 @@"items": {"$ref": "#/components/schemas/ent.Notifier"}+ },+ "password_reset_tokens": {+ "description": "PasswordResetTokens holds the value of the password_reset_tokens edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.PasswordResetTokens"+ }+ },+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.UserGroup"+ }+ }+ }+ },+ "ent.UserGroup": {+ "type": "object",+ "properties": {+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserGroupQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.UserGroupEdges"+ }+ ]+ },+ "group_id": {+ "description": "GroupID holds the value of the \"group_id\" field.",+ "type": "string"+ },+ "role": {+ "description": "Role holds the value of the \"role\" field.",+ "allOf": [+ {+ "$ref": "#/components/schemas/usergroup.Role"+ }+ ]+ },+ "user_id": {+ "description": "UserID holds the value of the \"user_id\" field.",+ "type": "string"+ }+ }+ },+ "ent.UserGroupEdges": {+ "type": "object",+ "properties": {+ "group": {+ "description": "Group holds the value of the group edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.Group"+ }+ ]+ },+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.User"+ }+ ]}}},@@ -5851,9 +6050,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"isSuperuser": {"type": "boolean"},@@ -5877,9 +6073,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"name": {"type": "string"}@@ -5976,7 +6169,7 @@"TypeTime"]},- "user.Role": {+ "usergroup.Role": {"type": "string","enum": ["user",@@ -6104,6 +6297,18 @@}}},+ "v1.ForgotPasswordRequest": {+ "type": "object",+ "required": [+ "email"+ ],+ "properties": {+ "email": {+ "type": "string",+ "example": "[email protected]"+ }+ }+ },"v1.GroupAcceptInvitationResponse": {"type": "object","properties": {@@ -6148,17 +6353,6 @@}}},- "v1.GroupMemberAdd": {- "type": "object",- "required": [- "userId"- ],- "properties": {- "userId": {- "type": "string"- }- }- },"v1.LoginForm": {"type": "object","properties": {@@ -6192,6 +6386,23 @@}}},+ "v1.ResetPasswordRequest": {+ "type": "object",+ "required": [+ "password",+ "token"+ ],+ "properties": {+ "password": {+ "type": "string",+ "minLength": 6+ },+ "token": {+ "type": "string",+ "minLength": 20+ }+ }+ },"v1.TelemetryStatus": {"type": "object","properties": {diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yamlindex 868713ae..33db3b0a 100644--- a/backend/app/api/static/docs/openapi-3.yaml+++ b/backend/app/api/static/docs/openapi-3.yaml@@ -923,22 +923,6 @@ paths:type: arrayitems:$ref: "#/components/schemas/repo.UserSummary"- post:- security:- - Bearer: []- tags:- - Group- summary: Add User to Group- requestBody:- content:- application/json:- schema:- $ref: "#/components/schemas/v1.GroupMemberAdd"- description: User ID- required: true- responses:- "204":- description: No Content"/v1/groups/members/{user_id}":delete:security:@@ -1588,6 +1572,44 @@ paths:responses:"204":description: No Content+ /v1/users/forgot-password:+ post:+ description: >-+ Sends a password reset email if the address is associated with a local+ account.++ Always returns 204 on success to avoid leaking whether the email is registered.+ tags:+ - Authentication+ summary: Request Password Reset+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/v1.ForgotPasswordRequest"+ description: Email+ required: true+ responses:+ "204":+ description: No Content+ "400":+ description: missing or invalid request body, or empty email field+ content:+ application/json:+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ content:+ application/json:+ schema:+ type: string+ "500":+ description: internal error while processing the request+ content:+ application/json:+ schema:+ type: string/v1/users/login:post:tags:@@ -1691,6 +1713,43 @@ paths:application/json:schema:type: string+ /v1/users/reset-password:+ post:+ description: |-+ Consumes a single-use reset token and changes the user's password.+ On success, all existing sessions for the user are revoked.+ tags:+ - Authentication+ summary: Reset Password+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/v1.ResetPasswordRequest"+ description: Token + new password+ required: true+ responses:+ "204":+ description: No Content+ "400":+ description: invalid request body, password shorter than the minimum length, or+ token that is invalid / expired / already used+ content:+ application/json:+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ content:+ application/json:+ schema:+ type: string+ "500":+ description: internal error while processing the request+ content:+ application/json:+ schema:+ type: string/v1/users/self:get:security:@@ -2409,6 +2468,11 @@ components:type: arrayitems:$ref: "#/components/schemas/ent.Tag"+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.UserGroup"users:description: Users holds the value of the users edge.type: array@@ -2537,6 +2601,43 @@ components:description: User holds the value of the user edge.allOf:- $ref: "#/components/schemas/ent.User"+ ent.PasswordResetTokens:+ type: object+ properties:+ created_at:+ description: CreatedAt holds the value of the "created_at" field.+ type: string+ edges:+ description: >-+ Edges holds the relations/edges for other nodes in the graph.++ The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ allOf:+ - $ref: "#/components/schemas/ent.PasswordResetTokensEdges"+ expires_at:+ description: ExpiresAt holds the value of the "expires_at" field.+ type: string+ id:+ description: ID of the ent.+ type: string+ token:+ description: Token holds the value of the "token" field.+ type: array+ items:+ type: integer+ updated_at:+ description: UpdatedAt holds the value of the "updated_at" field.+ type: string+ used_at:+ description: UsedAt holds the value of the "used_at" field.+ type: string+ ent.PasswordResetTokensEdges:+ type: object+ properties:+ user:+ description: User holds the value of the user edge.+ allOf:+ - $ref: "#/components/schemas/ent.User"ent.Tag:type: objectproperties:@@ -2674,10 +2775,6 @@ components:oidc_subject:description: OidcSubject holds the value of the "oidc_subject" field.type: string- role:- description: Role holds the value of the "role" field.- allOf:- - $ref: "#/components/schemas/user.Role"settings:description: Settings holds the value of the "settings" field.type: object@@ -2711,6 +2808,48 @@ components:type: arrayitems:$ref: "#/components/schemas/ent.Notifier"+ password_reset_tokens:+ description: PasswordResetTokens holds the value of the password_reset_tokens+ edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.PasswordResetTokens"+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.UserGroup"+ ent.UserGroup:+ type: object+ properties:+ edges:+ description: >-+ Edges holds the relations/edges for other nodes in the graph.++ The values are being populated by the UserGroupQuery when eager-loading is set.+ allOf:+ - $ref: "#/components/schemas/ent.UserGroupEdges"+ group_id:+ description: GroupID holds the value of the "group_id" field.+ type: string+ role:+ description: Role holds the value of the "role" field.+ allOf:+ - $ref: "#/components/schemas/usergroup.Role"+ user_id:+ description: UserID holds the value of the "user_id" field.+ type: string+ ent.UserGroupEdges:+ type: object+ properties:+ group:+ description: Group holds the value of the group edge.+ allOf:+ - $ref: "#/components/schemas/ent.Group"+ user:+ description: User holds the value of the user edge.+ allOf:+ - $ref: "#/components/schemas/ent.User"entityfield.Type:type: stringenum:@@ -3734,8 +3873,6 @@ components:type: stringid:type: string- isOwner:- type: booleanisSuperuser:type: booleanname:@@ -3751,8 +3888,6 @@ components:type: stringid:type: string- isOwner:- type: booleanname:type: stringrepo.UserUpdate:@@ -3816,7 +3951,7 @@ components:- TypeNumber- TypeBoolean- TypeTime- user.Role:+ usergroup.Role:type: stringenum:- user@@ -3902,6 +4037,14 @@ components:type: arrayitems:type: string+ v1.ForgotPasswordRequest:+ type: object+ required:+ properties:+ email:+ type: string+ example: [email protected]v1.GroupAcceptInvitationResponse:type: objectproperties:@@ -3931,13 +4074,6 @@ components:type: integermaximum: 100minimum: 1- v1.GroupMemberAdd:- type: object- required:- - userId- properties:- userId:- type: stringv1.LoginForm:type: objectproperties:@@ -3960,6 +4096,18 @@ components:type: stringenabled:type: boolean+ v1.ResetPasswordRequest:+ type: object+ required:+ - password+ - token+ properties:+ password:+ type: string+ minLength: 6+ token:+ type: string+ minLength: 20v1.TelemetryStatus:type: objectproperties:diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.jsonindex c6b0d506..0852613e 100644--- a/backend/app/api/static/docs/swagger.json+++ b/backend/app/api/static/docs/swagger.json@@ -1436,36 +1436,6 @@}}}- },- "post": {- "security": [- {- "Bearer": []- }- ],- "produces": [- "application/json"- ],- "tags": [- "Group"- ],- "summary": "Add User to Group",- "parameters": [- {- "description": "User ID",- "name": "payload",- "in": "body",- "required": true,- "schema": {- "$ref": "#/definitions/v1.GroupMemberAdd"- }- }- ],- "responses": {- "204": {- "description": "No Content"- }- }}},"/v1/groups/members/{user_id}": {@@ -2502,6 +2472,55 @@}}},+ "/v1/users/forgot-password": {+ "post": {+ "description": "Sends a password reset email if the address is associated with a local account.\nAlways returns 204 on success to avoid leaking whether the email is registered.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Request Password Reset",+ "parameters": [+ {+ "description": "Email",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ForgotPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "missing or invalid request body, or empty email field",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/login": {"post": {"consumes": [@@ -2657,6 +2676,55 @@}}},+ "/v1/users/reset-password": {+ "post": {+ "description": "Consumes a single-use reset token and changes the user's password.\nOn success, all existing sessions for the user are revoked.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Reset Password",+ "parameters": [+ {+ "description": "Token + new password",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ResetPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/self": {"get": {"security": [@@ -3715,6 +3783,13 @@"$ref": "#/definitions/ent.Tag"}},+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ },"users": {"description": "Users holds the value of the users edge.","type": "array",@@ -3901,6 +3976,59 @@}}},+ "ent.PasswordResetTokens": {+ "type": "object",+ "properties": {+ "created_at": {+ "description": "CreatedAt holds the value of the \"created_at\" field.",+ "type": "string"+ },+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the PasswordResetTokensQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.PasswordResetTokensEdges"+ }+ ]+ },+ "expires_at": {+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",+ "type": "string"+ },+ "id": {+ "description": "ID of the ent.",+ "type": "string"+ },+ "token": {+ "description": "Token holds the value of the \"token\" field.",+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "updated_at": {+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",+ "type": "string"+ },+ "used_at": {+ "description": "UsedAt holds the value of the \"used_at\" field.",+ "type": "string"+ }+ }+ },+ "ent.PasswordResetTokensEdges": {+ "type": "object",+ "properties": {+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]+ }+ }+ },"ent.Tag": {"type": "object","properties": {@@ -4094,14 +4222,6 @@"description": "OidcSubject holds the value of the \"oidc_subject\" field.","type": "string"},- "role": {- "description": "Role holds the value of the \"role\" field.",- "allOf": [- {- "$ref": "#/definitions/user.Role"- }- ]- },"settings": {"description": "Settings holds the value of the \"settings\" field.","type": "object",@@ -4147,6 +4267,70 @@"items": {"$ref": "#/definitions/ent.Notifier"}+ },+ "password_reset_tokens": {+ "description": "PasswordResetTokens holds the value of the password_reset_tokens edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.PasswordResetTokens"+ }+ },+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ }+ }+ },+ "ent.UserGroup": {+ "type": "object",+ "properties": {+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserGroupQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.UserGroupEdges"+ }+ ]+ },+ "group_id": {+ "description": "GroupID holds the value of the \"group_id\" field.",+ "type": "string"+ },+ "role": {+ "description": "Role holds the value of the \"role\" field.",+ "allOf": [+ {+ "$ref": "#/definitions/usergroup.Role"+ }+ ]+ },+ "user_id": {+ "description": "UserID holds the value of the \"user_id\" field.",+ "type": "string"+ }+ }+ },+ "ent.UserGroupEdges": {+ "type": "object",+ "properties": {+ "group": {+ "description": "Group holds the value of the group edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Group"+ }+ ]+ },+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]}}},@@ -5644,9 +5828,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"isSuperuser": {"type": "boolean"},@@ -5670,9 +5851,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"name": {"type": "string"}@@ -5769,7 +5947,7 @@"TypeTime"]},- "user.Role": {+ "usergroup.Role": {"type": "string","enum": ["user",@@ -5897,6 +6075,18 @@}}},+ "v1.ForgotPasswordRequest": {+ "type": "object",+ "required": [+ "email"+ ],+ "properties": {+ "email": {+ "type": "string",+ "example": "[email protected]"+ }+ }+ },"v1.GroupAcceptInvitationResponse": {"type": "object","properties": {@@ -5941,17 +6131,6 @@}}},- "v1.GroupMemberAdd": {- "type": "object",- "required": [- "userId"- ],- "properties": {- "userId": {- "type": "string"- }- }- },"v1.LoginForm": {"type": "object","properties": {@@ -5985,6 +6164,23 @@}}},+ "v1.ResetPasswordRequest": {+ "type": "object",+ "required": [+ "password",+ "token"+ ],+ "properties": {+ "password": {+ "type": "string",+ "minLength": 6+ },+ "token": {+ "type": "string",+ "minLength": 20+ }+ }+ },"v1.TelemetryStatus": {"type": "object","properties": {diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yamlindex decc84da..b9e8b30c 100644--- a/backend/app/api/static/docs/swagger.yaml+++ b/backend/app/api/static/docs/swagger.yaml@@ -546,6 +546,11 @@ definitions:items:$ref: '#/definitions/ent.Tag'type: array+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ items:+ $ref: '#/definitions/ent.UserGroup'+ type: arrayusers:description: Users holds the value of the users edge.items:@@ -672,6 +677,42 @@ definitions:- $ref: '#/definitions/ent.User'description: User holds the value of the user edge.type: object+ ent.PasswordResetTokens:+ properties:+ created_at:+ description: CreatedAt holds the value of the "created_at" field.+ type: string+ edges:+ allOf:+ - $ref: '#/definitions/ent.PasswordResetTokensEdges'+ description: |-+ Edges holds the relations/edges for other nodes in the graph.+ The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ expires_at:+ description: ExpiresAt holds the value of the "expires_at" field.+ type: string+ id:+ description: ID of the ent.+ type: string+ token:+ description: Token holds the value of the "token" field.+ items:+ type: integer+ type: array+ updated_at:+ description: UpdatedAt holds the value of the "updated_at" field.+ type: string+ used_at:+ description: UsedAt holds the value of the "used_at" field.+ type: string+ type: object+ ent.PasswordResetTokensEdges:+ properties:+ user:+ allOf:+ - $ref: '#/definitions/ent.User'+ description: User holds the value of the user edge.+ type: objectent.Tag:properties:color:@@ -805,10 +846,6 @@ definitions:oidc_subject:description: OidcSubject holds the value of the "oidc_subject" field.type: string- role:- allOf:- - $ref: '#/definitions/user.Role'- description: Role holds the value of the "role" field.settings:additionalProperties: truedescription: Settings holds the value of the "settings" field.@@ -842,6 +879,47 @@ definitions:items:$ref: '#/definitions/ent.Notifier'type: array+ password_reset_tokens:+ description: PasswordResetTokens holds the value of the password_reset_tokens+ edge.+ items:+ $ref: '#/definitions/ent.PasswordResetTokens'+ type: array+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ items:+ $ref: '#/definitions/ent.UserGroup'+ type: array+ type: object+ ent.UserGroup:+ properties:+ edges:+ allOf:+ - $ref: '#/definitions/ent.UserGroupEdges'+ description: |-+ Edges holds the relations/edges for other nodes in the graph.+ The values are being populated by the UserGroupQuery when eager-loading is set.+ group_id:+ description: GroupID holds the value of the "group_id" field.+ type: string+ role:+ allOf:+ - $ref: '#/definitions/usergroup.Role'+ description: Role holds the value of the "role" field.+ user_id:+ description: UserID holds the value of the "user_id" field.+ type: string+ type: object+ ent.UserGroupEdges:+ properties:+ group:+ allOf:+ - $ref: '#/definitions/ent.Group'+ description: Group holds the value of the group edge.+ user:+ allOf:+ - $ref: '#/definitions/ent.User'+ description: User holds the value of the user edge.type: objectentityfield.Type:enum:@@ -1865,8 +1943,6 @@ definitions:type: arrayid:type: string- isOwner:- type: booleanisSuperuser:type: booleanname:@@ -1882,8 +1958,6 @@ definitions:type: stringid:type: string- isOwner:- type: booleanname:type: stringtype: object@@ -1948,7 +2022,7 @@ definitions:- TypeNumber- TypeBoolean- TypeTime- user.Role:+ usergroup.Role:enum:- user- user@@ -2034,6 +2108,14 @@ definitions:- name- parentIdtype: object+ v1.ForgotPasswordRequest:+ properties:+ email:+ example: [email protected]+ type: string+ required:+ type: objectv1.GroupAcceptInvitationResponse:properties:id:@@ -2063,13 +2145,6 @@ definitions:required:- usestype: object- v1.GroupMemberAdd:- properties:- userId:- type: string- required:- - userId- type: objectv1.LoginForm:properties:password:@@ -2092,6 +2167,18 @@ definitions:enabled:type: booleantype: object+ v1.ResetPasswordRequest:+ properties:+ password:+ minLength: 6+ type: string+ token:+ minLength: 20+ type: string+ required:+ - password+ - token+ type: objectv1.TelemetryStatus:properties:enabled:@@ -3020,24 +3107,6 @@ paths:summary: Get All Group Memberstags:- Group- post:- parameters:- - description: User ID- in: body- name: payload- required: true- schema:- $ref: '#/definitions/v1.GroupMemberAdd'- produces:- - application/json- responses:- "204":- description: No Content- security:- - Bearer: []- summary: Add User to Group- tags:- - Group/v1/groups/members/{user_id}:delete:parameters:@@ -3666,6 +3735,40 @@ paths:summary: Change Passwordtags:- User+ /v1/users/forgot-password:+ post:+ consumes:+ - application/json+ description: |-+ Sends a password reset email if the address is associated with a local account.+ Always returns 204 on success to avoid leaking whether the email is registered.+ parameters:+ - description: Email+ in: body+ name: payload+ required: true+ schema:+ $ref: '#/definitions/v1.ForgotPasswordRequest'+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "400":+ description: missing or invalid request body, or empty email field+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ schema:+ type: string+ "500":+ description: internal error while processing the request+ schema:+ type: string+ summary: Request Password Reset+ tags:+ - Authentication/v1/users/login:post:consumes:@@ -3765,6 +3868,41 @@ paths:summary: Register New Usertags:- User+ /v1/users/reset-password:+ post:+ consumes:+ - application/json+ description: |-+ Consumes a single-use reset token and changes the user's password.+ On success, all existing sessions for the user are revoked.+ parameters:+ - description: Token + new password+ in: body+ name: payload+ required: true+ schema:+ $ref: '#/definitions/v1.ResetPasswordRequest'+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "400":+ description: invalid request body, password shorter than the minimum length,+ or token that is invalid / expired / already used+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ schema:+ type: string+ "500":+ description: internal error while processing the request+ schema:+ type: string+ summary: Reset Password+ tags:+ - Authentication/v1/users/self:delete:produces:diff --git a/backend/go.mod b/backend/go.modindex 0961c7a8..8249f771 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -24,10 +24,10 @@ require (github.com/olahol/melody v1.4.0github.com/pkg/errors v0.9.1github.com/pressly/goose/v3 v3.27.1- github.com/riandyrn/otelchi v0.12.2+ github.com/riandyrn/otelchi v0.12.3github.com/rs/zerolog v1.35.1github.com/samber/lo v1.53.0- github.com/shirou/gopsutil/v4 v4.26.3+ github.com/shirou/gopsutil/v4 v4.26.4github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686egithub.com/stretchr/testify v1.11.1github.com/swaggo/http-swagger/v2 v2.0.2@@ -58,13 +58,13 @@ require (gocloud.dev/pubsub/kafkapubsub v0.45.0gocloud.dev/pubsub/natspubsub v0.45.0gocloud.dev/pubsub/rabbitpubsub v0.45.0- golang.org/x/crypto v0.50.0- golang.org/x/image v0.39.0+ golang.org/x/crypto v0.51.0+ golang.org/x/image v0.40.0golang.org/x/oauth2 v0.36.0- golang.org/x/text v0.36.0- google.golang.org/grpc v1.80.0+ golang.org/x/text v0.37.0+ google.golang.org/grpc v1.81.0google.golang.org/protobuf v1.36.11- modernc.org/sqlite v1.49.1+ modernc.org/sqlite v1.50.1)require (@@ -92,7 +92,7 @@ require (github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirectgithub.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.54.0 // indirectgithub.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.54.0 // indirect- github.com/IBM/sarama v1.48.0 // indirect+ github.com/IBM/sarama v1.48.1 // indirectgithub.com/KyleBanks/depth v1.2.1 // indirectgithub.com/agext/levenshtein v1.2.3 // indirectgithub.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect@@ -121,14 +121,14 @@ require (github.com/bmatcuk/doublestar v1.3.4 // indirectgithub.com/cenkalti/backoff/v5 v5.0.3 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirect- github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect+ github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirectgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirectgithub.com/dustin/go-humanize v1.0.1 // indirectgithub.com/eapache/go-resiliency v1.7.0 // indirectgithub.com/eapache/queue v1.1.0 // indirectgithub.com/ebitengine/purego v0.10.0 // indirect- github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect- github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect+ github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect+ github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirectgithub.com/fatih/color v1.19.0 // indirectgithub.com/felixge/httpsnoop v1.0.4 // indirectgithub.com/fogleman/gg v1.3.0 // indirect@@ -154,7 +154,7 @@ require (github.com/google/go-cmp v0.7.0 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/google/wire v0.7.0 // indirect- github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect+ github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirectgithub.com/googleapis/gax-go/v2 v2.22.0 // indirectgithub.com/gorilla/websocket v1.5.3 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect@@ -168,17 +168,17 @@ require (github.com/jcmturner/gofork v1.7.6 // indirectgithub.com/jcmturner/gokrb5/v8 v8.4.4 // indirectgithub.com/jcmturner/rpc/v2 v2.0.3 // indirect- github.com/klauspost/compress v1.18.5 // indirect+ github.com/klauspost/compress v1.18.6 // indirectgithub.com/klauspost/cpuid/v2 v2.3.0 // indirectgithub.com/kylelemons/godebug v1.1.0 // indirectgithub.com/leodido/go-urn v1.4.0 // indirectgithub.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirectgithub.com/mattn/go-colorable v0.1.14 // indirect- github.com/mattn/go-isatty v0.0.21 // indirect+ github.com/mattn/go-isatty v0.0.22 // indirectgithub.com/mattn/go-sqlite3 v1.14.34 // indirectgithub.com/mfridman/interpolate v0.0.2 // indirectgithub.com/mitchellh/go-wordwrap v1.0.1 // indirect- github.com/nats-io/nats.go v1.51.0 // indirect+ github.com/nats-io/nats.go v1.52.0 // indirectgithub.com/nats-io/nkeys v0.4.15 // indirectgithub.com/nats-io/nuid v1.0.1 // indirectgithub.com/ncruces/go-strftime v1.0.0 // indirect@@ -203,24 +203,24 @@ require (github.com/zclconf/go-cty v1.14.4 // indirectgithub.com/zclconf/go-cty-yaml v1.1.0 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirect- go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect+ go.opentelemetry.io/contrib/detectors/gcp v1.42.0 // indirectgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirectgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirectgo.uber.org/multierr v1.11.0 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirect- golang.org/x/mod v0.35.0 // indirect- golang.org/x/net v0.53.0 // indirect+ golang.org/x/mod v0.36.0 // indirect+ golang.org/x/net v0.54.0 // indirectgolang.org/x/sync v0.20.0 // indirect- golang.org/x/sys v0.43.0 // indirect+ golang.org/x/sys v0.44.0 // indirectgolang.org/x/time v0.15.0 // indirect- golang.org/x/tools v0.44.0 // indirect+ golang.org/x/tools v0.45.0 // indirectgolang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect- google.golang.org/api v0.276.0 // indirect+ google.golang.org/api v0.278.0 // indirectgoogle.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect- google.golang.org/genproto/googleapis/api v0.0.0-20260420184626-e10c466a9529 // indirect- google.golang.org/genproto/googleapis/rpc v0.0.0-20260420184626-e10c466a9529 // indirect+ google.golang.org/genproto/googleapis/api v0.0.0-20260511170946-3700d4141b60 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260511170946-3700d4141b60 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect- modernc.org/libc v1.72.1 // indirect+ modernc.org/libc v1.72.3 // indirectmodernc.org/mathutil v1.7.1 // indirectmodernc.org/memory v1.11.0 // indirect)diff --git a/backend/go.sum b/backend/go.sumindex bb664ea6..9df91df6 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -73,6 +73,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemappgithub.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.54.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=github.com/IBM/sarama v1.48.0 h1:9LJS0VNeg/boXxT/GLAMDKX6uSQ1mr/5F/j4v9gSeBQ=github.com/IBM/sarama v1.48.0/go.mod h1:UhvwPF8zilmLOSd6O+ENzdycCJYwMww1U9DJOZpoCro=+github.com/IBM/sarama v1.48.1 h1:x1dSWebprjjE7Wr7n8RVAxwa4mt4O9JejRxnZrGIXk0=+github.com/IBM/sarama v1.48.1/go.mod h1:m/Q1aFezH82/AglfTpJbw/fO0ZybYXhPgTmvajiZX50=github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=github.com/XSAM/otelsql v0.42.0 h1:Li0xF4eJUxG2e0x3D4rvRlys1f27yJKvjTh7ljkUP5o=@@ -143,6 +145,8 @@ github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhgithub.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=+github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=+github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=github.com/containrrr/shoutrrr v0.8.0 h1:mfG2ATzIS7NR2Ec6XL+xyoHzN97H8WPjir8aYzJUSec=@@ -166,12 +170,18 @@ github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBgithub.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=+github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=+github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=+github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=+github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=github.com/evanoberholster/imagemeta v0.3.1 h1:E4GUjXcvlVMjP9joN25+bBNf3Al3MTTfMqCrDOCW+LE=github.com/evanoberholster/imagemeta v0.3.1/go.mod h1:V0vtDJmjTqvwAYO8r+u33NRVIMXQb0qSqEfImoKEiXM=+github.com/evanoberholster/imagemeta v1.0.0 h1:FlSihlsjkWIoS83wmgPOP3CbAxlRpxM8jQGZgLu+MWQ=+github.com/evanoberholster/imagemeta v1.0.0/go.mod h1:2ITZJjD1ygzWIhepvn8coRvpaFcnDNk3E6hx6v7z8DU=github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=@@ -275,6 +285,8 @@ github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8=github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=+github.com/googleapis/enterprise-certificate-proxy v0.3.15 h1:xolVQTEXusUcAA5UgtyRLjelpFFHWlPQ4XfWGc7MBas=+github.com/googleapis/enterprise-certificate-proxy v0.3.15/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4=github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY=github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=@@ -322,6 +334,8 @@ github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtgithub.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=+github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=+github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=@@ -338,6 +352,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPgithub.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=+github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=+github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=@@ -354,6 +370,8 @@ github.com/nats-io/nats-server/v2 v2.11.12 h1:jGDXTkcjqQ5fCRstwIxvv1K0RHfftFUoSCgithub.com/nats-io/nats-server/v2 v2.11.12/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=github.com/nats-io/nats.go v1.51.0 h1:ByW84XTz6W03GSSsygsZcA+xgKK8vPGaa/FCAAEHnAI=github.com/nats-io/nats.go v1.51.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=+github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=+github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=@@ -399,6 +417,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/riandyrn/otelchi v0.12.2 h1:6QhGv0LVw/dwjtPd12mnNrl0oEQF4ZAlmHcnlTYbeAg=github.com/riandyrn/otelchi v0.12.2/go.mod h1:weZZeUJURvtCcbWsdb7Y6F8KFZGedJlSrgUjq9VirV8=+github.com/riandyrn/otelchi v0.12.3 h1:KW9gA+97d6mExk8vbh0FRwb2biUvpyYlc8YuxP1Oap0=+github.com/riandyrn/otelchi v0.12.3/go.mod h1:weZZeUJURvtCcbWsdb7Y6F8KFZGedJlSrgUjq9VirV8=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=@@ -411,6 +431,8 @@ github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrahgithub.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=github.com/shirou/gopsutil/v4 v4.26.3 h1:2ESdQt90yU3oXF/CdOlRCJxrP+Am1aBYubTMTfxJ1qc=github.com/shirou/gopsutil/v4 v4.26.3/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=+github.com/shirou/gopsutil/v4 v4.26.4 h1:B4SXVbcwTyrocPHEmWBC4uCYr4Xcu3MK1TXqbprAOWY=+github.com/shirou/gopsutil/v4 v4.26.4/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=@@ -470,6 +492,8 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZgo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=+go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=+go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8=go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY=@@ -532,11 +556,17 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ygolang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=+golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=+golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=+golang.org/x/image v0.40.0 h1:Tw4GyDXMo+daZN1znreBRC3VayR1aLFUyUEOLUdW1a8=+golang.org/x/image v0.40.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=+golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=+golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=@@ -546,6 +576,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=+golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=+golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=@@ -564,6 +596,8 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=+golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=@@ -573,6 +607,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=+golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=+golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=@@ -580,6 +616,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=+golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=+golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=@@ -588,14 +626,22 @@ gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=google.golang.org/api v0.276.0 h1:nVArUtfLEihtW+b0DdcqRGK1xoEm2+ltAihyztq7MKY=google.golang.org/api v0.276.0/go.mod h1:Fnag/EWUPIcJXuIkP1pjoTgS5vdxlk3eeemL7Do6bvw=+google.golang.org/api v0.278.0 h1:W7jiRvRi53VYFfZ/HoZjQBtJk7gOFbHD8ot1RzVZU6E=+google.golang.org/api v0.278.0/go.mod h1:B9TqLBwJqVjp1mtt7WeoQwWRwvu/400y5lETOql+giQ=google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=google.golang.org/genproto/googleapis/api v0.0.0-20260420184626-e10c466a9529 h1:zUWMZsvo/IJcD1t6MNCPO/azZTwz0TvwCBqr5aifoVY=google.golang.org/genproto/googleapis/api v0.0.0-20260420184626-e10c466a9529/go.mod h1:a5OGAgyRr4lqco7AG9hQM9Fwh0N2ZV4grR0eXFEsXQg=+google.golang.org/genproto/googleapis/api v0.0.0-20260511170946-3700d4141b60 h1:3WsB1FAbiRIf2tOxscWKs3pQBD9he1NsrnbhMuWfekc=+google.golang.org/genproto/googleapis/api v0.0.0-20260511170946-3700d4141b60/go.mod h1:7yoXV7RIh5gblj/xVYoogxAWvA9wUeVbpsK/M694l00=google.golang.org/genproto/googleapis/rpc v0.0.0-20260420184626-e10c466a9529 h1:XF8+t6QQiS0o9ArVan/HW8Q7cycNPGsJf6GA2nXxYAg=google.golang.org/genproto/googleapis/rpc v0.0.0-20260420184626-e10c466a9529/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260511170946-3700d4141b60 h1:seT2EwLWM78plQ7wcDfuWBc/4FAEAXDDiaSol4ku4qo=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260511170946-3700d4141b60/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=+google.golang.org/grpc v1.81.0 h1:W3G9N3KQf3BU+YuCtGKJk0CmxQNbAISICD/9AORxLIw=+google.golang.org/grpc v1.81.0/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=@@ -607,8 +653,10 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=modernc.org/cc/v4 v4.28.1 h1:XpLbkYVQ24E8tX5u8+yWGvaxerxkR/S4zqxI8ZoSBuc=modernc.org/cc/v4 v4.28.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=+modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=modernc.org/ccgo/v4 v4.33.0 h1:dspBCm75jsj8Y/ufwAMVfe375L2iYdMyQ2QG/v3hL54=modernc.org/ccgo/v4 v4.33.0/go.mod h1:+RhXBoRYzRwaH21mV/aj6XvQRDtfjcZfAlPMsQo8CR0=+modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=@@ -619,6 +667,8 @@ modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=modernc.org/libc v1.72.1 h1:db1xwJ6u1kE3KHTFTTbe2GCrczHPKzlURP0aDC4NGD0=modernc.org/libc v1.72.1/go.mod h1:HRMiC/PhPGLIPM7GzAFCbI+oSgE3dhZ8FWftmRrHVlY=+modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=+modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=@@ -629,6 +679,8 @@ modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=modernc.org/sqlite v1.49.1 h1:dYGHTKcX1sJ+EQDnUzvz4TJ5GbuvhNJa8Fg6ElGx73U=modernc.org/sqlite v1.49.1/go.mod h1:m0w8xhwYUVY3H6pSDwc3gkJ/irZT/0YEXwBlhaxQEew=+modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=+modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=diff --git a/backend/internal/core/services/all.go b/backend/internal/core/services/all.goindex fbedb1d2..682cb8a3 100644--- a/backend/internal/core/services/all.go+++ b/backend/internal/core/services/all.go@@ -5,6 +5,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/core/currencies""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/sys/config"+ "github.com/sysadminsmedia/homebox/backend/pkgs/mailer")type AllServices struct {@@ -21,6 +22,7 @@ type options struct {autoIncrementAssetID boolcurrencies []currencies.CurrencynotifierConfig *config.NotifierConf+ mailer *mailer.Mailer}func WithAutoIncrementAssetID(v bool) func(*options) {@@ -43,6 +45,15 @@ func WithNotifierConfig(v *config.NotifierConf) func(*options) {}}+// WithMailer hands the SMTP mailer to services that send mail (currently only+// password reset). A nil or unconfigured mailer disables those code paths+// rather than panicking.+func WithMailer(m *mailer.Mailer) func(*options) {+ return func(o *options) {+ o.mailer = m+ }+}+// defaultNotifierConf returns a NotifierConf with safe defaults matching the conf tags.// This ensures SSRF protections are enabled when WithNotifierConfig is not provided.func defaultNotifierConf() *config.NotifierConf {@@ -75,7 +86,7 @@ func New(repos *repo.AllRepos, opts ...OptionsFunc) *AllServices {}return &AllServices{- User: &UserService{repos},+ User: &UserService{repos: repos, mailer: options.mailer},Group: &GroupService{repos},Entities: &EntityService{repo: repos,diff --git a/backend/internal/core/services/reporting/import.go b/backend/internal/core/services/reporting/import.goindex d1a41f9b..5948f60d 100644--- a/backend/internal/core/services/reporting/import.go+++ b/backend/internal/core/services/reporting/import.go@@ -10,9 +10,16 @@ import ("github.com/samber/lo")+// Required column headers in CSV/TSV imports. Exported so tests and other+// packages share the same canonical strings.+const (+ HeaderHBLocation = "HB.location"+ HeaderHBName = "HB.name"+)+var (ErrNoHomeboxHeaders = errors.New("no headers found")- ErrMissingRequiredHeaders = errors.New("missing required headers `HB.location` or `HB.name`")+ ErrMissingRequiredHeaders = errors.New("missing required headers `" + HeaderHBLocation + "` or `" + HeaderHBName + "`"))// determineSeparator determines the separator used in the CSV file@@ -89,7 +96,7 @@ func parseHeaders(headers []string) (hbHeaders map[string]int, fieldHeaders []st}}- required := []string{"HB.location", "HB.name"}+ required := []string{HeaderHBLocation, HeaderHBName}if !lo.EveryBy(required, func(h string) bool {return lo.HasKey(hbHeaders, h)}) {diff --git a/backend/internal/core/services/reporting/io_sheet_test.go b/backend/internal/core/services/reporting/io_sheet_test.goindex cd614a84..48a7c78c 100644--- a/backend/internal/core/services/reporting/io_sheet_test.go+++ b/backend/internal/core/services/reporting/io_sheet_test.go@@ -12,6 +12,12 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/repo")+// Repeated fixture column headers used across header-parse test cases.+const (+ headerHBField2 = "HB.field.2"+ headerHBField3 = "HB.field.3"+)+var (//go:embed .testdata/import/minimal.csvminimalImportCSV []byte@@ -130,27 +136,27 @@ func Test_parseHeaders(t *testing.T) {},{name: "field headers only",- rawHeaders: []string{"HB.location", "HB.name", "HB.field.1", "HB.field.2", "HB.field.3"},+ rawHeaders: []string{"HB.location", "HB.name", "HB.field.1", headerHBField2, headerHBField3},wantHbHeaders: map[string]int{- "HB.location": 0,- "HB.name": 1,- "HB.field.1": 2,- "HB.field.2": 3,- "HB.field.3": 4,+ "HB.location": 0,+ "HB.name": 1,+ "HB.field.1": 2,+ headerHBField2: 3,+ headerHBField3: 4,},- wantFieldHeaders: []string{"HB.field.1", "HB.field.2", "HB.field.3"},+ wantFieldHeaders: []string{"HB.field.1", headerHBField2, headerHBField3},wantErr: false,},{name: "mixed headers",- rawHeaders: []string{"Header 1", "HB.name", "Header 2", "HB.field.2", "Header 3", "HB.field.3", "HB.location"},+ rawHeaders: []string{"Header 1", "HB.name", "Header 2", headerHBField2, "Header 3", headerHBField3, "HB.location"},wantHbHeaders: map[string]int{- "HB.name": 1,- "HB.field.2": 3,- "HB.field.3": 5,- "HB.location": 6,+ "HB.name": 1,+ headerHBField2: 3,+ headerHBField3: 5,+ "HB.location": 6,},- wantFieldHeaders: []string{"HB.field.2", "HB.field.3"},+ wantFieldHeaders: []string{headerHBField2, headerHBField3},wantErr: false,},}diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.goindex 51502d0b..53042ff3 100644--- a/backend/internal/core/services/service_user.go+++ b/backend/internal/core/services/service_user.go@@ -13,18 +13,23 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+ "github.com/sysadminsmedia/homebox/backend/pkgs/mailer""go.opentelemetry.io/otel/attribute""go.opentelemetry.io/otel/trace")var (- oneWeek = time.Hour * 24 * 7- ErrorInvalidLogin = errors.New("invalid username or password")- ErrorInvalidToken = errors.New("invalid token")+ oneWeek = time.Hour * 24 * 7+ passwordResetTokenTTL = time.Hour+ ErrorInvalidLogin = errors.New("invalid username or password")+ ErrorInvalidToken = errors.New("invalid token")+ ErrorMailerNotConfigured = errors.New("password reset by email is unavailable: SMTP is not configured")+ ErrorPasswordResetInvalid = errors.New("password reset link is invalid or has expired"))type UserService struct {- repos *repo.AllRepos+ repos *repo.AllRepos+ mailer *mailer.Mailer}type (diff --git a/backend/internal/core/services/service_user_password_reset.go b/backend/internal/core/services/service_user_password_reset.gonew file mode 100644index 00000000..79bd54d0--- /dev/null+++ b/backend/internal/core/services/service_user_password_reset.go@@ -0,0 +1,288 @@+package services++import (+ "context"+ "errors"+ "fmt"+ "net/url"+ "strings"+ "time"++ "github.com/rs/zerolog/log"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+ "github.com/sysadminsmedia/homebox/backend/pkgs/mailer"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/trace"+)++// MailerReady reports whether the SMTP mailer is configured and usable. The+// HTTP forgot-password handler uses this to short-circuit with a clear error+// when SMTP is missing, so the user sees something actionable instead of a+// generic success message followed by no email arriving.+func (svc *UserService) MailerReady() bool {+ return svc.mailer != nil && svc.mailer.Ready()+}++// RequestPasswordReset issues a single-use reset token and emails the link.+// All work — user lookup, token creation, SMTP send — runs in a background+// goroutine so the HTTP response time does not depend on whether the email+// is registered. Without this, the SMTP call (tens of ms) would defeat the+// "always 204" enumeration defense by letting an attacker time-distinguish+// known accounts from unknown ones. Only the up-front "is the mailer+// configured" check runs synchronously.+//+// baseURL is the absolute URL prefix (scheme + host) the reset link is built+// against. The handler MUST resolve it via SecureBaseURL — never via+// GetHBURL — so a forged Referer or untrusted X-Forwarded-Host can't poison+// the link in the victim's email.+func (svc *UserService) RequestPasswordReset(ctx context.Context, email, baseURL string) error {+ _, span := entityServiceTracer().Start(ctx, "service.UserService.RequestPasswordReset",+ trace.WithAttributes(+ attribute.Int("user.email.length", len(email)),+ attribute.Int("base_url.length", len(baseURL)),+ ))+ defer span.End()++ if !svc.MailerReady() {+ span.SetAttributes(attribute.String("reset.outcome", "mailer_not_configured"))+ return ErrorMailerNotConfigured+ }++ // Detach from the request context so a client disconnect or timeout+ // doesn't abort the email send halfway through. Errors are logged, never+ // propagated — surfacing them would re-introduce the enumeration leak.+ go svc.processResetRequest(email, baseURL)++ span.SetAttributes(attribute.String("reset.outcome", "queued"))+ return nil+}++func (svc *UserService) processResetRequest(email, baseURL string) {+ ctx, span := entityServiceTracer().Start(context.Background(), "service.UserService.processResetRequest",+ trace.WithAttributes(attribute.Int("user.email.length", len(email))))+ defer span.End()++ rawToken, usr, err := svc.createResetToken(ctx, email)+ if err != nil {+ switch {+ case ent.IsNotFound(err):+ span.SetAttributes(attribute.String("reset.outcome", "user_not_found"))+ case errors.Is(err, errResetUserHasNoPassword):+ span.SetAttributes(attribute.String("reset.outcome", "user_no_password"))+ default:+ recordServiceSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "create_failed"))+ log.Err(err).Msg("failed to create password reset token")+ }+ return+ }+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))++ link := buildResetLink(baseURL, rawToken)+ if err := svc.sendResetEmail(usr, link); err != nil {+ recordServiceSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "email_send_failed"))+ log.Err(err).Str("user.id", usr.ID.String()).Msg("failed to send password reset email")+ return+ }+ span.SetAttributes(attribute.String("reset.outcome", "sent"))+}++// GenerateResetLink mints a token and returns the reset URL without sending+// email. The CLI subcommand calls this so an admin can recover an account when+// SMTP is not configured (e.g. a small self-hosted instance, or to debug the+// password matching path itself). Unlike the HTTP path, this returns+// ent.NotFound for an unknown email — the caller is the operator, who needs+// to know if they typed the address wrong.+func (svc *UserService) GenerateResetLink(ctx context.Context, email, baseURL string) (string, error) {+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.GenerateResetLink",+ trace.WithAttributes(+ attribute.Int("user.email.length", len(email)),+ attribute.Int("base_url.length", len(baseURL)),+ ))+ defer span.End()++ rawToken, usr, err := svc.createResetToken(ctx, email)+ if err != nil {+ if !ent.IsNotFound(err) && !errors.Is(err, errResetUserHasNoPassword) {+ recordServiceSpanError(span, err)+ }+ return "", err+ }+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))++ return buildResetLink(baseURL, rawToken), nil+}++// ResetPassword consumes a reset token and changes the password. On success it+// also revokes every active session token for the user — the password change+// must invalidate any session an attacker (or anyone on a shared device) might+// be holding. Returns ErrorPasswordResetInvalid for any invalid/expired/used+// token, deliberately conflating the three cases.+func (svc *UserService) ResetPassword(ctx context.Context, rawToken, newPassword string) error {+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.ResetPassword",+ trace.WithAttributes(+ attribute.Int("token.length", len(rawToken)),+ attribute.Int("password.new.length", len(newPassword)),+ ))+ defer span.End()++ if rawToken == "" || newPassword == "" {+ span.SetAttributes(attribute.String("reset.outcome", "missing_input"))+ return ErrorPasswordResetInvalid+ }++ hash := hasher.HashToken(rawToken)+ tok, err := svc.repos.PasswordResetTokens.GetValidByHash(ctx, hash)+ if err != nil {+ if ent.IsNotFound(err) {+ // SECURITY: equalize response time with the valid-token path.+ // The valid-token path runs argon2id (~50ms) + DB writes; without+ // a dummy hash here, an attacker could distinguish valid from+ // invalid tokens by response time. argon2id dominates the cost+ // of the success path, so equalizing it brings the residual gap+ // well below typical network jitter and below practical+ // distinguishability. The dummy hash result is discarded.+ _, _ = hasher.HashPasswordCtx(ctx, newPassword)+ span.SetAttributes(attribute.String("reset.outcome", "token_invalid"))+ return ErrorPasswordResetInvalid+ }+ recordServiceSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "lookup_failed"))+ return err+ }+ span.SetAttributes(+ attribute.String("user.id", tok.UserID.String()),+ attribute.String("token.id", tok.ID.String()),+ )++ hashed, err := hasher.HashPasswordCtx(ctx, newPassword)+ if err != nil {+ recordServiceSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "hash_failed"))+ return err+ }++ // ConsumeAndChangePassword runs the atomic conditional claim of the token+ // (used_at IS NULL → now) and the password update in a single ent+ // transaction, so a transient DB failure can never leave us in the bad+ // state where the token is burned but the password is unchanged. The+ // conditional UPDATE still defends against the concurrent-reset race —+ // a racer sees 0 rows affected and gets ErrPasswordResetTokenAlreadyClaimed.+ // Session revocation runs only after the commit succeeds.+ if err := svc.repos.PasswordResetTokens.ConsumeAndChangePassword(ctx, tok.ID, tok.UserID, hashed); err != nil {+ if errors.Is(err, repo.ErrPasswordResetTokenAlreadyClaimed) {+ span.SetAttributes(attribute.String("reset.outcome", "claim_race_lost"))+ return ErrorPasswordResetInvalid+ }+ recordServiceSpanError(span, err)+ span.SetAttributes(attribute.String("reset.outcome", "persist_failed"))+ return err+ }++ revoked, err := svc.repos.AuthTokens.DeleteAllByUser(ctx, tok.UserID)+ if err != nil {+ // The password is already changed and the token consumed; logging the+ // session-revocation failure is more useful than failing the whole+ // reset and leaving the user unable to log in with their new password.+ log.Err(err).Str("user.id", tok.UserID.String()).Msg("failed to revoke sessions after password reset")+ span.SetAttributes(attribute.String("reset.outcome", "success_revoke_failed"))+ return nil+ }++ span.SetAttributes(+ attribute.String("reset.outcome", "success"),+ attribute.Int("sessions.revoked.count", revoked),+ )+ return nil+}++// errResetUserHasNoPassword is an internal sentinel for the OIDC-only-user+// case. Callers translate it to either a silent success (HTTP) or a real+// error (CLI).+var errResetUserHasNoPassword = errors.New("user has no password set")++func (svc *UserService) createResetToken(ctx context.Context, email string) (string, repo.UserOut, error) {+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.createResetToken",+ trace.WithAttributes(attribute.Int("user.email.length", len(email))))+ defer span.End()++ usr, err := svc.repos.Users.GetOneEmail(ctx, email)+ if err != nil {+ span.SetAttributes(attribute.Bool("user.found", false))+ return "", repo.UserOut{}, err+ }+ span.SetAttributes(+ attribute.Bool("user.found", true),+ attribute.String("user.id", usr.ID.String()),+ attribute.Bool("user.has_password_hash", usr.PasswordHash != ""),+ )++ if usr.PasswordHash == "" {+ // OIDC-only user — there's no local password to reset. Don't issue a+ // token; the caller decides whether to surface this.+ return "", usr, errResetUserHasNoPassword+ }++ tok := hasher.GenerateTokenCtx(ctx)+ expiresAt := time.Now().Add(passwordResetTokenTTL)++ if _, err := svc.repos.PasswordResetTokens.Create(ctx, usr.ID, tok.Hash, expiresAt); err != nil {+ recordServiceSpanError(span, err)+ return "", usr, err+ }+ return tok.Raw, usr, nil+}++func (svc *UserService) sendResetEmail(usr repo.UserOut, link string) error {+ subject := "Reset your Homebox password"+ body := buildResetEmailBody(usr.Name, link)++ msg := mailer.NewMessageBuilder().+ SetTo(usr.Name, usr.Email).+ SetFrom("Homebox", svc.mailer.From).+ SetSubject(subject).+ SetBody(body).+ Build()++ return svc.mailer.Send(msg)+}++func buildResetLink(baseURL, rawToken string) string {+ base := strings.TrimSuffix(baseURL, "/")+ return fmt.Sprintf("%s/reset-password?token=%s", base, url.QueryEscape(rawToken))+}++func buildResetEmailBody(name, link string) string {+ if name == "" {+ name = "there"+ }+ // Plain HTML; the mailer sends as text/html. The link is also rendered as+ // plain text below in case the user's client mangles the anchor.+ return fmt.Sprintf(`<!doctype html>+<html><body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; line-height: 1.5; color: #1f2937;">+<p>Hi %s,</p>+<p>Someone (hopefully you) requested a password reset for your Homebox account. Click the link below to choose a new password. The link will expire in one hour and can only be used once.</p>+<p><a href="%s" style="display: inline-block; padding: 10px 18px; background: #0ea5e9; color: white; text-decoration: none; border-radius: 6px;">Reset password</a></p>+<p>If the button doesn't work, paste this URL into your browser:</p>+<p style="word-break: break-all;"><code>%s</code></p>+<p>If you didn't request this, you can ignore this email — your password won't change.</p>+<p>— Homebox</p>+</body></html>`, htmlEscape(name), htmlEscape(link), htmlEscape(link))+}++// htmlEscape is a minimal escaper for the few values we interpolate into the+// reset email. We don't pull in html/template here because the body is a fixed+// fragment with two substitutions.+func htmlEscape(s string) string {+ r := strings.NewReplacer(+ "&", "&",+ "<", "<",+ ">", ">",+ `"`, """,+ "'", "'",+ )+ return r.Replace(s)+}diff --git a/backend/internal/core/services/service_user_password_reset_test.go b/backend/internal/core/services/service_user_password_reset_test.gonew file mode 100644index 00000000..2cb4bbc0--- /dev/null+++ b/backend/internal/core/services/service_user_password_reset_test.go@@ -0,0 +1,267 @@+package services++import (+ "context"+ "net/url"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+)++// newTestUserWithPassword creates a fresh user with a known password so each+// test gets its own subject and doesn't fight with the shared tUser.+func newTestUserWithPassword(t *testing.T, password string) repo.UserOut {+ t.Helper()+ hash, err := hasher.HashPassword(password)+ require.NoError(t, err)+ usr, err := tRepos.Users.Create(context.Background(), repo.UserCreate{+ Name: fk.Str(10),+ Email: fk.Email(),+ Password: &hash,+ DefaultGroupID: tGroup.ID,+ })+ require.NoError(t, err)+ return usr+}++func extractToken(t *testing.T, link string) string {+ t.Helper()+ u, err := url.Parse(link)+ require.NoError(t, err, "reset link should be a valid URL")+ tok := u.Query().Get("token")+ require.NotEmpty(t, tok, "reset link should include a token query param")+ return tok+}++func TestRequestPasswordReset_NoMailer_ReturnsError(t *testing.T) {+ // tSvc.User.mailer is nil by default in tests; that's the path we want.+ err := tSvc.User.RequestPasswordReset(context.Background(), "[email protected]", "https://example.com")+ assert.ErrorIs(t, err, ErrorMailerNotConfigured)+}++func TestGenerateResetLink_HappyPath(t *testing.T) {+ usr := newTestUserWithPassword(t, "original-password")++ link, err := tSvc.User.GenerateResetLink(context.Background(), usr.Email, "https://example.com")+ require.NoError(t, err)+ assert.Contains(t, link, "https://example.com/reset-password?token=")++ // The token should be persisted (hashed) and unused.+ rawToken := extractToken(t, link)+ hash := hasher.HashToken(rawToken)+ got, err := tRepos.PasswordResetTokens.GetValidByHash(context.Background(), hash)+ require.NoError(t, err)+ assert.Equal(t, usr.ID, got.UserID)+}++func TestGenerateResetLink_UnknownEmail_ReturnsNotFound(t *testing.T) {+ _, err := tSvc.User.GenerateResetLink(context.Background(), "ghost-"+fk.Email(), "https://example.com")+ require.Error(t, err)+ assert.True(t, ent.IsNotFound(err), "expected NotFound, got %v", err)+}++func TestGenerateResetLink_OIDCUser_ReturnsSentinel(t *testing.T) {+ // User with no local password (OIDC-only style).+ usr, err := tRepos.Users.Create(context.Background(), repo.UserCreate{+ Name: fk.Str(10),+ Email: fk.Email(),+ Password: nil,+ DefaultGroupID: tGroup.ID,+ })+ require.NoError(t, err)++ _, err = tSvc.User.GenerateResetLink(context.Background(), usr.Email, "https://example.com")+ require.Error(t, err)+ assert.ErrorIs(t, err, errResetUserHasNoPassword)+}++func TestResetPassword_HappyPath_RevokesSessions(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "old-password")++ // Give the user two active sessions; both must be killed by the reset.+ _, err := tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)+ _, err = tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)++ link, err := tSvc.User.GenerateResetLink(ctx, usr.Email, "https://example.com")+ require.NoError(t, err)+ rawToken := extractToken(t, link)++ require.NoError(t, tSvc.User.ResetPassword(ctx, rawToken, "brand-new-password"))++ // Old sessions are gone — DeleteAllByUser should have wiped them.+ gone, err := tClient.AuthTokens.Query().+ Where(authtokens.HasUserWith(user.ID(usr.ID))).+ Count(ctx)+ require.NoError(t, err)+ assert.Equal(t, 0, gone, "all sessions for the user should be revoked")++ // Login with the new password works.+ _, err = tSvc.User.Login(ctx, usr.Email, "brand-new-password", false)+ require.NoError(t, err)++ // Login with the old password fails.+ _, err = tSvc.User.Login(ctx, usr.Email, "old-password", false)+ require.ErrorIs(t, err, ErrorInvalidLogin)++ // Token is marked used (not retrievable as valid).+ _, err = tRepos.PasswordResetTokens.GetValidByHash(ctx, hasher.HashToken(rawToken))+ assert.True(t, ent.IsNotFound(err), "used token must not be retrievable as valid")+}++func TestResetPassword_TokenReplay_Rejected(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "first-password")++ link, err := tSvc.User.GenerateResetLink(ctx, usr.Email, "https://example.com")+ require.NoError(t, err)+ rawToken := extractToken(t, link)++ require.NoError(t, tSvc.User.ResetPassword(ctx, rawToken, "second-password"))++ // Replay — the same token must not work twice.+ err = tSvc.User.ResetPassword(ctx, rawToken, "third-password")+ assert.ErrorIs(t, err, ErrorPasswordResetInvalid)+}++func TestResetPassword_AtomicClaim_LosesRaceToConcurrentReset(t *testing.T) {+ // Simulate the race: two requests both get the token via GetValidByHash+ // before either marks it used. The atomic conditional update inside+ // MarkUsed must let only one win. We model this by manually marking the+ // token used between GetValidByHash and the second ResetPassword call —+ // the second caller's MarkUsed should fail with the claim-race error,+ // which ResetPassword translates to ErrorPasswordResetInvalid.+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "starting-pw")++ link, err := tSvc.User.GenerateResetLink(ctx, usr.Email, "https://example.com")+ require.NoError(t, err)+ rawToken := extractToken(t, link)++ // Mark the token used out-of-band, mimicking a concurrent winner. After+ // this, ResetPassword's GetValidByHash will return NotFound (since+ // GetValidByHash filters used tokens), giving ErrorPasswordResetInvalid.+ tok, err := tRepos.PasswordResetTokens.GetValidByHash(ctx, hasher.HashToken(rawToken))+ require.NoError(t, err)+ require.NoError(t, tRepos.PasswordResetTokens.MarkUsed(ctx, tok.ID, time.Now()))++ err = tSvc.User.ResetPassword(ctx, rawToken, "race-loser-pw")+ require.ErrorIs(t, err, ErrorPasswordResetInvalid)++ // Confirm the password was NOT changed by the losing caller.+ _, err = tSvc.User.Login(ctx, usr.Email, "starting-pw", false)+ assert.NoError(t, err, "original password must still work — losing race must not have changed it")+}++func TestResetPassword_BogusToken_Rejected(t *testing.T) {+ err := tSvc.User.ResetPassword(context.Background(), "this-is-not-a-real-token", "newpw")+ assert.ErrorIs(t, err, ErrorPasswordResetInvalid)+}++// TestResetPassword_InvalidToken_RunsDummyHash exists to catch regressions of+// the timing-equalization fix. We don't assert absolute timings (CI is too+// noisy) — instead we assert that the invalid-token path takes at LEAST a+// reasonable fraction of the valid-token path. argon2id with the configured+// params (m=64MiB, t=3, p=2) takes tens of ms on any modern host; the+// invalid-token path without the dummy hash returns in microseconds, so a+// loose floor reliably distinguishes "dummy hash ran" from "didn't".+func TestResetPassword_InvalidToken_RunsDummyHash(t *testing.T) {+ ctx := context.Background()++ // Warm up: argon2id allocates ~64 MiB; the first call in a process can be+ // markedly slower than steady-state. Run once so the measurement below+ // reflects steady-state cost.+ _, _ = hasher.HashPasswordCtx(ctx, "warmup-pw")++ const password = "any-password-of-reasonable-length"++ measure := func(token string) time.Duration {+ start := time.Now()+ _ = tSvc.User.ResetPassword(ctx, token, password)+ return time.Since(start)+ }++ // Establish a per-host baseline by measuring a real argon2id directly.+ // This avoids hard-coding a millisecond floor that could be flaky on+ // slow CI runners or fast workstations.+ hashStart := time.Now()+ _, err := hasher.HashPasswordCtx(ctx, password)+ require.NoError(t, err)+ hashCost := time.Since(hashStart)++ invalidElapsed := measure("definitely-not-a-real-token-value-here")++ // The invalid-token path must take at least ~half the cost of a single+ // argon2id call. If the dummy hash were skipped, this would return in+ // well under a millisecond and the assertion would fail loudly.+ floor := hashCost / 2+ assert.GreaterOrEqual(t, invalidElapsed, floor,+ "invalid-token path returned in %s but a single argon2id costs %s — dummy hash likely was not run, exposing a timing oracle for valid vs invalid tokens",+ invalidElapsed, hashCost)+}++func TestResetPassword_EmptyInputs_Rejected(t *testing.T) {+ err := tSvc.User.ResetPassword(context.Background(), "", "newpw")+ require.ErrorIs(t, err, ErrorPasswordResetInvalid)++ err = tSvc.User.ResetPassword(context.Background(), "sometoken", "")+ assert.ErrorIs(t, err, ErrorPasswordResetInvalid)+}++func TestResetPassword_ExpiredToken_Rejected(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "starting-password")++ // Mint a token directly in the repo with an expiration in the past, so we+ // don't have to time-travel the clock or rebuild the service.+ tok := hasher.GenerateTokenCtx(ctx)+ _, err := tRepos.PasswordResetTokens.Create(ctx, usr.ID, tok.Hash, time.Now().Add(-1*time.Minute))+ require.NoError(t, err)++ err = tSvc.User.ResetPassword(ctx, tok.Raw, "wont-work")+ assert.ErrorIs(t, err, ErrorPasswordResetInvalid)+}++func TestPurgeExpired_RemovesExpiredAndUsedTokens(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "irrelevant")++ // Expired token.+ expiredTok := hasher.GenerateTokenCtx(ctx)+ expiredRow, err := tRepos.PasswordResetTokens.Create(ctx, usr.ID, expiredTok.Hash, time.Now().Add(-1*time.Hour))+ require.NoError(t, err)++ // Used token (still within its TTL).+ usedTok := hasher.GenerateTokenCtx(ctx)+ usedRow, err := tRepos.PasswordResetTokens.Create(ctx, usr.ID, usedTok.Hash, time.Now().Add(time.Hour))+ require.NoError(t, err)+ require.NoError(t, tRepos.PasswordResetTokens.MarkUsed(ctx, usedRow.ID, time.Now()))++ // Fresh token that should survive the purge.+ freshTok := hasher.GenerateTokenCtx(ctx)+ freshRow, err := tRepos.PasswordResetTokens.Create(ctx, usr.ID, freshTok.Hash, time.Now().Add(time.Hour))+ require.NoError(t, err)++ deleted, err := tRepos.PasswordResetTokens.PurgeExpired(ctx)+ require.NoError(t, err)+ assert.GreaterOrEqual(t, deleted, 2, "expired + used token rows should be deleted")++ exists := func(id uuid.UUID) bool {+ _, err := tClient.PasswordResetTokens.Query().Where(passwordresettokens.ID(id)).Only(ctx)+ return err == nil+ }+ assert.False(t, exists(expiredRow.ID), "expired token should be gone")+ assert.False(t, exists(usedRow.ID), "used token should be gone")+ assert.True(t, exists(freshRow.ID), "fresh token should survive")+}diff --git a/backend/internal/data/ent/client.go b/backend/internal/data/ent/client.goindex f3970b48..d0352d22 100644--- a/backend/internal/data/ent/client.go+++ b/backend/internal/data/ent/client.go@@ -28,6 +28,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/groupinvitationtoken""github.com/sysadminsmedia/homebox/backend/internal/data/ent/maintenanceentry""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag""github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield""github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"@@ -63,6 +64,8 @@ type Client struct {MaintenanceEntry *MaintenanceEntryClient// Notifier is the client for interacting with the Notifier builders.Notifier *NotifierClient+ // PasswordResetTokens is the client for interacting with the PasswordResetTokens builders.+ PasswordResetTokens *PasswordResetTokensClient// Tag is the client for interacting with the Tag builders.Tag *TagClient// TemplateField is the client for interacting with the TemplateField builders.@@ -94,6 +97,7 @@ func (c *Client) init() {c.GroupInvitationToken = NewGroupInvitationTokenClient(c.config)c.MaintenanceEntry = NewMaintenanceEntryClient(c.config)c.Notifier = NewNotifierClient(c.config)+ c.PasswordResetTokens = NewPasswordResetTokensClient(c.config)c.Tag = NewTagClient(c.config)c.TemplateField = NewTemplateFieldClient(c.config)c.User = NewUserClient(c.config)@@ -202,6 +206,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {GroupInvitationToken: NewGroupInvitationTokenClient(cfg),MaintenanceEntry: NewMaintenanceEntryClient(cfg),Notifier: NewNotifierClient(cfg),+ PasswordResetTokens: NewPasswordResetTokensClient(cfg),Tag: NewTagClient(cfg),TemplateField: NewTemplateFieldClient(cfg),User: NewUserClient(cfg),@@ -237,6 +242,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)GroupInvitationToken: NewGroupInvitationTokenClient(cfg),MaintenanceEntry: NewMaintenanceEntryClient(cfg),Notifier: NewNotifierClient(cfg),+ PasswordResetTokens: NewPasswordResetTokensClient(cfg),Tag: NewTagClient(cfg),TemplateField: NewTemplateFieldClient(cfg),User: NewUserClient(cfg),@@ -272,7 +278,8 @@ func (c *Client) Use(hooks ...Hook) {for _, n := range []interface{ Use(...Hook) }{c.APIKey, c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,c.EntityTemplate, c.EntityType, c.Group, c.GroupInvitationToken,- c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User, c.UserGroup,+ c.MaintenanceEntry, c.Notifier, c.PasswordResetTokens, c.Tag, c.TemplateField,+ c.User, c.UserGroup,} {n.Use(hooks...)}@@ -284,7 +291,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) {for _, n := range []interface{ Intercept(...Interceptor) }{c.APIKey, c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,c.EntityTemplate, c.EntityType, c.Group, c.GroupInvitationToken,- c.MaintenanceEntry, c.Notifier, c.Tag, c.TemplateField, c.User, c.UserGroup,+ c.MaintenanceEntry, c.Notifier, c.PasswordResetTokens, c.Tag, c.TemplateField,+ c.User, c.UserGroup,} {n.Intercept(interceptors...)}@@ -317,6 +325,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {return c.MaintenanceEntry.mutate(ctx, m)case *NotifierMutation:return c.Notifier.mutate(ctx, m)+ case *PasswordResetTokensMutation:+ return c.PasswordResetTokens.mutate(ctx, m)case *TagMutation:return c.Tag.mutate(ctx, m)case *TemplateFieldMutation:@@ -2454,6 +2464,155 @@ func (c *NotifierClient) mutate(ctx context.Context, m *NotifierMutation) (Value}}+// PasswordResetTokensClient is a client for the PasswordResetTokens schema.+type PasswordResetTokensClient struct {+ config+}++// NewPasswordResetTokensClient returns a client for the PasswordResetTokens from the given config.+func NewPasswordResetTokensClient(c config) *PasswordResetTokensClient {+ return &PasswordResetTokensClient{config: c}+}++// Use adds a list of mutation hooks to the hooks stack.+// A call to `Use(f, g, h)` equals to `passwordresettokens.Hooks(f(g(h())))`.+func (c *PasswordResetTokensClient) Use(hooks ...Hook) {+ c.hooks.PasswordResetTokens = append(c.hooks.PasswordResetTokens, hooks...)+}++// Intercept adds a list of query interceptors to the interceptors stack.+// A call to `Intercept(f, g, h)` equals to `passwordresettokens.Intercept(f(g(h())))`.+func (c *PasswordResetTokensClient) Intercept(interceptors ...Interceptor) {+ c.inters.PasswordResetTokens = append(c.inters.PasswordResetTokens, interceptors...)+}++// Create returns a builder for creating a PasswordResetTokens entity.+func (c *PasswordResetTokensClient) Create() *PasswordResetTokensCreate {+ mutation := newPasswordResetTokensMutation(c.config, OpCreate)+ return &PasswordResetTokensCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}+}++// CreateBulk returns a builder for creating a bulk of PasswordResetTokens entities.+func (c *PasswordResetTokensClient) CreateBulk(builders ...*PasswordResetTokensCreate) *PasswordResetTokensCreateBulk {+ return &PasswordResetTokensCreateBulk{config: c.config, builders: builders}+}++// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates+// a builder and applies setFunc on it.+func (c *PasswordResetTokensClient) MapCreateBulk(slice any, setFunc func(*PasswordResetTokensCreate, int)) *PasswordResetTokensCreateBulk {+ rv := reflect.ValueOf(slice)+ if rv.Kind() != reflect.Slice {+ return &PasswordResetTokensCreateBulk{err: fmt.Errorf("calling to PasswordResetTokensClient.MapCreateBulk with wrong type %T, need slice", slice)}+ }+ builders := make([]*PasswordResetTokensCreate, rv.Len())+ for i := 0; i < rv.Len(); i++ {+ builders[i] = c.Create()+ setFunc(builders[i], i)+ }+ return &PasswordResetTokensCreateBulk{config: c.config, builders: builders}+}++// Update returns an update builder for PasswordResetTokens.+func (c *PasswordResetTokensClient) Update() *PasswordResetTokensUpdate {+ mutation := newPasswordResetTokensMutation(c.config, OpUpdate)+ return &PasswordResetTokensUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}+}++// UpdateOne returns an update builder for the given entity.+func (c *PasswordResetTokensClient) UpdateOne(_m *PasswordResetTokens) *PasswordResetTokensUpdateOne {+ mutation := newPasswordResetTokensMutation(c.config, OpUpdateOne, withPasswordResetTokens(_m))+ return &PasswordResetTokensUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}+}++// UpdateOneID returns an update builder for the given id.+func (c *PasswordResetTokensClient) UpdateOneID(id uuid.UUID) *PasswordResetTokensUpdateOne {+ mutation := newPasswordResetTokensMutation(c.config, OpUpdateOne, withPasswordResetTokensID(id))+ return &PasswordResetTokensUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}+}++// Delete returns a delete builder for PasswordResetTokens.+func (c *PasswordResetTokensClient) Delete() *PasswordResetTokensDelete {+ mutation := newPasswordResetTokensMutation(c.config, OpDelete)+ return &PasswordResetTokensDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}+}++// DeleteOne returns a builder for deleting the given entity.+func (c *PasswordResetTokensClient) DeleteOne(_m *PasswordResetTokens) *PasswordResetTokensDeleteOne {+ return c.DeleteOneID(_m.ID)+}++// DeleteOneID returns a builder for deleting the given entity by its id.+func (c *PasswordResetTokensClient) DeleteOneID(id uuid.UUID) *PasswordResetTokensDeleteOne {+ builder := c.Delete().Where(passwordresettokens.ID(id))+ builder.mutation.id = &id+ builder.mutation.op = OpDeleteOne+ return &PasswordResetTokensDeleteOne{builder}+}++// Query returns a query builder for PasswordResetTokens.+func (c *PasswordResetTokensClient) Query() *PasswordResetTokensQuery {+ return &PasswordResetTokensQuery{+ config: c.config,+ ctx: &QueryContext{Type: TypePasswordResetTokens},+ inters: c.Interceptors(),+ }+}++// Get returns a PasswordResetTokens entity by its id.+func (c *PasswordResetTokensClient) Get(ctx context.Context, id uuid.UUID) (*PasswordResetTokens, error) {+ return c.Query().Where(passwordresettokens.ID(id)).Only(ctx)+}++// GetX is like Get, but panics if an error occurs.+func (c *PasswordResetTokensClient) GetX(ctx context.Context, id uuid.UUID) *PasswordResetTokens {+ obj, err := c.Get(ctx, id)+ if err != nil {+ panic(err)+ }+ return obj+}++// QueryUser queries the user edge of a PasswordResetTokens.+func (c *PasswordResetTokensClient) QueryUser(_m *PasswordResetTokens) *UserQuery {+ query := (&UserClient{config: c.config}).Query()+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {+ id := _m.ID+ step := sqlgraph.NewStep(+ sqlgraph.From(passwordresettokens.Table, passwordresettokens.FieldID, id),+ sqlgraph.To(user.Table, user.FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, passwordresettokens.UserTable, passwordresettokens.UserColumn),+ )+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)+ return fromV, nil+ }+ return query+}++// Hooks returns the client hooks.+func (c *PasswordResetTokensClient) Hooks() []Hook {+ return c.hooks.PasswordResetTokens+}++// Interceptors returns the client interceptors.+func (c *PasswordResetTokensClient) Interceptors() []Interceptor {+ return c.inters.PasswordResetTokens+}++func (c *PasswordResetTokensClient) mutate(ctx context.Context, m *PasswordResetTokensMutation) (Value, error) {+ switch m.Op() {+ case OpCreate:+ return (&PasswordResetTokensCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)+ case OpUpdate:+ return (&PasswordResetTokensUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)+ case OpUpdateOne:+ return (&PasswordResetTokensUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)+ case OpDelete, OpDeleteOne:+ return (&PasswordResetTokensDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)+ default:+ return nil, fmt.Errorf("ent: unknown PasswordResetTokens mutation op: %q", m.Op())+ }+}+// TagClient is a client for the Tag schema.type TagClient struct {config@@ -2940,6 +3099,22 @@ func (c *UserClient) QueryAuthTokens(_m *User) *AuthTokensQuery {return query}+// QueryPasswordResetTokens queries the password_reset_tokens edge of a User.+func (c *UserClient) QueryPasswordResetTokens(_m *User) *PasswordResetTokensQuery {+ query := (&PasswordResetTokensClient{config: c.config}).Query()+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {+ id := _m.ID+ step := sqlgraph.NewStep(+ sqlgraph.From(user.Table, user.FieldID, id),+ sqlgraph.To(passwordresettokens.Table, passwordresettokens.FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, user.PasswordResetTokensTable, user.PasswordResetTokensColumn),+ )+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)+ return fromV, nil+ }+ return query+}+// QueryAPIKeys queries the api_keys edge of a User.func (c *UserClient) QueryAPIKeys(_m *User) *APIKeyQuery {query := (&APIKeyClient{config: c.config}).Query()@@ -3133,12 +3308,12 @@ func (c *UserGroupClient) mutate(ctx context.Context, m *UserGroupMutation) (Valtype (hooks struct {APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,- EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,- TemplateField, User, UserGroup []ent.Hook+ EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier,+ PasswordResetTokens, Tag, TemplateField, User, UserGroup []ent.Hook}inters struct {APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,- EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,- TemplateField, User, UserGroup []ent.Interceptor+ EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier,+ PasswordResetTokens, Tag, TemplateField, User, UserGroup []ent.Interceptor})diff --git a/backend/internal/data/ent/ent.go b/backend/internal/data/ent/ent.goindex a6374045..d574ec3b 100644--- a/backend/internal/data/ent/ent.go+++ b/backend/internal/data/ent/ent.go@@ -24,6 +24,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/groupinvitationtoken""github.com/sysadminsmedia/homebox/backend/internal/data/ent/maintenanceentry""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag""github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield""github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"@@ -100,6 +101,7 @@ func checkColumn(t, c string) error {groupinvitationtoken.Table: groupinvitationtoken.ValidColumn,maintenanceentry.Table: maintenanceentry.ValidColumn,notifier.Table: notifier.ValidColumn,+ passwordresettokens.Table: passwordresettokens.ValidColumn,tag.Table: tag.ValidColumn,templatefield.Table: templatefield.ValidColumn,user.Table: user.ValidColumn,diff --git a/backend/internal/data/ent/has_id.go b/backend/internal/data/ent/has_id.goindex e1e483ca..42064105 100644--- a/backend/internal/data/ent/has_id.go+++ b/backend/internal/data/ent/has_id.go@@ -52,6 +52,10 @@ func (_m *Notifier) GetID() uuid.UUID {return _m.ID}+func (_m *PasswordResetTokens) GetID() uuid.UUID {+ return _m.ID+}+func (_m *Tag) GetID() uuid.UUID {return _m.ID}diff --git a/backend/internal/data/ent/hook/hook.go b/backend/internal/data/ent/hook/hook.goindex 675f999b..03641dc4 100644--- a/backend/internal/data/ent/hook/hook.go+++ b/backend/internal/data/ent/hook/hook.go@@ -153,6 +153,18 @@ func (f NotifierFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, erreturn nil, fmt.Errorf("unexpected mutation type %T. expect *ent.NotifierMutation", m)}+// The PasswordResetTokensFunc type is an adapter to allow the use of ordinary+// function as PasswordResetTokens mutator.+type PasswordResetTokensFunc func(context.Context, *ent.PasswordResetTokensMutation) (ent.Value, error)++// Mutate calls f(ctx, m).+func (f PasswordResetTokensFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {+ if mv, ok := m.(*ent.PasswordResetTokensMutation); ok {+ return f(ctx, mv)+ }+ return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PasswordResetTokensMutation", m)+}+// The TagFunc type is an adapter to allow the use of ordinary// function as Tag mutator.type TagFunc func(context.Context, *ent.TagMutation) (ent.Value, error)diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.goindex 294a7a2e..4bb7e56b 100644--- a/backend/internal/data/ent/migrate/schema.go+++ b/backend/internal/data/ent/migrate/schema.go@@ -445,6 +445,37 @@ var (},},}+ // PasswordResetTokensColumns holds the columns for the "password_reset_tokens" table.+ PasswordResetTokensColumns = []*schema.Column{+ {Name: "id", Type: field.TypeUUID},+ {Name: "created_at", Type: field.TypeTime},+ {Name: "updated_at", Type: field.TypeTime},+ {Name: "token", Type: field.TypeBytes, Unique: true},+ {Name: "expires_at", Type: field.TypeTime},+ {Name: "used_at", Type: field.TypeTime, Nullable: true},+ {Name: "user_password_reset_tokens", Type: field.TypeUUID},+ }+ // PasswordResetTokensTable holds the schema information for the "password_reset_tokens" table.+ PasswordResetTokensTable = &schema.Table{+ Name: "password_reset_tokens",+ Columns: PasswordResetTokensColumns,+ PrimaryKey: []*schema.Column{PasswordResetTokensColumns[0]},+ ForeignKeys: []*schema.ForeignKey{+ {+ Symbol: "password_reset_tokens_users_password_reset_tokens",+ Columns: []*schema.Column{PasswordResetTokensColumns[6]},+ RefColumns: []*schema.Column{UsersColumns[0]},+ OnDelete: schema.Cascade,+ },+ },+ Indexes: []*schema.Index{+ {+ Name: "passwordresettokens_token",+ Unique: false,+ Columns: []*schema.Column{PasswordResetTokensColumns[3]},+ },+ },+ }// TagsColumns holds the columns for the "tags" table.TagsColumns = []*schema.Column{{Name: "id", Type: field.TypeUUID},@@ -599,6 +630,7 @@ var (GroupInvitationTokensTable,MaintenanceEntriesTable,NotifiersTable,+ PasswordResetTokensTable,TagsTable,TemplateFieldsTable,UsersTable,@@ -625,6 +657,7 @@ func init() {MaintenanceEntriesTable.ForeignKeys[0].RefTable = EntitiesTableNotifiersTable.ForeignKeys[0].RefTable = GroupsTableNotifiersTable.ForeignKeys[1].RefTable = UsersTable+ PasswordResetTokensTable.ForeignKeys[0].RefTable = UsersTableTagsTable.ForeignKeys[0].RefTable = GroupsTableTagsTable.ForeignKeys[1].RefTable = TagsTableTemplateFieldsTable.ForeignKeys[0].RefTable = EntityTemplatesTablediff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.goindex 694ad0e3..e267e555 100644--- a/backend/internal/data/ent/mutation.go+++ b/backend/internal/data/ent/mutation.go@@ -24,6 +24,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/groupinvitationtoken""github.com/sysadminsmedia/homebox/backend/internal/data/ent/maintenanceentry""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate""github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag""github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield"@@ -52,6 +53,7 @@ const (TypeGroupInvitationToken = "GroupInvitationToken"TypeMaintenanceEntry = "MaintenanceEntry"TypeNotifier = "Notifier"+ TypePasswordResetTokens = "PasswordResetTokens"TypeTag = "Tag"TypeTemplateField = "TemplateField"TypeUser = "User"@@ -11914,6 +11916,643 @@ func (m *NotifierMutation) ResetEdge(name string) error {return fmt.Errorf("unknown Notifier edge %s", name)}+// PasswordResetTokensMutation represents an operation that mutates the PasswordResetTokens nodes in the graph.+type PasswordResetTokensMutation struct {+ config+ op Op+ typ string+ id *uuid.UUID+ created_at *time.Time+ updated_at *time.Time+ token *[]byte+ expires_at *time.Time+ used_at *time.Time+ clearedFields map[string]struct{}+ user *uuid.UUID+ cleareduser bool+ done bool+ oldValue func(context.Context) (*PasswordResetTokens, error)+ predicates []predicate.PasswordResetTokens+}++var _ ent.Mutation = (*PasswordResetTokensMutation)(nil)++// passwordresettokensOption allows management of the mutation configuration using functional options.+type passwordresettokensOption func(*PasswordResetTokensMutation)++// newPasswordResetTokensMutation creates new mutation for the PasswordResetTokens entity.+func newPasswordResetTokensMutation(c config, op Op, opts ...passwordresettokensOption) *PasswordResetTokensMutation {+ m := &PasswordResetTokensMutation{+ config: c,+ op: op,+ typ: TypePasswordResetTokens,+ clearedFields: make(map[string]struct{}),+ }+ for _, opt := range opts {+ opt(m)+ }+ return m+}++// withPasswordResetTokensID sets the ID field of the mutation.+func withPasswordResetTokensID(id uuid.UUID) passwordresettokensOption {+ return func(m *PasswordResetTokensMutation) {+ var (+ err error+ once sync.Once+ value *PasswordResetTokens+ )+ m.oldValue = func(ctx context.Context) (*PasswordResetTokens, error) {+ once.Do(func() {+ if m.done {+ err = errors.New("querying old values post mutation is not allowed")+ } else {+ value, err = m.Client().PasswordResetTokens.Get(ctx, id)+ }+ })+ return value, err+ }+ m.id = &id+ }+}++// withPasswordResetTokens sets the old PasswordResetTokens of the mutation.+func withPasswordResetTokens(node *PasswordResetTokens) passwordresettokensOption {+ return func(m *PasswordResetTokensMutation) {+ m.oldValue = func(context.Context) (*PasswordResetTokens, error) {+ return node, nil+ }+ m.id = &node.ID+ }+}++// Client returns a new `ent.Client` from the mutation. If the mutation was+// executed in a transaction (ent.Tx), a transactional client is returned.+func (m PasswordResetTokensMutation) Client() *Client {+ client := &Client{config: m.config}+ client.init()+ return client+}++// Tx returns an `ent.Tx` for mutations that were executed in transactions;+// it returns an error otherwise.+func (m PasswordResetTokensMutation) Tx() (*Tx, error) {+ if _, ok := m.driver.(*txDriver); !ok {+ return nil, errors.New("ent: mutation is not running in a transaction")+ }+ tx := &Tx{config: m.config}+ tx.init()+ return tx, nil+}++// SetID sets the value of the id field. Note that this+// operation is only accepted on creation of PasswordResetTokens entities.+func (m *PasswordResetTokensMutation) SetID(id uuid.UUID) {+ m.id = &id+}++// ID returns the ID value in the mutation. Note that the ID is only available+// if it was provided to the builder or after it was returned from the database.+func (m *PasswordResetTokensMutation) ID() (id uuid.UUID, exists bool) {+ if m.id == nil {+ return+ }+ return *m.id, true+}++// IDs queries the database and returns the entity ids that match the mutation's predicate.+// That means, if the mutation is applied within a transaction with an isolation level such+// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated+// or updated by the mutation.+func (m *PasswordResetTokensMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {+ switch {+ case m.op.Is(OpUpdateOne | OpDeleteOne):+ id, exists := m.ID()+ if exists {+ return []uuid.UUID{id}, nil+ }+ fallthrough+ case m.op.Is(OpUpdate | OpDelete):+ return m.Client().PasswordResetTokens.Query().Where(m.predicates...).IDs(ctx)+ default:+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)+ }+}++// SetCreatedAt sets the "created_at" field.+func (m *PasswordResetTokensMutation) SetCreatedAt(t time.Time) {+ m.created_at = &t+}++// CreatedAt returns the value of the "created_at" field in the mutation.+func (m *PasswordResetTokensMutation) CreatedAt() (r time.Time, exists bool) {+ v := m.created_at+ if v == nil {+ return+ }+ return *v, true+}++// OldCreatedAt returns the old "created_at" field's value of the PasswordResetTokens entity.+// If the PasswordResetTokens object wasn't provided to the builder, the object is fetched from the database.+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.+func (m *PasswordResetTokensMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {+ if !m.op.Is(OpUpdateOne) {+ return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")+ }+ if m.id == nil || m.oldValue == nil {+ return v, errors.New("OldCreatedAt requires an ID field in the mutation")+ }+ oldValue, err := m.oldValue(ctx)+ if err != nil {+ return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)+ }+ return oldValue.CreatedAt, nil+}++// ResetCreatedAt resets all changes to the "created_at" field.+func (m *PasswordResetTokensMutation) ResetCreatedAt() {+ m.created_at = nil+}++// SetUpdatedAt sets the "updated_at" field.+func (m *PasswordResetTokensMutation) SetUpdatedAt(t time.Time) {+ m.updated_at = &t+}++// UpdatedAt returns the value of the "updated_at" field in the mutation.+func (m *PasswordResetTokensMutation) UpdatedAt() (r time.Time, exists bool) {+ v := m.updated_at+ if v == nil {+ return+ }+ return *v, true+}++// OldUpdatedAt returns the old "updated_at" field's value of the PasswordResetTokens entity.+// If the PasswordResetTokens object wasn't provided to the builder, the object is fetched from the database.+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.+func (m *PasswordResetTokensMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {+ if !m.op.Is(OpUpdateOne) {+ return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")+ }+ if m.id == nil || m.oldValue == nil {+ return v, errors.New("OldUpdatedAt requires an ID field in the mutation")+ }+ oldValue, err := m.oldValue(ctx)+ if err != nil {+ return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)+ }+ return oldValue.UpdatedAt, nil+}++// ResetUpdatedAt resets all changes to the "updated_at" field.+func (m *PasswordResetTokensMutation) ResetUpdatedAt() {+ m.updated_at = nil+}++// SetToken sets the "token" field.+func (m *PasswordResetTokensMutation) SetToken(b []byte) {+ m.token = &b+}++// Token returns the value of the "token" field in the mutation.+func (m *PasswordResetTokensMutation) Token() (r []byte, exists bool) {+ v := m.token+ if v == nil {+ return+ }+ return *v, true+}++// OldToken returns the old "token" field's value of the PasswordResetTokens entity.+// If the PasswordResetTokens object wasn't provided to the builder, the object is fetched from the database.+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.+func (m *PasswordResetTokensMutation) OldToken(ctx context.Context) (v []byte, err error) {+ if !m.op.Is(OpUpdateOne) {+ return v, errors.New("OldToken is only allowed on UpdateOne operations")+ }+ if m.id == nil || m.oldValue == nil {+ return v, errors.New("OldToken requires an ID field in the mutation")+ }+ oldValue, err := m.oldValue(ctx)+ if err != nil {+ return v, fmt.Errorf("querying old value for OldToken: %w", err)+ }+ return oldValue.Token, nil+}++// ResetToken resets all changes to the "token" field.+func (m *PasswordResetTokensMutation) ResetToken() {+ m.token = nil+}++// SetExpiresAt sets the "expires_at" field.+func (m *PasswordResetTokensMutation) SetExpiresAt(t time.Time) {+ m.expires_at = &t+}++// ExpiresAt returns the value of the "expires_at" field in the mutation.+func (m *PasswordResetTokensMutation) ExpiresAt() (r time.Time, exists bool) {+ v := m.expires_at+ if v == nil {+ return+ }+ return *v, true+}++// OldExpiresAt returns the old "expires_at" field's value of the PasswordResetTokens entity.+// If the PasswordResetTokens object wasn't provided to the builder, the object is fetched from the database.+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.+func (m *PasswordResetTokensMutation) OldExpiresAt(ctx context.Context) (v time.Time, err error) {+ if !m.op.Is(OpUpdateOne) {+ return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations")+ }+ if m.id == nil || m.oldValue == nil {+ return v, errors.New("OldExpiresAt requires an ID field in the mutation")+ }+ oldValue, err := m.oldValue(ctx)+ if err != nil {+ return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err)+ }+ return oldValue.ExpiresAt, nil+}++// ResetExpiresAt resets all changes to the "expires_at" field.+func (m *PasswordResetTokensMutation) ResetExpiresAt() {+ m.expires_at = nil+}++// SetUsedAt sets the "used_at" field.+func (m *PasswordResetTokensMutation) SetUsedAt(t time.Time) {+ m.used_at = &t+}++// UsedAt returns the value of the "used_at" field in the mutation.+func (m *PasswordResetTokensMutation) UsedAt() (r time.Time, exists bool) {+ v := m.used_at+ if v == nil {+ return+ }+ return *v, true+}++// OldUsedAt returns the old "used_at" field's value of the PasswordResetTokens entity.+// If the PasswordResetTokens object wasn't provided to the builder, the object is fetched from the database.+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.+func (m *PasswordResetTokensMutation) OldUsedAt(ctx context.Context) (v *time.Time, err error) {+ if !m.op.Is(OpUpdateOne) {+ return v, errors.New("OldUsedAt is only allowed on UpdateOne operations")+ }+ if m.id == nil || m.oldValue == nil {+ return v, errors.New("OldUsedAt requires an ID field in the mutation")+ }+ oldValue, err := m.oldValue(ctx)+ if err != nil {+ return v, fmt.Errorf("querying old value for OldUsedAt: %w", err)+ }+ return oldValue.UsedAt, nil+}++// ClearUsedAt clears the value of the "used_at" field.+func (m *PasswordResetTokensMutation) ClearUsedAt() {+ m.used_at = nil+ m.clearedFields[passwordresettokens.FieldUsedAt] = struct{}{}+}++// UsedAtCleared returns if the "used_at" field was cleared in this mutation.+func (m *PasswordResetTokensMutation) UsedAtCleared() bool {+ _, ok := m.clearedFields[passwordresettokens.FieldUsedAt]+ return ok+}++// ResetUsedAt resets all changes to the "used_at" field.+func (m *PasswordResetTokensMutation) ResetUsedAt() {+ m.used_at = nil+ delete(m.clearedFields, passwordresettokens.FieldUsedAt)+}++// SetUserID sets the "user" edge to the User entity by id.+func (m *PasswordResetTokensMutation) SetUserID(id uuid.UUID) {+ m.user = &id+}++// ClearUser clears the "user" edge to the User entity.+func (m *PasswordResetTokensMutation) ClearUser() {+ m.cleareduser = true+}++// UserCleared reports if the "user" edge to the User entity was cleared.+func (m *PasswordResetTokensMutation) UserCleared() bool {+ return m.cleareduser+}++// UserID returns the "user" edge ID in the mutation.+func (m *PasswordResetTokensMutation) UserID() (id uuid.UUID, exists bool) {+ if m.user != nil {+ return *m.user, true+ }+ return+}++// UserIDs returns the "user" edge IDs in the mutation.+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use+// UserID instead. It exists only for internal usage by the builders.+func (m *PasswordResetTokensMutation) UserIDs() (ids []uuid.UUID) {+ if id := m.user; id != nil {+ ids = append(ids, *id)+ }+ return+}++// ResetUser resets all changes to the "user" edge.+func (m *PasswordResetTokensMutation) ResetUser() {+ m.user = nil+ m.cleareduser = false+}++// Where appends a list predicates to the PasswordResetTokensMutation builder.+func (m *PasswordResetTokensMutation) Where(ps ...predicate.PasswordResetTokens) {+ m.predicates = append(m.predicates, ps...)+}++// WhereP appends storage-level predicates to the PasswordResetTokensMutation builder. Using this method,+// users can use type-assertion to append predicates that do not depend on any generated package.+func (m *PasswordResetTokensMutation) WhereP(ps ...func(*sql.Selector)) {+ p := make([]predicate.PasswordResetTokens, len(ps))+ for i := range ps {+ p[i] = ps[i]+ }+ m.Where(p...)+}++// Op returns the operation name.+func (m *PasswordResetTokensMutation) Op() Op {+ return m.op+}++// SetOp allows setting the mutation operation.+func (m *PasswordResetTokensMutation) SetOp(op Op) {+ m.op = op+}++// Type returns the node type of this mutation (PasswordResetTokens).+func (m *PasswordResetTokensMutation) Type() string {+ return m.typ+}++// Fields returns all fields that were changed during this mutation. Note that in+// order to get all numeric fields that were incremented/decremented, call+// AddedFields().+func (m *PasswordResetTokensMutation) Fields() []string {+ fields := make([]string, 0, 5)+ if m.created_at != nil {+ fields = append(fields, passwordresettokens.FieldCreatedAt)+ }+ if m.updated_at != nil {+ fields = append(fields, passwordresettokens.FieldUpdatedAt)+ }+ if m.token != nil {+ fields = append(fields, passwordresettokens.FieldToken)+ }+ if m.expires_at != nil {+ fields = append(fields, passwordresettokens.FieldExpiresAt)+ }+ if m.used_at != nil {+ fields = append(fields, passwordresettokens.FieldUsedAt)+ }+ return fields+}++// Field returns the value of a field with the given name. The second boolean+// return value indicates that this field was not set, or was not defined in the+// schema.+func (m *PasswordResetTokensMutation) Field(name string) (ent.Value, bool) {+ switch name {+ case passwordresettokens.FieldCreatedAt:+ return m.CreatedAt()+ case passwordresettokens.FieldUpdatedAt:+ return m.UpdatedAt()+ case passwordresettokens.FieldToken:+ return m.Token()+ case passwordresettokens.FieldExpiresAt:+ return m.ExpiresAt()+ case passwordresettokens.FieldUsedAt:+ return m.UsedAt()+ }+ return nil, false+}++// OldField returns the old value of the field from the database. An error is+// returned if the mutation operation is not UpdateOne, or the query to the+// database failed.+func (m *PasswordResetTokensMutation) OldField(ctx context.Context, name string) (ent.Value, error) {+ switch name {+ case passwordresettokens.FieldCreatedAt:+ return m.OldCreatedAt(ctx)+ case passwordresettokens.FieldUpdatedAt:+ return m.OldUpdatedAt(ctx)+ case passwordresettokens.FieldToken:+ return m.OldToken(ctx)+ case passwordresettokens.FieldExpiresAt:+ return m.OldExpiresAt(ctx)+ case passwordresettokens.FieldUsedAt:+ return m.OldUsedAt(ctx)+ }+ return nil, fmt.Errorf("unknown PasswordResetTokens field %s", name)+}++// SetField sets the value of a field with the given name. It returns an error if+// the field is not defined in the schema, or if the type mismatched the field+// type.+func (m *PasswordResetTokensMutation) SetField(name string, value ent.Value) error {+ switch name {+ case passwordresettokens.FieldCreatedAt:+ v, ok := value.(time.Time)+ if !ok {+ return fmt.Errorf("unexpected type %T for field %s", value, name)+ }+ m.SetCreatedAt(v)+ return nil+ case passwordresettokens.FieldUpdatedAt:+ v, ok := value.(time.Time)+ if !ok {+ return fmt.Errorf("unexpected type %T for field %s", value, name)+ }+ m.SetUpdatedAt(v)+ return nil+ case passwordresettokens.FieldToken:+ v, ok := value.([]byte)+ if !ok {+ return fmt.Errorf("unexpected type %T for field %s", value, name)+ }+ m.SetToken(v)+ return nil+ case passwordresettokens.FieldExpiresAt:+ v, ok := value.(time.Time)+ if !ok {+ return fmt.Errorf("unexpected type %T for field %s", value, name)+ }+ m.SetExpiresAt(v)+ return nil+ case passwordresettokens.FieldUsedAt:+ v, ok := value.(time.Time)+ if !ok {+ return fmt.Errorf("unexpected type %T for field %s", value, name)+ }+ m.SetUsedAt(v)+ return nil+ }+ return fmt.Errorf("unknown PasswordResetTokens field %s", name)+}++// AddedFields returns all numeric fields that were incremented/decremented during+// this mutation.+func (m *PasswordResetTokensMutation) AddedFields() []string {+ return nil+}++// AddedField returns the numeric value that was incremented/decremented on a field+// with the given name. The second boolean return value indicates that this field+// was not set, or was not defined in the schema.+func (m *PasswordResetTokensMutation) AddedField(name string) (ent.Value, bool) {+ return nil, false+}++// AddField adds the value to the field with the given name. It returns an error if+// the field is not defined in the schema, or if the type mismatched the field+// type.+func (m *PasswordResetTokensMutation) AddField(name string, value ent.Value) error {+ switch name {+ }+ return fmt.Errorf("unknown PasswordResetTokens numeric field %s", name)+}++// ClearedFields returns all nullable fields that were cleared during this+// mutation.+func (m *PasswordResetTokensMutation) ClearedFields() []string {+ var fields []string+ if m.FieldCleared(passwordresettokens.FieldUsedAt) {+ fields = append(fields, passwordresettokens.FieldUsedAt)+ }+ return fields+}++// FieldCleared returns a boolean indicating if a field with the given name was+// cleared in this mutation.+func (m *PasswordResetTokensMutation) FieldCleared(name string) bool {+ _, ok := m.clearedFields[name]+ return ok+}++// ClearField clears the value of the field with the given name. It returns an+// error if the field is not defined in the schema.+func (m *PasswordResetTokensMutation) ClearField(name string) error {+ switch name {+ case passwordresettokens.FieldUsedAt:+ m.ClearUsedAt()+ return nil+ }+ return fmt.Errorf("unknown PasswordResetTokens nullable field %s", name)+}++// ResetField resets all changes in the mutation for the field with the given name.+// It returns an error if the field is not defined in the schema.+func (m *PasswordResetTokensMutation) ResetField(name string) error {+ switch name {+ case passwordresettokens.FieldCreatedAt:+ m.ResetCreatedAt()+ return nil+ case passwordresettokens.FieldUpdatedAt:+ m.ResetUpdatedAt()+ return nil+ case passwordresettokens.FieldToken:+ m.ResetToken()+ return nil+ case passwordresettokens.FieldExpiresAt:+ m.ResetExpiresAt()+ return nil+ case passwordresettokens.FieldUsedAt:+ m.ResetUsedAt()+ return nil+ }+ return fmt.Errorf("unknown PasswordResetTokens field %s", name)+}++// AddedEdges returns all edge names that were set/added in this mutation.+func (m *PasswordResetTokensMutation) AddedEdges() []string {+ edges := make([]string, 0, 1)+ if m.user != nil {+ edges = append(edges, passwordresettokens.EdgeUser)+ }+ return edges+}++// AddedIDs returns all IDs (to other nodes) that were added for the given edge+// name in this mutation.+func (m *PasswordResetTokensMutation) AddedIDs(name string) []ent.Value {+ switch name {+ case passwordresettokens.EdgeUser:+ if id := m.user; id != nil {+ return []ent.Value{*id}+ }+ }+ return nil+}++// RemovedEdges returns all edge names that were removed in this mutation.+func (m *PasswordResetTokensMutation) RemovedEdges() []string {+ edges := make([]string, 0, 1)+ return edges+}++// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with+// the given name in this mutation.+func (m *PasswordResetTokensMutation) RemovedIDs(name string) []ent.Value {+ return nil+}++// ClearedEdges returns all edge names that were cleared in this mutation.+func (m *PasswordResetTokensMutation) ClearedEdges() []string {+ edges := make([]string, 0, 1)+ if m.cleareduser {+ edges = append(edges, passwordresettokens.EdgeUser)+ }+ return edges+}++// EdgeCleared returns a boolean which indicates if the edge with the given name+// was cleared in this mutation.+func (m *PasswordResetTokensMutation) EdgeCleared(name string) bool {+ switch name {+ case passwordresettokens.EdgeUser:+ return m.cleareduser+ }+ return false+}++// ClearEdge clears the value of the edge with the given name. It returns an error+// if that edge is not defined in the schema.+func (m *PasswordResetTokensMutation) ClearEdge(name string) error {+ switch name {+ case passwordresettokens.EdgeUser:+ m.ClearUser()+ return nil+ }+ return fmt.Errorf("unknown PasswordResetTokens unique edge %s", name)+}++// ResetEdge resets all changes to the edge with the given name in this mutation.+// It returns an error if the edge is not defined in the schema.+func (m *PasswordResetTokensMutation) ResetEdge(name string) error {+ switch name {+ case passwordresettokens.EdgeUser:+ m.ResetUser()+ return nil+ }+ return fmt.Errorf("unknown PasswordResetTokens edge %s", name)+}+// TagMutation represents an operation that mutates the Tag nodes in the graph.type TagMutation struct {config@@ -13801,37 +14440,40 @@ func (m *TemplateFieldMutation) ResetEdge(name string) error {// UserMutation represents an operation that mutates the User nodes in the graph.type UserMutation struct {config- op Op- typ string- id *uuid.UUID- created_at *time.Time- updated_at *time.Time- name *string- email *string- password *string- is_superuser *bool- superuser *bool- activated_on *time.Time- oidc_issuer *string- oidc_subject *string- default_group_id *uuid.UUID- settings *map[string]interface{}- clearedFields map[string]struct{}- groups map[uuid.UUID]struct{}- removedgroups map[uuid.UUID]struct{}- clearedgroups bool- auth_tokens map[uuid.UUID]struct{}- removedauth_tokens map[uuid.UUID]struct{}- clearedauth_tokens bool- api_keys map[uuid.UUID]struct{}- removedapi_keys map[uuid.UUID]struct{}- clearedapi_keys bool- notifiers map[uuid.UUID]struct{}- removednotifiers map[uuid.UUID]struct{}- clearednotifiers bool- done bool- oldValue func(context.Context) (*User, error)- predicates []predicate.User+ op Op+ typ string+ id *uuid.UUID+ created_at *time.Time+ updated_at *time.Time+ name *string+ email *string+ password *string+ is_superuser *bool+ superuser *bool+ activated_on *time.Time+ oidc_issuer *string+ oidc_subject *string+ default_group_id *uuid.UUID+ settings *map[string]interface{}+ clearedFields map[string]struct{}+ groups map[uuid.UUID]struct{}+ removedgroups map[uuid.UUID]struct{}+ clearedgroups bool+ auth_tokens map[uuid.UUID]struct{}+ removedauth_tokens map[uuid.UUID]struct{}+ clearedauth_tokens bool+ password_reset_tokens map[uuid.UUID]struct{}+ removedpassword_reset_tokens map[uuid.UUID]struct{}+ clearedpassword_reset_tokens bool+ api_keys map[uuid.UUID]struct{}+ removedapi_keys map[uuid.UUID]struct{}+ clearedapi_keys bool+ notifiers map[uuid.UUID]struct{}+ removednotifiers map[uuid.UUID]struct{}+ clearednotifiers bool+ done bool+ oldValue func(context.Context) (*User, error)+ predicates []predicate.User}var _ ent.Mutation = (*UserMutation)(nil)@@ -14556,6 +15198,60 @@ func (m *UserMutation) ResetAuthTokens() {m.removedauth_tokens = nil}+// AddPasswordResetTokenIDs adds the "password_reset_tokens" edge to the PasswordResetTokens entity by ids.+func (m *UserMutation) AddPasswordResetTokenIDs(ids ...uuid.UUID) {+ if m.password_reset_tokens == nil {+ m.password_reset_tokens = make(map[uuid.UUID]struct{})+ }+ for i := range ids {+ m.password_reset_tokens[ids[i]] = struct{}{}+ }+}++// ClearPasswordResetTokens clears the "password_reset_tokens" edge to the PasswordResetTokens entity.+func (m *UserMutation) ClearPasswordResetTokens() {+ m.clearedpassword_reset_tokens = true+}++// PasswordResetTokensCleared reports if the "password_reset_tokens" edge to the PasswordResetTokens entity was cleared.+func (m *UserMutation) PasswordResetTokensCleared() bool {+ return m.clearedpassword_reset_tokens+}++// RemovePasswordResetTokenIDs removes the "password_reset_tokens" edge to the PasswordResetTokens entity by IDs.+func (m *UserMutation) RemovePasswordResetTokenIDs(ids ...uuid.UUID) {+ if m.removedpassword_reset_tokens == nil {+ m.removedpassword_reset_tokens = make(map[uuid.UUID]struct{})+ }+ for i := range ids {+ delete(m.password_reset_tokens, ids[i])+ m.removedpassword_reset_tokens[ids[i]] = struct{}{}+ }+}++// RemovedPasswordResetTokens returns the removed IDs of the "password_reset_tokens" edge to the PasswordResetTokens entity.+func (m *UserMutation) RemovedPasswordResetTokensIDs() (ids []uuid.UUID) {+ for id := range m.removedpassword_reset_tokens {+ ids = append(ids, id)+ }+ return+}++// PasswordResetTokensIDs returns the "password_reset_tokens" edge IDs in the mutation.+func (m *UserMutation) PasswordResetTokensIDs() (ids []uuid.UUID) {+ for id := range m.password_reset_tokens {+ ids = append(ids, id)+ }+ return+}++// ResetPasswordResetTokens resets all changes to the "password_reset_tokens" edge.+func (m *UserMutation) ResetPasswordResetTokens() {+ m.password_reset_tokens = nil+ m.clearedpassword_reset_tokens = false+ m.removedpassword_reset_tokens = nil+}+// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by ids.func (m *UserMutation) AddAPIKeyIDs(ids ...uuid.UUID) {if m.api_keys == nil {@@ -15023,13 +15719,16 @@ func (m *UserMutation) ResetField(name string) error {// AddedEdges returns all edge names that were set/added in this mutation.func (m *UserMutation) AddedEdges() []string {- edges := make([]string, 0, 4)+ edges := make([]string, 0, 5)if m.groups != nil {edges = append(edges, user.EdgeGroups)}if m.auth_tokens != nil {edges = append(edges, user.EdgeAuthTokens)}+ if m.password_reset_tokens != nil {+ edges = append(edges, user.EdgePasswordResetTokens)+ }if m.api_keys != nil {edges = append(edges, user.EdgeAPIKeys)}@@ -15055,6 +15754,12 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value {ids = append(ids, id)}return ids+ case user.EdgePasswordResetTokens:+ ids := make([]ent.Value, 0, len(m.password_reset_tokens))+ for id := range m.password_reset_tokens {+ ids = append(ids, id)+ }+ return idscase user.EdgeAPIKeys:ids := make([]ent.Value, 0, len(m.api_keys))for id := range m.api_keys {@@ -15073,13 +15778,16 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value {// RemovedEdges returns all edge names that were removed in this mutation.func (m *UserMutation) RemovedEdges() []string {- edges := make([]string, 0, 4)+ edges := make([]string, 0, 5)if m.removedgroups != nil {edges = append(edges, user.EdgeGroups)}if m.removedauth_tokens != nil {edges = append(edges, user.EdgeAuthTokens)}+ if m.removedpassword_reset_tokens != nil {+ edges = append(edges, user.EdgePasswordResetTokens)+ }if m.removedapi_keys != nil {edges = append(edges, user.EdgeAPIKeys)}@@ -15105,6 +15813,12 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value {ids = append(ids, id)}return ids+ case user.EdgePasswordResetTokens:+ ids := make([]ent.Value, 0, len(m.removedpassword_reset_tokens))+ for id := range m.removedpassword_reset_tokens {+ ids = append(ids, id)+ }+ return idscase user.EdgeAPIKeys:ids := make([]ent.Value, 0, len(m.removedapi_keys))for id := range m.removedapi_keys {@@ -15123,13 +15837,16 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value {// ClearedEdges returns all edge names that were cleared in this mutation.func (m *UserMutation) ClearedEdges() []string {- edges := make([]string, 0, 4)+ edges := make([]string, 0, 5)if m.clearedgroups {edges = append(edges, user.EdgeGroups)}if m.clearedauth_tokens {edges = append(edges, user.EdgeAuthTokens)}+ if m.clearedpassword_reset_tokens {+ edges = append(edges, user.EdgePasswordResetTokens)+ }if m.clearedapi_keys {edges = append(edges, user.EdgeAPIKeys)}@@ -15147,6 +15864,8 @@ func (m *UserMutation) EdgeCleared(name string) bool {return m.clearedgroupscase user.EdgeAuthTokens:return m.clearedauth_tokens+ case user.EdgePasswordResetTokens:+ return m.clearedpassword_reset_tokenscase user.EdgeAPIKeys:return m.clearedapi_keyscase user.EdgeNotifiers:@@ -15173,6 +15892,9 @@ func (m *UserMutation) ResetEdge(name string) error {case user.EdgeAuthTokens:m.ResetAuthTokens()return nil+ case user.EdgePasswordResetTokens:+ m.ResetPasswordResetTokens()+ return nilcase user.EdgeAPIKeys:m.ResetAPIKeys()return nildiff --git a/backend/internal/data/ent/passwordresettokens.go b/backend/internal/data/ent/passwordresettokens.gonew file mode 100644index 00000000..ee4254b6--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens.go@@ -0,0 +1,193 @@+// Code generated by ent, DO NOT EDIT.++package ent++import (+ "fmt"+ "strings"+ "time"++ "entgo.io/ent"+ "entgo.io/ent/dialect/sql"+ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"+)++// PasswordResetTokens is the model entity for the PasswordResetTokens schema.+type PasswordResetTokens struct {+ config `json:"-"`+ // ID of the ent.+ ID uuid.UUID `json:"id,omitempty"`+ // CreatedAt holds the value of the "created_at" field.+ CreatedAt time.Time `json:"created_at,omitempty"`+ // UpdatedAt holds the value of the "updated_at" field.+ UpdatedAt time.Time `json:"updated_at,omitempty"`+ // Token holds the value of the "token" field.+ Token []byte `json:"token,omitempty"`+ // ExpiresAt holds the value of the "expires_at" field.+ ExpiresAt time.Time `json:"expires_at,omitempty"`+ // UsedAt holds the value of the "used_at" field.+ UsedAt *time.Time `json:"used_at,omitempty"`+ // Edges holds the relations/edges for other nodes in the graph.+ // The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ Edges PasswordResetTokensEdges `json:"edges"`+ user_password_reset_tokens *uuid.UUID+ selectValues sql.SelectValues+}++// PasswordResetTokensEdges holds the relations/edges for other nodes in the graph.+type PasswordResetTokensEdges struct {+ // User holds the value of the user edge.+ User *User `json:"user,omitempty"`+ // loadedTypes holds the information for reporting if a+ // type was loaded (or requested) in eager-loading or not.+ loadedTypes [1]bool+}++// UserOrErr returns the User value or an error if the edge+// was not loaded in eager-loading, or loaded but was not found.+func (e PasswordResetTokensEdges) UserOrErr() (*User, error) {+ if e.User != nil {+ return e.User, nil+ } else if e.loadedTypes[0] {+ return nil, &NotFoundError{label: user.Label}+ }+ return nil, &NotLoadedError{edge: "user"}+}++// scanValues returns the types for scanning values from sql.Rows.+func (*PasswordResetTokens) scanValues(columns []string) ([]any, error) {+ values := make([]any, len(columns))+ for i := range columns {+ switch columns[i] {+ case passwordresettokens.FieldToken:+ values[i] = new([]byte)+ case passwordresettokens.FieldCreatedAt, passwordresettokens.FieldUpdatedAt, passwordresettokens.FieldExpiresAt, passwordresettokens.FieldUsedAt:+ values[i] = new(sql.NullTime)+ case passwordresettokens.FieldID:+ values[i] = new(uuid.UUID)+ case passwordresettokens.ForeignKeys[0]: // user_password_reset_tokens+ values[i] = &sql.NullScanner{S: new(uuid.UUID)}+ default:+ values[i] = new(sql.UnknownType)+ }+ }+ return values, nil+}++// assignValues assigns the values that were returned from sql.Rows (after scanning)+// to the PasswordResetTokens fields.+func (_m *PasswordResetTokens) assignValues(columns []string, values []any) error {+ if m, n := len(values), len(columns); m < n {+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)+ }+ for i := range columns {+ switch columns[i] {+ case passwordresettokens.FieldID:+ if value, ok := values[i].(*uuid.UUID); !ok {+ return fmt.Errorf("unexpected type %T for field id", values[i])+ } else if value != nil {+ _m.ID = *value+ }+ case passwordresettokens.FieldCreatedAt:+ if value, ok := values[i].(*sql.NullTime); !ok {+ return fmt.Errorf("unexpected type %T for field created_at", values[i])+ } else if value.Valid {+ _m.CreatedAt = value.Time+ }+ case passwordresettokens.FieldUpdatedAt:+ if value, ok := values[i].(*sql.NullTime); !ok {+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])+ } else if value.Valid {+ _m.UpdatedAt = value.Time+ }+ case passwordresettokens.FieldToken:+ if value, ok := values[i].(*[]byte); !ok {+ return fmt.Errorf("unexpected type %T for field token", values[i])+ } else if value != nil {+ _m.Token = *value+ }+ case passwordresettokens.FieldExpiresAt:+ if value, ok := values[i].(*sql.NullTime); !ok {+ return fmt.Errorf("unexpected type %T for field expires_at", values[i])+ } else if value.Valid {+ _m.ExpiresAt = value.Time+ }+ case passwordresettokens.FieldUsedAt:+ if value, ok := values[i].(*sql.NullTime); !ok {+ return fmt.Errorf("unexpected type %T for field used_at", values[i])+ } else if value.Valid {+ _m.UsedAt = new(time.Time)+ *_m.UsedAt = value.Time+ }+ case passwordresettokens.ForeignKeys[0]:+ if value, ok := values[i].(*sql.NullScanner); !ok {+ return fmt.Errorf("unexpected type %T for field user_password_reset_tokens", values[i])+ } else if value.Valid {+ _m.user_password_reset_tokens = new(uuid.UUID)+ *_m.user_password_reset_tokens = *value.S.(*uuid.UUID)+ }+ default:+ _m.selectValues.Set(columns[i], values[i])+ }+ }+ return nil+}++// Value returns the ent.Value that was dynamically selected and assigned to the PasswordResetTokens.+// This includes values selected through modifiers, order, etc.+func (_m *PasswordResetTokens) Value(name string) (ent.Value, error) {+ return _m.selectValues.Get(name)+}++// QueryUser queries the "user" edge of the PasswordResetTokens entity.+func (_m *PasswordResetTokens) QueryUser() *UserQuery {+ return NewPasswordResetTokensClient(_m.config).QueryUser(_m)+}++// Update returns a builder for updating this PasswordResetTokens.+// Note that you need to call PasswordResetTokens.Unwrap() before calling this method if this PasswordResetTokens+// was returned from a transaction, and the transaction was committed or rolled back.+func (_m *PasswordResetTokens) Update() *PasswordResetTokensUpdateOne {+ return NewPasswordResetTokensClient(_m.config).UpdateOne(_m)+}++// Unwrap unwraps the PasswordResetTokens entity that was returned from a transaction after it was closed,+// so that all future queries will be executed through the driver which created the transaction.+func (_m *PasswordResetTokens) Unwrap() *PasswordResetTokens {+ _tx, ok := _m.config.driver.(*txDriver)+ if !ok {+ panic("ent: PasswordResetTokens is not a transactional entity")+ }+ _m.config.driver = _tx.drv+ return _m+}++// String implements the fmt.Stringer.+func (_m *PasswordResetTokens) String() string {+ var builder strings.Builder+ builder.WriteString("PasswordResetTokens(")+ builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))+ builder.WriteString("created_at=")+ builder.WriteString(_m.CreatedAt.Format(time.ANSIC))+ builder.WriteString(", ")+ builder.WriteString("updated_at=")+ builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))+ builder.WriteString(", ")+ builder.WriteString("token=")+ builder.WriteString(fmt.Sprintf("%v", _m.Token))+ builder.WriteString(", ")+ builder.WriteString("expires_at=")+ builder.WriteString(_m.ExpiresAt.Format(time.ANSIC))+ builder.WriteString(", ")+ if v := _m.UsedAt; v != nil {+ builder.WriteString("used_at=")+ builder.WriteString(v.Format(time.ANSIC))+ }+ builder.WriteByte(')')+ return builder.String()+}++// PasswordResetTokensSlice is a parsable slice of PasswordResetTokens.+type PasswordResetTokensSlice []*PasswordResetTokensdiff --git a/backend/internal/data/ent/passwordresettokens/passwordresettokens.go b/backend/internal/data/ent/passwordresettokens/passwordresettokens.gonew file mode 100644index 00000000..b793452f--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens/passwordresettokens.go@@ -0,0 +1,125 @@+// Code generated by ent, DO NOT EDIT.++package passwordresettokens++import (+ "time"++ "entgo.io/ent/dialect/sql"+ "entgo.io/ent/dialect/sql/sqlgraph"+ "github.com/google/uuid"+)++const (+ // Label holds the string label denoting the passwordresettokens type in the database.+ Label = "password_reset_tokens"+ // FieldID holds the string denoting the id field in the database.+ FieldID = "id"+ // FieldCreatedAt holds the string denoting the created_at field in the database.+ FieldCreatedAt = "created_at"+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.+ FieldUpdatedAt = "updated_at"+ // FieldToken holds the string denoting the token field in the database.+ FieldToken = "token"+ // FieldExpiresAt holds the string denoting the expires_at field in the database.+ FieldExpiresAt = "expires_at"+ // FieldUsedAt holds the string denoting the used_at field in the database.+ FieldUsedAt = "used_at"+ // EdgeUser holds the string denoting the user edge name in mutations.+ EdgeUser = "user"+ // Table holds the table name of the passwordresettokens in the database.+ Table = "password_reset_tokens"+ // UserTable is the table that holds the user relation/edge.+ UserTable = "password_reset_tokens"+ // UserInverseTable is the table name for the User entity.+ // It exists in this package in order to avoid circular dependency with the "user" package.+ UserInverseTable = "users"+ // UserColumn is the table column denoting the user relation/edge.+ UserColumn = "user_password_reset_tokens"+)++// Columns holds all SQL columns for passwordresettokens fields.+var Columns = []string{+ FieldID,+ FieldCreatedAt,+ FieldUpdatedAt,+ FieldToken,+ FieldExpiresAt,+ FieldUsedAt,+}++// ForeignKeys holds the SQL foreign-keys that are owned by the "password_reset_tokens"+// table and are not defined as standalone fields in the schema.+var ForeignKeys = []string{+ "user_password_reset_tokens",+}++// ValidColumn reports if the column name is valid (part of the table columns).+func ValidColumn(column string) bool {+ for i := range Columns {+ if column == Columns[i] {+ return true+ }+ }+ for i := range ForeignKeys {+ if column == ForeignKeys[i] {+ return true+ }+ }+ return false+}++var (+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.+ DefaultCreatedAt func() time.Time+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.+ DefaultUpdatedAt func() time.Time+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.+ UpdateDefaultUpdatedAt func() time.Time+ // DefaultExpiresAt holds the default value on creation for the "expires_at" field.+ DefaultExpiresAt func() time.Time+ // DefaultID holds the default value on creation for the "id" field.+ DefaultID func() uuid.UUID+)++// OrderOption defines the ordering options for the PasswordResetTokens queries.+type OrderOption func(*sql.Selector)++// ByID orders the results by the id field.+func ByID(opts ...sql.OrderTermOption) OrderOption {+ return sql.OrderByField(FieldID, opts...).ToFunc()+}++// ByCreatedAt orders the results by the created_at field.+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()+}++// ByUpdatedAt orders the results by the updated_at field.+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()+}++// ByExpiresAt orders the results by the expires_at field.+func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {+ return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()+}++// ByUsedAt orders the results by the used_at field.+func ByUsedAt(opts ...sql.OrderTermOption) OrderOption {+ return sql.OrderByField(FieldUsedAt, opts...).ToFunc()+}++// ByUserField orders the results by user field.+func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))+ }+}+func newUserStep() *sqlgraph.Step {+ return sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.To(UserInverseTable, FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),+ )+}diff --git a/backend/internal/data/ent/passwordresettokens/where.go b/backend/internal/data/ent/passwordresettokens/where.gonew file mode 100644index 00000000..d29acf34--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens/where.go@@ -0,0 +1,330 @@+// Code generated by ent, DO NOT EDIT.++package passwordresettokens++import (+ "time"++ "entgo.io/ent/dialect/sql"+ "entgo.io/ent/dialect/sql/sqlgraph"+ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"+)++// ID filters vertices based on their ID field.+func ID(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldID, id))+}++// IDEQ applies the EQ predicate on the ID field.+func IDEQ(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldID, id))+}++// IDNEQ applies the NEQ predicate on the ID field.+func IDNEQ(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldID, id))+}++// IDIn applies the In predicate on the ID field.+func IDIn(ids ...uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldID, ids...))+}++// IDNotIn applies the NotIn predicate on the ID field.+func IDNotIn(ids ...uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldID, ids...))+}++// IDGT applies the GT predicate on the ID field.+func IDGT(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldID, id))+}++// IDGTE applies the GTE predicate on the ID field.+func IDGTE(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldID, id))+}++// IDLT applies the LT predicate on the ID field.+func IDLT(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldID, id))+}++// IDLTE applies the LTE predicate on the ID field.+func IDLTE(id uuid.UUID) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldID, id))+}++// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.+func CreatedAt(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldCreatedAt, v))+}++// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.+func UpdatedAt(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldUpdatedAt, v))+}++// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.+func Token(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldToken, v))+}++// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.+func ExpiresAt(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldExpiresAt, v))+}++// UsedAt applies equality check predicate on the "used_at" field. It's identical to UsedAtEQ.+func UsedAt(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldUsedAt, v))+}++// CreatedAtEQ applies the EQ predicate on the "created_at" field.+func CreatedAtEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldCreatedAt, v))+}++// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.+func CreatedAtNEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldCreatedAt, v))+}++// CreatedAtIn applies the In predicate on the "created_at" field.+func CreatedAtIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldCreatedAt, vs...))+}++// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.+func CreatedAtNotIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldCreatedAt, vs...))+}++// CreatedAtGT applies the GT predicate on the "created_at" field.+func CreatedAtGT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldCreatedAt, v))+}++// CreatedAtGTE applies the GTE predicate on the "created_at" field.+func CreatedAtGTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldCreatedAt, v))+}++// CreatedAtLT applies the LT predicate on the "created_at" field.+func CreatedAtLT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldCreatedAt, v))+}++// CreatedAtLTE applies the LTE predicate on the "created_at" field.+func CreatedAtLTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldCreatedAt, v))+}++// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.+func UpdatedAtEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldUpdatedAt, v))+}++// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.+func UpdatedAtNEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldUpdatedAt, v))+}++// UpdatedAtIn applies the In predicate on the "updated_at" field.+func UpdatedAtIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldUpdatedAt, vs...))+}++// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.+func UpdatedAtNotIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldUpdatedAt, vs...))+}++// UpdatedAtGT applies the GT predicate on the "updated_at" field.+func UpdatedAtGT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldUpdatedAt, v))+}++// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.+func UpdatedAtGTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldUpdatedAt, v))+}++// UpdatedAtLT applies the LT predicate on the "updated_at" field.+func UpdatedAtLT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldUpdatedAt, v))+}++// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.+func UpdatedAtLTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldUpdatedAt, v))+}++// TokenEQ applies the EQ predicate on the "token" field.+func TokenEQ(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldToken, v))+}++// TokenNEQ applies the NEQ predicate on the "token" field.+func TokenNEQ(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldToken, v))+}++// TokenIn applies the In predicate on the "token" field.+func TokenIn(vs ...[]byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldToken, vs...))+}++// TokenNotIn applies the NotIn predicate on the "token" field.+func TokenNotIn(vs ...[]byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldToken, vs...))+}++// TokenGT applies the GT predicate on the "token" field.+func TokenGT(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldToken, v))+}++// TokenGTE applies the GTE predicate on the "token" field.+func TokenGTE(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldToken, v))+}++// TokenLT applies the LT predicate on the "token" field.+func TokenLT(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldToken, v))+}++// TokenLTE applies the LTE predicate on the "token" field.+func TokenLTE(v []byte) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldToken, v))+}++// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.+func ExpiresAtEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldExpiresAt, v))+}++// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.+func ExpiresAtNEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldExpiresAt, v))+}++// ExpiresAtIn applies the In predicate on the "expires_at" field.+func ExpiresAtIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldExpiresAt, vs...))+}++// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.+func ExpiresAtNotIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldExpiresAt, vs...))+}++// ExpiresAtGT applies the GT predicate on the "expires_at" field.+func ExpiresAtGT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldExpiresAt, v))+}++// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.+func ExpiresAtGTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldExpiresAt, v))+}++// ExpiresAtLT applies the LT predicate on the "expires_at" field.+func ExpiresAtLT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldExpiresAt, v))+}++// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.+func ExpiresAtLTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldExpiresAt, v))+}++// UsedAtEQ applies the EQ predicate on the "used_at" field.+func UsedAtEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldEQ(FieldUsedAt, v))+}++// UsedAtNEQ applies the NEQ predicate on the "used_at" field.+func UsedAtNEQ(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNEQ(FieldUsedAt, v))+}++// UsedAtIn applies the In predicate on the "used_at" field.+func UsedAtIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIn(FieldUsedAt, vs...))+}++// UsedAtNotIn applies the NotIn predicate on the "used_at" field.+func UsedAtNotIn(vs ...time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotIn(FieldUsedAt, vs...))+}++// UsedAtGT applies the GT predicate on the "used_at" field.+func UsedAtGT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGT(FieldUsedAt, v))+}++// UsedAtGTE applies the GTE predicate on the "used_at" field.+func UsedAtGTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldGTE(FieldUsedAt, v))+}++// UsedAtLT applies the LT predicate on the "used_at" field.+func UsedAtLT(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLT(FieldUsedAt, v))+}++// UsedAtLTE applies the LTE predicate on the "used_at" field.+func UsedAtLTE(v time.Time) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldLTE(FieldUsedAt, v))+}++// UsedAtIsNil applies the IsNil predicate on the "used_at" field.+func UsedAtIsNil() predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldIsNull(FieldUsedAt))+}++// UsedAtNotNil applies the NotNil predicate on the "used_at" field.+func UsedAtNotNil() predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.FieldNotNull(FieldUsedAt))+}++// HasUser applies the HasEdge predicate on the "user" edge.+func HasUser() predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(func(s *sql.Selector) {+ step := sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),+ )+ sqlgraph.HasNeighbors(s, step)+ })+}++// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).+func HasUserWith(preds ...predicate.User) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(func(s *sql.Selector) {+ step := newUserStep()+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {+ for _, p := range preds {+ p(s)+ }+ })+ })+}++// And groups predicates with the AND operator between them.+func And(predicates ...predicate.PasswordResetTokens) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.AndPredicates(predicates...))+}++// Or groups predicates with the OR operator between them.+func Or(predicates ...predicate.PasswordResetTokens) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.OrPredicates(predicates...))+}++// Not applies the not operator on the given predicate.+func Not(p predicate.PasswordResetTokens) predicate.PasswordResetTokens {+ return predicate.PasswordResetTokens(sql.NotPredicates(p))+}diff --git a/backend/internal/data/ent/passwordresettokens_create.go b/backend/internal/data/ent/passwordresettokens_create.gonew file mode 100644index 00000000..eeb3887b--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens_create.go@@ -0,0 +1,339 @@+// Code generated by ent, DO NOT EDIT.++package ent++import (+ "context"+ "errors"+ "fmt"+ "time"++ "entgo.io/ent/dialect/sql/sqlgraph"+ "entgo.io/ent/schema/field"+ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"+)++// PasswordResetTokensCreate is the builder for creating a PasswordResetTokens entity.+type PasswordResetTokensCreate struct {+ config+ mutation *PasswordResetTokensMutation+ hooks []Hook+}++// SetCreatedAt sets the "created_at" field.+func (_c *PasswordResetTokensCreate) SetCreatedAt(v time.Time) *PasswordResetTokensCreate {+ _c.mutation.SetCreatedAt(v)+ return _c+}++// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.+func (_c *PasswordResetTokensCreate) SetNillableCreatedAt(v *time.Time) *PasswordResetTokensCreate {+ if v != nil {+ _c.SetCreatedAt(*v)+ }+ return _c+}++// SetUpdatedAt sets the "updated_at" field.+func (_c *PasswordResetTokensCreate) SetUpdatedAt(v time.Time) *PasswordResetTokensCreate {+ _c.mutation.SetUpdatedAt(v)+ return _c+}++// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.+func (_c *PasswordResetTokensCreate) SetNillableUpdatedAt(v *time.Time) *PasswordResetTokensCreate {+ if v != nil {+ _c.SetUpdatedAt(*v)+ }+ return _c+}++// SetToken sets the "token" field.+func (_c *PasswordResetTokensCreate) SetToken(v []byte) *PasswordResetTokensCreate {+ _c.mutation.SetToken(v)+ return _c+}++// SetExpiresAt sets the "expires_at" field.+func (_c *PasswordResetTokensCreate) SetExpiresAt(v time.Time) *PasswordResetTokensCreate {+ _c.mutation.SetExpiresAt(v)+ return _c+}++// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.+func (_c *PasswordResetTokensCreate) SetNillableExpiresAt(v *time.Time) *PasswordResetTokensCreate {+ if v != nil {+ _c.SetExpiresAt(*v)+ }+ return _c+}++// SetUsedAt sets the "used_at" field.+func (_c *PasswordResetTokensCreate) SetUsedAt(v time.Time) *PasswordResetTokensCreate {+ _c.mutation.SetUsedAt(v)+ return _c+}++// SetNillableUsedAt sets the "used_at" field if the given value is not nil.+func (_c *PasswordResetTokensCreate) SetNillableUsedAt(v *time.Time) *PasswordResetTokensCreate {+ if v != nil {+ _c.SetUsedAt(*v)+ }+ return _c+}++// SetID sets the "id" field.+func (_c *PasswordResetTokensCreate) SetID(v uuid.UUID) *PasswordResetTokensCreate {+ _c.mutation.SetID(v)+ return _c+}++// SetNillableID sets the "id" field if the given value is not nil.+func (_c *PasswordResetTokensCreate) SetNillableID(v *uuid.UUID) *PasswordResetTokensCreate {+ if v != nil {+ _c.SetID(*v)+ }+ return _c+}++// SetUserID sets the "user" edge to the User entity by ID.+func (_c *PasswordResetTokensCreate) SetUserID(id uuid.UUID) *PasswordResetTokensCreate {+ _c.mutation.SetUserID(id)+ return _c+}++// SetUser sets the "user" edge to the User entity.+func (_c *PasswordResetTokensCreate) SetUser(v *User) *PasswordResetTokensCreate {+ return _c.SetUserID(v.ID)+}++// Mutation returns the PasswordResetTokensMutation object of the builder.+func (_c *PasswordResetTokensCreate) Mutation() *PasswordResetTokensMutation {+ return _c.mutation+}++// Save creates the PasswordResetTokens in the database.+func (_c *PasswordResetTokensCreate) Save(ctx context.Context) (*PasswordResetTokens, error) {+ _c.defaults()+ return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)+}++// SaveX calls Save and panics if Save returns an error.+func (_c *PasswordResetTokensCreate) SaveX(ctx context.Context) *PasswordResetTokens {+ v, err := _c.Save(ctx)+ if err != nil {+ panic(err)+ }+ return v+}++// Exec executes the query.+func (_c *PasswordResetTokensCreate) Exec(ctx context.Context) error {+ _, err := _c.Save(ctx)+ return err+}++// ExecX is like Exec, but panics if an error occurs.+func (_c *PasswordResetTokensCreate) ExecX(ctx context.Context) {+ if err := _c.Exec(ctx); err != nil {+ panic(err)+ }+}++// defaults sets the default values of the builder before save.+func (_c *PasswordResetTokensCreate) defaults() {+ if _, ok := _c.mutation.CreatedAt(); !ok {+ v := passwordresettokens.DefaultCreatedAt()+ _c.mutation.SetCreatedAt(v)+ }+ if _, ok := _c.mutation.UpdatedAt(); !ok {+ v := passwordresettokens.DefaultUpdatedAt()+ _c.mutation.SetUpdatedAt(v)+ }+ if _, ok := _c.mutation.ExpiresAt(); !ok {+ v := passwordresettokens.DefaultExpiresAt()+ _c.mutation.SetExpiresAt(v)+ }+ if _, ok := _c.mutation.ID(); !ok {+ v := passwordresettokens.DefaultID()+ _c.mutation.SetID(v)+ }+}++// check runs all checks and user-defined validators on the builder.+func (_c *PasswordResetTokensCreate) check() error {+ if _, ok := _c.mutation.CreatedAt(); !ok {+ return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "PasswordResetTokens.created_at"`)}+ }+ if _, ok := _c.mutation.UpdatedAt(); !ok {+ return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "PasswordResetTokens.updated_at"`)}+ }+ if _, ok := _c.mutation.Token(); !ok {+ return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "PasswordResetTokens.token"`)}+ }+ if _, ok := _c.mutation.ExpiresAt(); !ok {+ return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "PasswordResetTokens.expires_at"`)}+ }+ if len(_c.mutation.UserIDs()) == 0 {+ return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "PasswordResetTokens.user"`)}+ }+ return nil+}++func (_c *PasswordResetTokensCreate) sqlSave(ctx context.Context) (*PasswordResetTokens, error) {+ if err := _c.check(); err != nil {+ return nil, err+ }+ _node, _spec := _c.createSpec()+ if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {+ if sqlgraph.IsConstraintError(err) {+ err = &ConstraintError{msg: err.Error(), wrap: err}+ }+ return nil, err+ }+ if _spec.ID.Value != nil {+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {+ _node.ID = *id+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {+ return nil, err+ }+ }+ _c.mutation.id = &_node.ID+ _c.mutation.done = true+ return _node, nil+}++func (_c *PasswordResetTokensCreate) createSpec() (*PasswordResetTokens, *sqlgraph.CreateSpec) {+ var (+ _node = &PasswordResetTokens{config: _c.config}+ _spec = sqlgraph.NewCreateSpec(passwordresettokens.Table, sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID))+ )+ if id, ok := _c.mutation.ID(); ok {+ _node.ID = id+ _spec.ID.Value = &id+ }+ if value, ok := _c.mutation.CreatedAt(); ok {+ _spec.SetField(passwordresettokens.FieldCreatedAt, field.TypeTime, value)+ _node.CreatedAt = value+ }+ if value, ok := _c.mutation.UpdatedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUpdatedAt, field.TypeTime, value)+ _node.UpdatedAt = value+ }+ if value, ok := _c.mutation.Token(); ok {+ _spec.SetField(passwordresettokens.FieldToken, field.TypeBytes, value)+ _node.Token = value+ }+ if value, ok := _c.mutation.ExpiresAt(); ok {+ _spec.SetField(passwordresettokens.FieldExpiresAt, field.TypeTime, value)+ _node.ExpiresAt = value+ }+ if value, ok := _c.mutation.UsedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUsedAt, field.TypeTime, value)+ _node.UsedAt = &value+ }+ if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: passwordresettokens.UserTable,+ Columns: []string{passwordresettokens.UserColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _node.user_password_reset_tokens = &nodes[0]+ _spec.Edges = append(_spec.Edges, edge)+ }+ return _node, _spec+}++// PasswordResetTokensCreateBulk is the builder for creating many PasswordResetTokens entities in bulk.+type PasswordResetTokensCreateBulk struct {+ config+ err error+ builders []*PasswordResetTokensCreate+}++// Save creates the PasswordResetTokens entities in the database.+func (_c *PasswordResetTokensCreateBulk) Save(ctx context.Context) ([]*PasswordResetTokens, error) {+ if _c.err != nil {+ return nil, _c.err+ }+ specs := make([]*sqlgraph.CreateSpec, len(_c.builders))+ nodes := make([]*PasswordResetTokens, len(_c.builders))+ mutators := make([]Mutator, len(_c.builders))+ for i := range _c.builders {+ func(i int, root context.Context) {+ builder := _c.builders[i]+ builder.defaults()+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {+ mutation, ok := m.(*PasswordResetTokensMutation)+ if !ok {+ return nil, fmt.Errorf("unexpected mutation type %T", m)+ }+ if err := builder.check(); err != nil {+ return nil, err+ }+ builder.mutation = mutation+ var err error+ nodes[i], specs[i] = builder.createSpec()+ if i < len(mutators)-1 {+ _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)+ } else {+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}+ // Invoke the actual operation on the latest mutation in the chain.+ if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {+ if sqlgraph.IsConstraintError(err) {+ err = &ConstraintError{msg: err.Error(), wrap: err}+ }+ }+ }+ if err != nil {+ return nil, err+ }+ mutation.id = &nodes[i].ID+ mutation.done = true+ return nodes[i], nil+ })+ for i := len(builder.hooks) - 1; i >= 0; i-- {+ mut = builder.hooks[i](mut)+ }+ mutators[i] = mut+ }(i, ctx)+ }+ if len(mutators) > 0 {+ if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {+ return nil, err+ }+ }+ return nodes, nil+}++// SaveX is like Save, but panics if an error occurs.+func (_c *PasswordResetTokensCreateBulk) SaveX(ctx context.Context) []*PasswordResetTokens {+ v, err := _c.Save(ctx)+ if err != nil {+ panic(err)+ }+ return v+}++// Exec executes the query.+func (_c *PasswordResetTokensCreateBulk) Exec(ctx context.Context) error {+ _, err := _c.Save(ctx)+ return err+}++// ExecX is like Exec, but panics if an error occurs.+func (_c *PasswordResetTokensCreateBulk) ExecX(ctx context.Context) {+ if err := _c.Exec(ctx); err != nil {+ panic(err)+ }+}diff --git a/backend/internal/data/ent/passwordresettokens_delete.go b/backend/internal/data/ent/passwordresettokens_delete.gonew file mode 100644index 00000000..cfd1d989--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens_delete.go@@ -0,0 +1,88 @@+// Code generated by ent, DO NOT EDIT.++package ent++import (+ "context"++ "entgo.io/ent/dialect/sql"+ "entgo.io/ent/dialect/sql/sqlgraph"+ "entgo.io/ent/schema/field"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"+)++// PasswordResetTokensDelete is the builder for deleting a PasswordResetTokens entity.+type PasswordResetTokensDelete struct {+ config+ hooks []Hook+ mutation *PasswordResetTokensMutation+}++// Where appends a list predicates to the PasswordResetTokensDelete builder.+func (_d *PasswordResetTokensDelete) Where(ps ...predicate.PasswordResetTokens) *PasswordResetTokensDelete {+ _d.mutation.Where(ps...)+ return _d+}++// Exec executes the deletion query and returns how many vertices were deleted.+func (_d *PasswordResetTokensDelete) Exec(ctx context.Context) (int, error) {+ return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)+}++// ExecX is like Exec, but panics if an error occurs.+func (_d *PasswordResetTokensDelete) ExecX(ctx context.Context) int {+ n, err := _d.Exec(ctx)+ if err != nil {+ panic(err)+ }+ return n+}++func (_d *PasswordResetTokensDelete) sqlExec(ctx context.Context) (int, error) {+ _spec := sqlgraph.NewDeleteSpec(passwordresettokens.Table, sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID))+ if ps := _d.mutation.predicates; len(ps) > 0 {+ _spec.Predicate = func(selector *sql.Selector) {+ for i := range ps {+ ps[i](selector)+ }+ }+ }+ affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)+ if err != nil && sqlgraph.IsConstraintError(err) {+ err = &ConstraintError{msg: err.Error(), wrap: err}+ }+ _d.mutation.done = true+ return affected, err+}++// PasswordResetTokensDeleteOne is the builder for deleting a single PasswordResetTokens entity.+type PasswordResetTokensDeleteOne struct {+ _d *PasswordResetTokensDelete+}++// Where appends a list predicates to the PasswordResetTokensDelete builder.+func (_d *PasswordResetTokensDeleteOne) Where(ps ...predicate.PasswordResetTokens) *PasswordResetTokensDeleteOne {+ _d._d.mutation.Where(ps...)+ return _d+}++// Exec executes the deletion query.+func (_d *PasswordResetTokensDeleteOne) Exec(ctx context.Context) error {+ n, err := _d._d.Exec(ctx)+ switch {+ case err != nil:+ return err+ case n == 0:+ return &NotFoundError{passwordresettokens.Label}+ default:+ return nil+ }+}++// ExecX is like Exec, but panics if an error occurs.+func (_d *PasswordResetTokensDeleteOne) ExecX(ctx context.Context) {+ if err := _d.Exec(ctx); err != nil {+ panic(err)+ }+}diff --git a/backend/internal/data/ent/passwordresettokens_query.go b/backend/internal/data/ent/passwordresettokens_query.gonew file mode 100644index 00000000..d684b9a8--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens_query.go@@ -0,0 +1,615 @@+// Code generated by ent, DO NOT EDIT.++package ent++import (+ "context"+ "fmt"+ "math"++ "entgo.io/ent"+ "entgo.io/ent/dialect/sql"+ "entgo.io/ent/dialect/sql/sqlgraph"+ "entgo.io/ent/schema/field"+ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"+)++// PasswordResetTokensQuery is the builder for querying PasswordResetTokens entities.+type PasswordResetTokensQuery struct {+ config+ ctx *QueryContext+ order []passwordresettokens.OrderOption+ inters []Interceptor+ predicates []predicate.PasswordResetTokens+ withUser *UserQuery+ withFKs bool+ // intermediate query (i.e. traversal path).+ sql *sql.Selector+ path func(context.Context) (*sql.Selector, error)+}++// Where adds a new predicate for the PasswordResetTokensQuery builder.+func (_q *PasswordResetTokensQuery) Where(ps ...predicate.PasswordResetTokens) *PasswordResetTokensQuery {+ _q.predicates = append(_q.predicates, ps...)+ return _q+}++// Limit the number of records to be returned by this query.+func (_q *PasswordResetTokensQuery) Limit(limit int) *PasswordResetTokensQuery {+ _q.ctx.Limit = &limit+ return _q+}++// Offset to start from.+func (_q *PasswordResetTokensQuery) Offset(offset int) *PasswordResetTokensQuery {+ _q.ctx.Offset = &offset+ return _q+}++// Unique configures the query builder to filter duplicate records on query.+// By default, unique is set to true, and can be disabled using this method.+func (_q *PasswordResetTokensQuery) Unique(unique bool) *PasswordResetTokensQuery {+ _q.ctx.Unique = &unique+ return _q+}++// Order specifies how the records should be ordered.+func (_q *PasswordResetTokensQuery) Order(o ...passwordresettokens.OrderOption) *PasswordResetTokensQuery {+ _q.order = append(_q.order, o...)+ return _q+}++// QueryUser chains the current query on the "user" edge.+func (_q *PasswordResetTokensQuery) QueryUser() *UserQuery {+ query := (&UserClient{config: _q.config}).Query()+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {+ if err := _q.prepareQuery(ctx); err != nil {+ return nil, err+ }+ selector := _q.sqlQuery(ctx)+ if err := selector.Err(); err != nil {+ return nil, err+ }+ step := sqlgraph.NewStep(+ sqlgraph.From(passwordresettokens.Table, passwordresettokens.FieldID, selector),+ sqlgraph.To(user.Table, user.FieldID),+ sqlgraph.Edge(sqlgraph.M2O, true, passwordresettokens.UserTable, passwordresettokens.UserColumn),+ )+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)+ return fromU, nil+ }+ return query+}++// First returns the first PasswordResetTokens entity from the query.+// Returns a *NotFoundError when no PasswordResetTokens was found.+func (_q *PasswordResetTokensQuery) First(ctx context.Context) (*PasswordResetTokens, error) {+ nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))+ if err != nil {+ return nil, err+ }+ if len(nodes) == 0 {+ return nil, &NotFoundError{passwordresettokens.Label}+ }+ return nodes[0], nil+}++// FirstX is like First, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) FirstX(ctx context.Context) *PasswordResetTokens {+ node, err := _q.First(ctx)+ if err != nil && !IsNotFound(err) {+ panic(err)+ }+ return node+}++// FirstID returns the first PasswordResetTokens ID from the query.+// Returns a *NotFoundError when no PasswordResetTokens ID was found.+func (_q *PasswordResetTokensQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {+ var ids []uuid.UUID+ if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {+ return+ }+ if len(ids) == 0 {+ err = &NotFoundError{passwordresettokens.Label}+ return+ }+ return ids[0], nil+}++// FirstIDX is like FirstID, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) FirstIDX(ctx context.Context) uuid.UUID {+ id, err := _q.FirstID(ctx)+ if err != nil && !IsNotFound(err) {+ panic(err)+ }+ return id+}++// Only returns a single PasswordResetTokens entity found by the query, ensuring it only returns one.+// Returns a *NotSingularError when more than one PasswordResetTokens entity is found.+// Returns a *NotFoundError when no PasswordResetTokens entities are found.+func (_q *PasswordResetTokensQuery) Only(ctx context.Context) (*PasswordResetTokens, error) {+ nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))+ if err != nil {+ return nil, err+ }+ switch len(nodes) {+ case 1:+ return nodes[0], nil+ case 0:+ return nil, &NotFoundError{passwordresettokens.Label}+ default:+ return nil, &NotSingularError{passwordresettokens.Label}+ }+}++// OnlyX is like Only, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) OnlyX(ctx context.Context) *PasswordResetTokens {+ node, err := _q.Only(ctx)+ if err != nil {+ panic(err)+ }+ return node+}++// OnlyID is like Only, but returns the only PasswordResetTokens ID in the query.+// Returns a *NotSingularError when more than one PasswordResetTokens ID is found.+// Returns a *NotFoundError when no entities are found.+func (_q *PasswordResetTokensQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {+ var ids []uuid.UUID+ if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {+ return+ }+ switch len(ids) {+ case 1:+ id = ids[0]+ case 0:+ err = &NotFoundError{passwordresettokens.Label}+ default:+ err = &NotSingularError{passwordresettokens.Label}+ }+ return+}++// OnlyIDX is like OnlyID, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) OnlyIDX(ctx context.Context) uuid.UUID {+ id, err := _q.OnlyID(ctx)+ if err != nil {+ panic(err)+ }+ return id+}++// All executes the query and returns a list of PasswordResetTokensSlice.+func (_q *PasswordResetTokensQuery) All(ctx context.Context) ([]*PasswordResetTokens, error) {+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)+ if err := _q.prepareQuery(ctx); err != nil {+ return nil, err+ }+ qr := querierAll[[]*PasswordResetTokens, *PasswordResetTokensQuery]()+ return withInterceptors[[]*PasswordResetTokens](ctx, _q, qr, _q.inters)+}++// AllX is like All, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) AllX(ctx context.Context) []*PasswordResetTokens {+ nodes, err := _q.All(ctx)+ if err != nil {+ panic(err)+ }+ return nodes+}++// IDs executes the query and returns a list of PasswordResetTokens IDs.+func (_q *PasswordResetTokensQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {+ if _q.ctx.Unique == nil && _q.path != nil {+ _q.Unique(true)+ }+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)+ if err = _q.Select(passwordresettokens.FieldID).Scan(ctx, &ids); err != nil {+ return nil, err+ }+ return ids, nil+}++// IDsX is like IDs, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) IDsX(ctx context.Context) []uuid.UUID {+ ids, err := _q.IDs(ctx)+ if err != nil {+ panic(err)+ }+ return ids+}++// Count returns the count of the given query.+func (_q *PasswordResetTokensQuery) Count(ctx context.Context) (int, error) {+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)+ if err := _q.prepareQuery(ctx); err != nil {+ return 0, err+ }+ return withInterceptors[int](ctx, _q, querierCount[*PasswordResetTokensQuery](), _q.inters)+}++// CountX is like Count, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) CountX(ctx context.Context) int {+ count, err := _q.Count(ctx)+ if err != nil {+ panic(err)+ }+ return count+}++// Exist returns true if the query has elements in the graph.+func (_q *PasswordResetTokensQuery) Exist(ctx context.Context) (bool, error) {+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)+ switch _, err := _q.FirstID(ctx); {+ case IsNotFound(err):+ return false, nil+ case err != nil:+ return false, fmt.Errorf("ent: check existence: %w", err)+ default:+ return true, nil+ }+}++// ExistX is like Exist, but panics if an error occurs.+func (_q *PasswordResetTokensQuery) ExistX(ctx context.Context) bool {+ exist, err := _q.Exist(ctx)+ if err != nil {+ panic(err)+ }+ return exist+}++// Clone returns a duplicate of the PasswordResetTokensQuery builder, including all associated steps. It can be+// used to prepare common query builders and use them differently after the clone is made.+func (_q *PasswordResetTokensQuery) Clone() *PasswordResetTokensQuery {+ if _q == nil {+ return nil+ }+ return &PasswordResetTokensQuery{+ config: _q.config,+ ctx: _q.ctx.Clone(),+ order: append([]passwordresettokens.OrderOption{}, _q.order...),+ inters: append([]Interceptor{}, _q.inters...),+ predicates: append([]predicate.PasswordResetTokens{}, _q.predicates...),+ withUser: _q.withUser.Clone(),+ // clone intermediate query.+ sql: _q.sql.Clone(),+ path: _q.path,+ }+}++// WithUser tells the query-builder to eager-load the nodes that are connected to+// the "user" edge. The optional arguments are used to configure the query builder of the edge.+func (_q *PasswordResetTokensQuery) WithUser(opts ...func(*UserQuery)) *PasswordResetTokensQuery {+ query := (&UserClient{config: _q.config}).Query()+ for _, opt := range opts {+ opt(query)+ }+ _q.withUser = query+ return _q+}++// GroupBy is used to group vertices by one or more fields/columns.+// It is often used with aggregate functions, like: count, max, mean, min, sum.+//+// Example:+//+// var v []struct {+// CreatedAt time.Time `json:"created_at,omitempty"`+// Count int `json:"count,omitempty"`+// }+//+// client.PasswordResetTokens.Query().+// GroupBy(passwordresettokens.FieldCreatedAt).+// Aggregate(ent.Count()).+// Scan(ctx, &v)+func (_q *PasswordResetTokensQuery) GroupBy(field string, fields ...string) *PasswordResetTokensGroupBy {+ _q.ctx.Fields = append([]string{field}, fields...)+ grbuild := &PasswordResetTokensGroupBy{build: _q}+ grbuild.flds = &_q.ctx.Fields+ grbuild.label = passwordresettokens.Label+ grbuild.scan = grbuild.Scan+ return grbuild+}++// Select allows the selection one or more fields/columns for the given query,+// instead of selecting all fields in the entity.+//+// Example:+//+// var v []struct {+// CreatedAt time.Time `json:"created_at,omitempty"`+// }+//+// client.PasswordResetTokens.Query().+// Select(passwordresettokens.FieldCreatedAt).+// Scan(ctx, &v)+func (_q *PasswordResetTokensQuery) Select(fields ...string) *PasswordResetTokensSelect {+ _q.ctx.Fields = append(_q.ctx.Fields, fields...)+ sbuild := &PasswordResetTokensSelect{PasswordResetTokensQuery: _q}+ sbuild.label = passwordresettokens.Label+ sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan+ return sbuild+}++// Aggregate returns a PasswordResetTokensSelect configured with the given aggregations.+func (_q *PasswordResetTokensQuery) Aggregate(fns ...AggregateFunc) *PasswordResetTokensSelect {+ return _q.Select().Aggregate(fns...)+}++func (_q *PasswordResetTokensQuery) prepareQuery(ctx context.Context) error {+ for _, inter := range _q.inters {+ if inter == nil {+ return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")+ }+ if trv, ok := inter.(Traverser); ok {+ if err := trv.Traverse(ctx, _q); err != nil {+ return err+ }+ }+ }+ for _, f := range _q.ctx.Fields {+ if !passwordresettokens.ValidColumn(f) {+ return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}+ }+ }+ if _q.path != nil {+ prev, err := _q.path(ctx)+ if err != nil {+ return err+ }+ _q.sql = prev+ }+ return nil+}++func (_q *PasswordResetTokensQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PasswordResetTokens, error) {+ var (+ nodes = []*PasswordResetTokens{}+ withFKs = _q.withFKs+ _spec = _q.querySpec()+ loadedTypes = [1]bool{+ _q.withUser != nil,+ }+ )+ if _q.withUser != nil {+ withFKs = true+ }+ if withFKs {+ _spec.Node.Columns = append(_spec.Node.Columns, passwordresettokens.ForeignKeys...)+ }+ _spec.ScanValues = func(columns []string) ([]any, error) {+ return (*PasswordResetTokens).scanValues(nil, columns)+ }+ _spec.Assign = func(columns []string, values []any) error {+ node := &PasswordResetTokens{config: _q.config}+ nodes = append(nodes, node)+ node.Edges.loadedTypes = loadedTypes+ return node.assignValues(columns, values)+ }+ for i := range hooks {+ hooks[i](ctx, _spec)+ }+ if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {+ return nil, err+ }+ if len(nodes) == 0 {+ return nodes, nil+ }+ if query := _q.withUser; query != nil {+ if err := _q.loadUser(ctx, query, nodes, nil,+ func(n *PasswordResetTokens, e *User) { n.Edges.User = e }); err != nil {+ return nil, err+ }+ }+ return nodes, nil+}++func (_q *PasswordResetTokensQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*PasswordResetTokens, init func(*PasswordResetTokens), assign func(*PasswordResetTokens, *User)) error {+ ids := make([]uuid.UUID, 0, len(nodes))+ nodeids := make(map[uuid.UUID][]*PasswordResetTokens)+ for i := range nodes {+ if nodes[i].user_password_reset_tokens == nil {+ continue+ }+ fk := *nodes[i].user_password_reset_tokens+ if _, ok := nodeids[fk]; !ok {+ ids = append(ids, fk)+ }+ nodeids[fk] = append(nodeids[fk], nodes[i])+ }+ if len(ids) == 0 {+ return nil+ }+ query.Where(user.IDIn(ids...))+ neighbors, err := query.All(ctx)+ if err != nil {+ return err+ }+ for _, n := range neighbors {+ nodes, ok := nodeids[n.ID]+ if !ok {+ return fmt.Errorf(`unexpected foreign-key "user_password_reset_tokens" returned %v`, n.ID)+ }+ for i := range nodes {+ assign(nodes[i], n)+ }+ }+ return nil+}++func (_q *PasswordResetTokensQuery) sqlCount(ctx context.Context) (int, error) {+ _spec := _q.querySpec()+ _spec.Node.Columns = _q.ctx.Fields+ if len(_q.ctx.Fields) > 0 {+ _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique+ }+ return sqlgraph.CountNodes(ctx, _q.driver, _spec)+}++func (_q *PasswordResetTokensQuery) querySpec() *sqlgraph.QuerySpec {+ _spec := sqlgraph.NewQuerySpec(passwordresettokens.Table, passwordresettokens.Columns, sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID))+ _spec.From = _q.sql+ if unique := _q.ctx.Unique; unique != nil {+ _spec.Unique = *unique+ } else if _q.path != nil {+ _spec.Unique = true+ }+ if fields := _q.ctx.Fields; len(fields) > 0 {+ _spec.Node.Columns = make([]string, 0, len(fields))+ _spec.Node.Columns = append(_spec.Node.Columns, passwordresettokens.FieldID)+ for i := range fields {+ if fields[i] != passwordresettokens.FieldID {+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])+ }+ }+ }+ if ps := _q.predicates; len(ps) > 0 {+ _spec.Predicate = func(selector *sql.Selector) {+ for i := range ps {+ ps[i](selector)+ }+ }+ }+ if limit := _q.ctx.Limit; limit != nil {+ _spec.Limit = *limit+ }+ if offset := _q.ctx.Offset; offset != nil {+ _spec.Offset = *offset+ }+ if ps := _q.order; len(ps) > 0 {+ _spec.Order = func(selector *sql.Selector) {+ for i := range ps {+ ps[i](selector)+ }+ }+ }+ return _spec+}++func (_q *PasswordResetTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {+ builder := sql.Dialect(_q.driver.Dialect())+ t1 := builder.Table(passwordresettokens.Table)+ columns := _q.ctx.Fields+ if len(columns) == 0 {+ columns = passwordresettokens.Columns+ }+ selector := builder.Select(t1.Columns(columns...)...).From(t1)+ if _q.sql != nil {+ selector = _q.sql+ selector.Select(selector.Columns(columns...)...)+ }+ if _q.ctx.Unique != nil && *_q.ctx.Unique {+ selector.Distinct()+ }+ for _, p := range _q.predicates {+ p(selector)+ }+ for _, p := range _q.order {+ p(selector)+ }+ if offset := _q.ctx.Offset; offset != nil {+ // limit is mandatory for offset clause. We start+ // with default value, and override it below if needed.+ selector.Offset(*offset).Limit(math.MaxInt32)+ }+ if limit := _q.ctx.Limit; limit != nil {+ selector.Limit(*limit)+ }+ return selector+}++// PasswordResetTokensGroupBy is the group-by builder for PasswordResetTokens entities.+type PasswordResetTokensGroupBy struct {+ selector+ build *PasswordResetTokensQuery+}++// Aggregate adds the given aggregation functions to the group-by query.+func (_g *PasswordResetTokensGroupBy) Aggregate(fns ...AggregateFunc) *PasswordResetTokensGroupBy {+ _g.fns = append(_g.fns, fns...)+ return _g+}++// Scan applies the selector query and scans the result into the given value.+func (_g *PasswordResetTokensGroupBy) Scan(ctx context.Context, v any) error {+ ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)+ if err := _g.build.prepareQuery(ctx); err != nil {+ return err+ }+ return scanWithInterceptors[*PasswordResetTokensQuery, *PasswordResetTokensGroupBy](ctx, _g.build, _g, _g.build.inters, v)+}++func (_g *PasswordResetTokensGroupBy) sqlScan(ctx context.Context, root *PasswordResetTokensQuery, v any) error {+ selector := root.sqlQuery(ctx).Select()+ aggregation := make([]string, 0, len(_g.fns))+ for _, fn := range _g.fns {+ aggregation = append(aggregation, fn(selector))+ }+ if len(selector.SelectedColumns()) == 0 {+ columns := make([]string, 0, len(*_g.flds)+len(_g.fns))+ for _, f := range *_g.flds {+ columns = append(columns, selector.C(f))+ }+ columns = append(columns, aggregation...)+ selector.Select(columns...)+ }+ selector.GroupBy(selector.Columns(*_g.flds...)...)+ if err := selector.Err(); err != nil {+ return err+ }+ rows := &sql.Rows{}+ query, args := selector.Query()+ if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {+ return err+ }+ defer rows.Close()+ return sql.ScanSlice(rows, v)+}++// PasswordResetTokensSelect is the builder for selecting fields of PasswordResetTokens entities.+type PasswordResetTokensSelect struct {+ *PasswordResetTokensQuery+ selector+}++// Aggregate adds the given aggregation functions to the selector query.+func (_s *PasswordResetTokensSelect) Aggregate(fns ...AggregateFunc) *PasswordResetTokensSelect {+ _s.fns = append(_s.fns, fns...)+ return _s+}++// Scan applies the selector query and scans the result into the given value.+func (_s *PasswordResetTokensSelect) Scan(ctx context.Context, v any) error {+ ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)+ if err := _s.prepareQuery(ctx); err != nil {+ return err+ }+ return scanWithInterceptors[*PasswordResetTokensQuery, *PasswordResetTokensSelect](ctx, _s.PasswordResetTokensQuery, _s, _s.inters, v)+}++func (_s *PasswordResetTokensSelect) sqlScan(ctx context.Context, root *PasswordResetTokensQuery, v any) error {+ selector := root.sqlQuery(ctx)+ aggregation := make([]string, 0, len(_s.fns))+ for _, fn := range _s.fns {+ aggregation = append(aggregation, fn(selector))+ }+ switch n := len(*_s.selector.flds); {+ case n == 0 && len(aggregation) > 0:+ selector.Select(aggregation...)+ case n != 0 && len(aggregation) > 0:+ selector.AppendSelect(aggregation...)+ }+ rows := &sql.Rows{}+ query, args := selector.Query()+ if err := _s.driver.Query(ctx, query, args, rows); err != nil {+ return err+ }+ defer rows.Close()+ return sql.ScanSlice(rows, v)+}diff --git a/backend/internal/data/ent/passwordresettokens_update.go b/backend/internal/data/ent/passwordresettokens_update.gonew file mode 100644index 00000000..94f08c16--- /dev/null+++ b/backend/internal/data/ent/passwordresettokens_update.go@@ -0,0 +1,432 @@+// Code generated by ent, DO NOT EDIT.++package ent++import (+ "context"+ "errors"+ "fmt"+ "time"++ "entgo.io/ent/dialect/sql"+ "entgo.io/ent/dialect/sql/sqlgraph"+ "entgo.io/ent/schema/field"+ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"+)++// PasswordResetTokensUpdate is the builder for updating PasswordResetTokens entities.+type PasswordResetTokensUpdate struct {+ config+ hooks []Hook+ mutation *PasswordResetTokensMutation+}++// Where appends a list predicates to the PasswordResetTokensUpdate builder.+func (_u *PasswordResetTokensUpdate) Where(ps ...predicate.PasswordResetTokens) *PasswordResetTokensUpdate {+ _u.mutation.Where(ps...)+ return _u+}++// SetUpdatedAt sets the "updated_at" field.+func (_u *PasswordResetTokensUpdate) SetUpdatedAt(v time.Time) *PasswordResetTokensUpdate {+ _u.mutation.SetUpdatedAt(v)+ return _u+}++// SetToken sets the "token" field.+func (_u *PasswordResetTokensUpdate) SetToken(v []byte) *PasswordResetTokensUpdate {+ _u.mutation.SetToken(v)+ return _u+}++// SetExpiresAt sets the "expires_at" field.+func (_u *PasswordResetTokensUpdate) SetExpiresAt(v time.Time) *PasswordResetTokensUpdate {+ _u.mutation.SetExpiresAt(v)+ return _u+}++// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.+func (_u *PasswordResetTokensUpdate) SetNillableExpiresAt(v *time.Time) *PasswordResetTokensUpdate {+ if v != nil {+ _u.SetExpiresAt(*v)+ }+ return _u+}++// SetUsedAt sets the "used_at" field.+func (_u *PasswordResetTokensUpdate) SetUsedAt(v time.Time) *PasswordResetTokensUpdate {+ _u.mutation.SetUsedAt(v)+ return _u+}++// SetNillableUsedAt sets the "used_at" field if the given value is not nil.+func (_u *PasswordResetTokensUpdate) SetNillableUsedAt(v *time.Time) *PasswordResetTokensUpdate {+ if v != nil {+ _u.SetUsedAt(*v)+ }+ return _u+}++// ClearUsedAt clears the value of the "used_at" field.+func (_u *PasswordResetTokensUpdate) ClearUsedAt() *PasswordResetTokensUpdate {+ _u.mutation.ClearUsedAt()+ return _u+}++// SetUserID sets the "user" edge to the User entity by ID.+func (_u *PasswordResetTokensUpdate) SetUserID(id uuid.UUID) *PasswordResetTokensUpdate {+ _u.mutation.SetUserID(id)+ return _u+}++// SetUser sets the "user" edge to the User entity.+func (_u *PasswordResetTokensUpdate) SetUser(v *User) *PasswordResetTokensUpdate {+ return _u.SetUserID(v.ID)+}++// Mutation returns the PasswordResetTokensMutation object of the builder.+func (_u *PasswordResetTokensUpdate) Mutation() *PasswordResetTokensMutation {+ return _u.mutation+}++// ClearUser clears the "user" edge to the User entity.+func (_u *PasswordResetTokensUpdate) ClearUser() *PasswordResetTokensUpdate {+ _u.mutation.ClearUser()+ return _u+}++// Save executes the query and returns the number of nodes affected by the update operation.+func (_u *PasswordResetTokensUpdate) Save(ctx context.Context) (int, error) {+ _u.defaults()+ return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)+}++// SaveX is like Save, but panics if an error occurs.+func (_u *PasswordResetTokensUpdate) SaveX(ctx context.Context) int {+ affected, err := _u.Save(ctx)+ if err != nil {+ panic(err)+ }+ return affected+}++// Exec executes the query.+func (_u *PasswordResetTokensUpdate) Exec(ctx context.Context) error {+ _, err := _u.Save(ctx)+ return err+}++// ExecX is like Exec, but panics if an error occurs.+func (_u *PasswordResetTokensUpdate) ExecX(ctx context.Context) {+ if err := _u.Exec(ctx); err != nil {+ panic(err)+ }+}++// defaults sets the default values of the builder before save.+func (_u *PasswordResetTokensUpdate) defaults() {+ if _, ok := _u.mutation.UpdatedAt(); !ok {+ v := passwordresettokens.UpdateDefaultUpdatedAt()+ _u.mutation.SetUpdatedAt(v)+ }+}++// check runs all checks and user-defined validators on the builder.+func (_u *PasswordResetTokensUpdate) check() error {+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {+ return errors.New(`ent: clearing a required unique edge "PasswordResetTokens.user"`)+ }+ return nil+}++func (_u *PasswordResetTokensUpdate) sqlSave(ctx context.Context) (_node int, err error) {+ if err := _u.check(); err != nil {+ return _node, err+ }+ _spec := sqlgraph.NewUpdateSpec(passwordresettokens.Table, passwordresettokens.Columns, sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID))+ if ps := _u.mutation.predicates; len(ps) > 0 {+ _spec.Predicate = func(selector *sql.Selector) {+ for i := range ps {+ ps[i](selector)+ }+ }+ }+ if value, ok := _u.mutation.UpdatedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUpdatedAt, field.TypeTime, value)+ }+ if value, ok := _u.mutation.Token(); ok {+ _spec.SetField(passwordresettokens.FieldToken, field.TypeBytes, value)+ }+ if value, ok := _u.mutation.ExpiresAt(); ok {+ _spec.SetField(passwordresettokens.FieldExpiresAt, field.TypeTime, value)+ }+ if value, ok := _u.mutation.UsedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUsedAt, field.TypeTime, value)+ }+ if _u.mutation.UsedAtCleared() {+ _spec.ClearField(passwordresettokens.FieldUsedAt, field.TypeTime)+ }+ if _u.mutation.UserCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: passwordresettokens.UserTable,+ Columns: []string{passwordresettokens.UserColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: passwordresettokens.UserTable,+ Columns: []string{passwordresettokens.UserColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }+ if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {+ if _, ok := err.(*sqlgraph.NotFoundError); ok {+ err = &NotFoundError{passwordresettokens.Label}+ } else if sqlgraph.IsConstraintError(err) {+ err = &ConstraintError{msg: err.Error(), wrap: err}+ }+ return 0, err+ }+ _u.mutation.done = true+ return _node, nil+}++// PasswordResetTokensUpdateOne is the builder for updating a single PasswordResetTokens entity.+type PasswordResetTokensUpdateOne struct {+ config+ fields []string+ hooks []Hook+ mutation *PasswordResetTokensMutation+}++// SetUpdatedAt sets the "updated_at" field.+func (_u *PasswordResetTokensUpdateOne) SetUpdatedAt(v time.Time) *PasswordResetTokensUpdateOne {+ _u.mutation.SetUpdatedAt(v)+ return _u+}++// SetToken sets the "token" field.+func (_u *PasswordResetTokensUpdateOne) SetToken(v []byte) *PasswordResetTokensUpdateOne {+ _u.mutation.SetToken(v)+ return _u+}++// SetExpiresAt sets the "expires_at" field.+func (_u *PasswordResetTokensUpdateOne) SetExpiresAt(v time.Time) *PasswordResetTokensUpdateOne {+ _u.mutation.SetExpiresAt(v)+ return _u+}++// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.+func (_u *PasswordResetTokensUpdateOne) SetNillableExpiresAt(v *time.Time) *PasswordResetTokensUpdateOne {+ if v != nil {+ _u.SetExpiresAt(*v)+ }+ return _u+}++// SetUsedAt sets the "used_at" field.+func (_u *PasswordResetTokensUpdateOne) SetUsedAt(v time.Time) *PasswordResetTokensUpdateOne {+ _u.mutation.SetUsedAt(v)+ return _u+}++// SetNillableUsedAt sets the "used_at" field if the given value is not nil.+func (_u *PasswordResetTokensUpdateOne) SetNillableUsedAt(v *time.Time) *PasswordResetTokensUpdateOne {+ if v != nil {+ _u.SetUsedAt(*v)+ }+ return _u+}++// ClearUsedAt clears the value of the "used_at" field.+func (_u *PasswordResetTokensUpdateOne) ClearUsedAt() *PasswordResetTokensUpdateOne {+ _u.mutation.ClearUsedAt()+ return _u+}++// SetUserID sets the "user" edge to the User entity by ID.+func (_u *PasswordResetTokensUpdateOne) SetUserID(id uuid.UUID) *PasswordResetTokensUpdateOne {+ _u.mutation.SetUserID(id)+ return _u+}++// SetUser sets the "user" edge to the User entity.+func (_u *PasswordResetTokensUpdateOne) SetUser(v *User) *PasswordResetTokensUpdateOne {+ return _u.SetUserID(v.ID)+}++// Mutation returns the PasswordResetTokensMutation object of the builder.+func (_u *PasswordResetTokensUpdateOne) Mutation() *PasswordResetTokensMutation {+ return _u.mutation+}++// ClearUser clears the "user" edge to the User entity.+func (_u *PasswordResetTokensUpdateOne) ClearUser() *PasswordResetTokensUpdateOne {+ _u.mutation.ClearUser()+ return _u+}++// Where appends a list predicates to the PasswordResetTokensUpdate builder.+func (_u *PasswordResetTokensUpdateOne) Where(ps ...predicate.PasswordResetTokens) *PasswordResetTokensUpdateOne {+ _u.mutation.Where(ps...)+ return _u+}++// Select allows selecting one or more fields (columns) of the returned entity.+// The default is selecting all fields defined in the entity schema.+func (_u *PasswordResetTokensUpdateOne) Select(field string, fields ...string) *PasswordResetTokensUpdateOne {+ _u.fields = append([]string{field}, fields...)+ return _u+}++// Save executes the query and returns the updated PasswordResetTokens entity.+func (_u *PasswordResetTokensUpdateOne) Save(ctx context.Context) (*PasswordResetTokens, error) {+ _u.defaults()+ return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)+}++// SaveX is like Save, but panics if an error occurs.+func (_u *PasswordResetTokensUpdateOne) SaveX(ctx context.Context) *PasswordResetTokens {+ node, err := _u.Save(ctx)+ if err != nil {+ panic(err)+ }+ return node+}++// Exec executes the query on the entity.+func (_u *PasswordResetTokensUpdateOne) Exec(ctx context.Context) error {+ _, err := _u.Save(ctx)+ return err+}++// ExecX is like Exec, but panics if an error occurs.+func (_u *PasswordResetTokensUpdateOne) ExecX(ctx context.Context) {+ if err := _u.Exec(ctx); err != nil {+ panic(err)+ }+}++// defaults sets the default values of the builder before save.+func (_u *PasswordResetTokensUpdateOne) defaults() {+ if _, ok := _u.mutation.UpdatedAt(); !ok {+ v := passwordresettokens.UpdateDefaultUpdatedAt()+ _u.mutation.SetUpdatedAt(v)+ }+}++// check runs all checks and user-defined validators on the builder.+func (_u *PasswordResetTokensUpdateOne) check() error {+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {+ return errors.New(`ent: clearing a required unique edge "PasswordResetTokens.user"`)+ }+ return nil+}++func (_u *PasswordResetTokensUpdateOne) sqlSave(ctx context.Context) (_node *PasswordResetTokens, err error) {+ if err := _u.check(); err != nil {+ return _node, err+ }+ _spec := sqlgraph.NewUpdateSpec(passwordresettokens.Table, passwordresettokens.Columns, sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID))+ id, ok := _u.mutation.ID()+ if !ok {+ return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "PasswordResetTokens.id" for update`)}+ }+ _spec.Node.ID.Value = id+ if fields := _u.fields; len(fields) > 0 {+ _spec.Node.Columns = make([]string, 0, len(fields))+ _spec.Node.Columns = append(_spec.Node.Columns, passwordresettokens.FieldID)+ for _, f := range fields {+ if !passwordresettokens.ValidColumn(f) {+ return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}+ }+ if f != passwordresettokens.FieldID {+ _spec.Node.Columns = append(_spec.Node.Columns, f)+ }+ }+ }+ if ps := _u.mutation.predicates; len(ps) > 0 {+ _spec.Predicate = func(selector *sql.Selector) {+ for i := range ps {+ ps[i](selector)+ }+ }+ }+ if value, ok := _u.mutation.UpdatedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUpdatedAt, field.TypeTime, value)+ }+ if value, ok := _u.mutation.Token(); ok {+ _spec.SetField(passwordresettokens.FieldToken, field.TypeBytes, value)+ }+ if value, ok := _u.mutation.ExpiresAt(); ok {+ _spec.SetField(passwordresettokens.FieldExpiresAt, field.TypeTime, value)+ }+ if value, ok := _u.mutation.UsedAt(); ok {+ _spec.SetField(passwordresettokens.FieldUsedAt, field.TypeTime, value)+ }+ if _u.mutation.UsedAtCleared() {+ _spec.ClearField(passwordresettokens.FieldUsedAt, field.TypeTime)+ }+ if _u.mutation.UserCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: passwordresettokens.UserTable,+ Columns: []string{passwordresettokens.UserColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.M2O,+ Inverse: true,+ Table: passwordresettokens.UserTable,+ Columns: []string{passwordresettokens.UserColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }+ _node = &PasswordResetTokens{config: _u.config}+ _spec.Assign = _node.assignValues+ _spec.ScanValues = _node.scanValues+ if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {+ if _, ok := err.(*sqlgraph.NotFoundError); ok {+ err = &NotFoundError{passwordresettokens.Label}+ } else if sqlgraph.IsConstraintError(err) {+ err = &ConstraintError{msg: err.Error(), wrap: err}+ }+ return nil, err+ }+ _u.mutation.done = true+ return _node, nil+}diff --git a/backend/internal/data/ent/predicate/predicate.go b/backend/internal/data/ent/predicate/predicate.goindex 81ba6ac0..fd2ac993 100644--- a/backend/internal/data/ent/predicate/predicate.go+++ b/backend/internal/data/ent/predicate/predicate.go@@ -42,6 +42,9 @@ type MaintenanceEntry func(*sql.Selector)// Notifier is the predicate function for notifier builders.type Notifier func(*sql.Selector)+// PasswordResetTokens is the predicate function for passwordresettokens builders.+type PasswordResetTokens func(*sql.Selector)+// Tag is the predicate function for tag builders.type Tag func(*sql.Selector)diff --git a/backend/internal/data/ent/runtime.go b/backend/internal/data/ent/runtime.goindex bc9a2b1f..454e857a 100644--- a/backend/internal/data/ent/runtime.go+++ b/backend/internal/data/ent/runtime.go@@ -17,6 +17,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/groupinvitationtoken""github.com/sysadminsmedia/homebox/backend/internal/data/ent/maintenanceentry""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/schema""github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag""github.com/sysadminsmedia/homebox/backend/internal/data/ent/templatefield"@@ -596,6 +597,29 @@ func init() {notifierDescID := notifierMixinFields0[0].Descriptor()// notifier.DefaultID holds the default value on creation for the id field.notifier.DefaultID = notifierDescID.Default.(func() uuid.UUID)+ passwordresettokensMixin := schema.PasswordResetTokens{}.Mixin()+ passwordresettokensMixinFields0 := passwordresettokensMixin[0].Fields()+ _ = passwordresettokensMixinFields0+ passwordresettokensFields := schema.PasswordResetTokens{}.Fields()+ _ = passwordresettokensFields+ // passwordresettokensDescCreatedAt is the schema descriptor for created_at field.+ passwordresettokensDescCreatedAt := passwordresettokensMixinFields0[1].Descriptor()+ // passwordresettokens.DefaultCreatedAt holds the default value on creation for the created_at field.+ passwordresettokens.DefaultCreatedAt = passwordresettokensDescCreatedAt.Default.(func() time.Time)+ // passwordresettokensDescUpdatedAt is the schema descriptor for updated_at field.+ passwordresettokensDescUpdatedAt := passwordresettokensMixinFields0[2].Descriptor()+ // passwordresettokens.DefaultUpdatedAt holds the default value on creation for the updated_at field.+ passwordresettokens.DefaultUpdatedAt = passwordresettokensDescUpdatedAt.Default.(func() time.Time)+ // passwordresettokens.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.+ passwordresettokens.UpdateDefaultUpdatedAt = passwordresettokensDescUpdatedAt.UpdateDefault.(func() time.Time)+ // passwordresettokensDescExpiresAt is the schema descriptor for expires_at field.+ passwordresettokensDescExpiresAt := passwordresettokensFields[1].Descriptor()+ // passwordresettokens.DefaultExpiresAt holds the default value on creation for the expires_at field.+ passwordresettokens.DefaultExpiresAt = passwordresettokensDescExpiresAt.Default.(func() time.Time)+ // passwordresettokensDescID is the schema descriptor for id field.+ passwordresettokensDescID := passwordresettokensMixinFields0[0].Descriptor()+ // passwordresettokens.DefaultID holds the default value on creation for the id field.+ passwordresettokens.DefaultID = passwordresettokensDescID.Default.(func() uuid.UUID)tagMixin := schema.Tag{}.Mixin()tagMixinFields0 := tagMixin[0].Fields()_ = tagMixinFields0diff --git a/backend/internal/data/ent/schema/password_reset_tokens.go b/backend/internal/data/ent/schema/password_reset_tokens.gonew file mode 100644index 00000000..c21d463a--- /dev/null+++ b/backend/internal/data/ent/schema/password_reset_tokens.go@@ -0,0 +1,55 @@+package schema++import (+ "time"++ "entgo.io/ent"+ "entgo.io/ent/dialect/entsql"+ "entgo.io/ent/schema/edge"+ "entgo.io/ent/schema/field"+ "entgo.io/ent/schema/index"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/schema/mixins"+)++// PasswordResetTokens holds single-use reset tokens for the forgot-password flow.+// The schema mirrors AuthTokens; the only addition is `used_at`, which is set+// when the token is consumed so a replay reuses neither the row nor a new one.+type PasswordResetTokens struct {+ ent.Schema+}++func (PasswordResetTokens) Mixin() []ent.Mixin {+ return []ent.Mixin{+ mixins.BaseMixin{},+ }+}++func (PasswordResetTokens) Fields() []ent.Field {+ return []ent.Field{+ field.Bytes("token").+ Unique(),+ field.Time("expires_at").+ Default(func() time.Time { return time.Now().Add(time.Hour) }),+ field.Time("used_at").+ Optional().+ Nillable(),+ }+}++func (PasswordResetTokens) Edges() []ent.Edge {+ return []ent.Edge{+ edge.From("user", User.Type).+ Ref("password_reset_tokens").+ Unique().+ Required().+ Annotations(entsql.Annotation{+ OnDelete: entsql.Cascade,+ }),+ }+}++func (PasswordResetTokens) Indexes() []ent.Index {+ return []ent.Index{+ index.Fields("token"),+ }+}diff --git a/backend/internal/data/ent/schema/user.go b/backend/internal/data/ent/schema/user.goindex 541c810b..7b059a59 100644--- a/backend/internal/data/ent/schema/user.go+++ b/backend/internal/data/ent/schema/user.go@@ -74,6 +74,10 @@ func (User) Edges() []ent.Edge {Annotations(entsql.Annotation{OnDelete: entsql.Cascade,}),+ edge.To("password_reset_tokens", PasswordResetTokens.Type).+ Annotations(entsql.Annotation{+ OnDelete: entsql.Cascade,+ }),edge.To("api_keys", APIKey.Type).Annotations(entsql.Annotation{OnDelete: entsql.Cascade,diff --git a/backend/internal/data/ent/tx.go b/backend/internal/data/ent/tx.goindex 44faa7e0..48063134 100644--- a/backend/internal/data/ent/tx.go+++ b/backend/internal/data/ent/tx.go@@ -36,6 +36,8 @@ type Tx struct {MaintenanceEntry *MaintenanceEntryClient// Notifier is the client for interacting with the Notifier builders.Notifier *NotifierClient+ // PasswordResetTokens is the client for interacting with the PasswordResetTokens builders.+ PasswordResetTokens *PasswordResetTokensClient// Tag is the client for interacting with the Tag builders.Tag *TagClient// TemplateField is the client for interacting with the TemplateField builders.@@ -187,6 +189,7 @@ func (tx *Tx) init() {tx.GroupInvitationToken = NewGroupInvitationTokenClient(tx.config)tx.MaintenanceEntry = NewMaintenanceEntryClient(tx.config)tx.Notifier = NewNotifierClient(tx.config)+ tx.PasswordResetTokens = NewPasswordResetTokensClient(tx.config)tx.Tag = NewTagClient(tx.config)tx.TemplateField = NewTemplateFieldClient(tx.config)tx.User = NewUserClient(tx.config)diff --git a/backend/internal/data/ent/user.go b/backend/internal/data/ent/user.goindex efd02498..a7c91b4b 100644--- a/backend/internal/data/ent/user.go+++ b/backend/internal/data/ent/user.go@@ -55,6 +55,8 @@ type UserEdges struct {Groups []*Group `json:"groups,omitempty"`// AuthTokens holds the value of the auth_tokens edge.AuthTokens []*AuthTokens `json:"auth_tokens,omitempty"`+ // PasswordResetTokens holds the value of the password_reset_tokens edge.+ PasswordResetTokens []*PasswordResetTokens `json:"password_reset_tokens,omitempty"`// APIKeys holds the value of the api_keys edge.APIKeys []*APIKey `json:"api_keys,omitempty"`// Notifiers holds the value of the notifiers edge.@@ -63,7 +65,7 @@ type UserEdges struct {UserGroups []*UserGroup `json:"user_groups,omitempty"`// loadedTypes holds the information for reporting if a// type was loaded (or requested) in eager-loading or not.- loadedTypes [5]bool+ loadedTypes [6]bool}// GroupsOrErr returns the Groups value or an error if the edge@@ -84,10 +86,19 @@ func (e UserEdges) AuthTokensOrErr() ([]*AuthTokens, error) {return nil, &NotLoadedError{edge: "auth_tokens"}}+// PasswordResetTokensOrErr returns the PasswordResetTokens value or an error if the edge+// was not loaded in eager-loading.+func (e UserEdges) PasswordResetTokensOrErr() ([]*PasswordResetTokens, error) {+ if e.loadedTypes[2] {+ return e.PasswordResetTokens, nil+ }+ return nil, &NotLoadedError{edge: "password_reset_tokens"}+}+// APIKeysOrErr returns the APIKeys value or an error if the edge// was not loaded in eager-loading.func (e UserEdges) APIKeysOrErr() ([]*APIKey, error) {- if e.loadedTypes[2] {+ if e.loadedTypes[3] {return e.APIKeys, nil}return nil, &NotLoadedError{edge: "api_keys"}@@ -96,7 +107,7 @@ func (e UserEdges) APIKeysOrErr() ([]*APIKey, error) {// NotifiersOrErr returns the Notifiers value or an error if the edge// was not loaded in eager-loading.func (e UserEdges) NotifiersOrErr() ([]*Notifier, error) {- if e.loadedTypes[3] {+ if e.loadedTypes[4] {return e.Notifiers, nil}return nil, &NotLoadedError{edge: "notifiers"}@@ -105,7 +116,7 @@ func (e UserEdges) NotifiersOrErr() ([]*Notifier, error) {// UserGroupsOrErr returns the UserGroups value or an error if the edge// was not loaded in eager-loading.func (e UserEdges) UserGroupsOrErr() ([]*UserGroup, error) {- if e.loadedTypes[4] {+ if e.loadedTypes[5] {return e.UserGroups, nil}return nil, &NotLoadedError{edge: "user_groups"}@@ -250,6 +261,11 @@ func (_m *User) QueryAuthTokens() *AuthTokensQuery {return NewUserClient(_m.config).QueryAuthTokens(_m)}+// QueryPasswordResetTokens queries the "password_reset_tokens" edge of the User entity.+func (_m *User) QueryPasswordResetTokens() *PasswordResetTokensQuery {+ return NewUserClient(_m.config).QueryPasswordResetTokens(_m)+}+// QueryAPIKeys queries the "api_keys" edge of the User entity.func (_m *User) QueryAPIKeys() *APIKeyQuery {return NewUserClient(_m.config).QueryAPIKeys(_m)diff --git a/backend/internal/data/ent/user/user.go b/backend/internal/data/ent/user/user.goindex 4f17abb5..a9acadd3 100644--- a/backend/internal/data/ent/user/user.go+++ b/backend/internal/data/ent/user/user.go@@ -43,6 +43,8 @@ const (EdgeGroups = "groups"// EdgeAuthTokens holds the string denoting the auth_tokens edge name in mutations.EdgeAuthTokens = "auth_tokens"+ // EdgePasswordResetTokens holds the string denoting the password_reset_tokens edge name in mutations.+ EdgePasswordResetTokens = "password_reset_tokens"// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.EdgeAPIKeys = "api_keys"// EdgeNotifiers holds the string denoting the notifiers edge name in mutations.@@ -63,6 +65,13 @@ const (AuthTokensInverseTable = "auth_tokens"// AuthTokensColumn is the table column denoting the auth_tokens relation/edge.AuthTokensColumn = "user_auth_tokens"+ // PasswordResetTokensTable is the table that holds the password_reset_tokens relation/edge.+ PasswordResetTokensTable = "password_reset_tokens"+ // PasswordResetTokensInverseTable is the table name for the PasswordResetTokens entity.+ // It exists in this package in order to avoid circular dependency with the "passwordresettokens" package.+ PasswordResetTokensInverseTable = "password_reset_tokens"+ // PasswordResetTokensColumn is the table column denoting the password_reset_tokens relation/edge.+ PasswordResetTokensColumn = "user_password_reset_tokens"// APIKeysTable is the table that holds the api_keys relation/edge.APIKeysTable = "api_keys"// APIKeysInverseTable is the table name for the APIKey entity.@@ -231,6 +240,20 @@ func ByAuthTokens(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {}}+// ByPasswordResetTokensCount orders the results by password_reset_tokens count.+func ByPasswordResetTokensCount(opts ...sql.OrderTermOption) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborsCount(s, newPasswordResetTokensStep(), opts...)+ }+}++// ByPasswordResetTokens orders the results by password_reset_tokens terms.+func ByPasswordResetTokens(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {+ return func(s *sql.Selector) {+ sqlgraph.OrderByNeighborTerms(s, newPasswordResetTokensStep(), append([]sql.OrderTerm{term}, terms...)...)+ }+}+// ByAPIKeysCount orders the results by api_keys count.func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {return func(s *sql.Selector) {@@ -286,6 +309,13 @@ func newAuthTokensStep() *sqlgraph.Step {sqlgraph.Edge(sqlgraph.O2M, false, AuthTokensTable, AuthTokensColumn),)}+func newPasswordResetTokensStep() *sqlgraph.Step {+ return sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.To(PasswordResetTokensInverseTable, FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, PasswordResetTokensTable, PasswordResetTokensColumn),+ )+}func newAPIKeysStep() *sqlgraph.Step {return sqlgraph.NewStep(sqlgraph.From(Table, FieldID),diff --git a/backend/internal/data/ent/user/where.go b/backend/internal/data/ent/user/where.goindex 89d24821..1f484cb1 100644--- a/backend/internal/data/ent/user/where.go+++ b/backend/internal/data/ent/user/where.go@@ -722,6 +722,29 @@ func HasAuthTokensWith(preds ...predicate.AuthTokens) predicate.User {})}+// HasPasswordResetTokens applies the HasEdge predicate on the "password_reset_tokens" edge.+func HasPasswordResetTokens() predicate.User {+ return predicate.User(func(s *sql.Selector) {+ step := sqlgraph.NewStep(+ sqlgraph.From(Table, FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, PasswordResetTokensTable, PasswordResetTokensColumn),+ )+ sqlgraph.HasNeighbors(s, step)+ })+}++// HasPasswordResetTokensWith applies the HasEdge predicate on the "password_reset_tokens" edge with a given conditions (other predicates).+func HasPasswordResetTokensWith(preds ...predicate.PasswordResetTokens) predicate.User {+ return predicate.User(func(s *sql.Selector) {+ step := newPasswordResetTokensStep()+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {+ for _, p := range preds {+ p(s)+ }+ })+ })+}+// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.func HasAPIKeys() predicate.User {return predicate.User(func(s *sql.Selector) {diff --git a/backend/internal/data/ent/user_create.go b/backend/internal/data/ent/user_create.goindex 590303ac..0b5bb317 100644--- a/backend/internal/data/ent/user_create.go+++ b/backend/internal/data/ent/user_create.go@@ -15,6 +15,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/group""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/user")@@ -213,6 +214,21 @@ func (_c *UserCreate) AddAuthTokens(v ...*AuthTokens) *UserCreate {return _c.AddAuthTokenIDs(ids...)}+// AddPasswordResetTokenIDs adds the "password_reset_tokens" edge to the PasswordResetTokens entity by IDs.+func (_c *UserCreate) AddPasswordResetTokenIDs(ids ...uuid.UUID) *UserCreate {+ _c.mutation.AddPasswordResetTokenIDs(ids...)+ return _c+}++// AddPasswordResetTokens adds the "password_reset_tokens" edges to the PasswordResetTokens entity.+func (_c *UserCreate) AddPasswordResetTokens(v ...*PasswordResetTokens) *UserCreate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _c.AddPasswordResetTokenIDs(ids...)+}+// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.func (_c *UserCreate) AddAPIKeyIDs(ids ...uuid.UUID) *UserCreate {_c.mutation.AddAPIKeyIDs(ids...)@@ -454,6 +470,22 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {}_spec.Edges = append(_spec.Edges, edge)}+ if nodes := _c.mutation.PasswordResetTokensIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges = append(_spec.Edges, edge)+ }if nodes := _c.mutation.APIKeysIDs(); len(nodes) > 0 {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.O2M,diff --git a/backend/internal/data/ent/user_query.go b/backend/internal/data/ent/user_query.goindex a20a55a9..a830f799 100644--- a/backend/internal/data/ent/user_query.go+++ b/backend/internal/data/ent/user_query.go@@ -17,6 +17,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/group""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate""github.com/sysadminsmedia/homebox/backend/internal/data/ent/user""github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"@@ -25,15 +26,16 @@ import (// UserQuery is the builder for querying User entities.type UserQuery struct {config- ctx *QueryContext- order []user.OrderOption- inters []Interceptor- predicates []predicate.User- withGroups *GroupQuery- withAuthTokens *AuthTokensQuery- withAPIKeys *APIKeyQuery- withNotifiers *NotifierQuery- withUserGroups *UserGroupQuery+ ctx *QueryContext+ order []user.OrderOption+ inters []Interceptor+ predicates []predicate.User+ withGroups *GroupQuery+ withAuthTokens *AuthTokensQuery+ withPasswordResetTokens *PasswordResetTokensQuery+ withAPIKeys *APIKeyQuery+ withNotifiers *NotifierQuery+ withUserGroups *UserGroupQuery// intermediate query (i.e. traversal path).sql *sql.Selectorpath func(context.Context) (*sql.Selector, error)@@ -114,6 +116,28 @@ func (_q *UserQuery) QueryAuthTokens() *AuthTokensQuery {return query}+// QueryPasswordResetTokens chains the current query on the "password_reset_tokens" edge.+func (_q *UserQuery) QueryPasswordResetTokens() *PasswordResetTokensQuery {+ query := (&PasswordResetTokensClient{config: _q.config}).Query()+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {+ if err := _q.prepareQuery(ctx); err != nil {+ return nil, err+ }+ selector := _q.sqlQuery(ctx)+ if err := selector.Err(); err != nil {+ return nil, err+ }+ step := sqlgraph.NewStep(+ sqlgraph.From(user.Table, user.FieldID, selector),+ sqlgraph.To(passwordresettokens.Table, passwordresettokens.FieldID),+ sqlgraph.Edge(sqlgraph.O2M, false, user.PasswordResetTokensTable, user.PasswordResetTokensColumn),+ )+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)+ return fromU, nil+ }+ return query+}+// QueryAPIKeys chains the current query on the "api_keys" edge.func (_q *UserQuery) QueryAPIKeys() *APIKeyQuery {query := (&APIKeyClient{config: _q.config}).Query()@@ -367,16 +391,17 @@ func (_q *UserQuery) Clone() *UserQuery {return nil}return &UserQuery{- config: _q.config,- ctx: _q.ctx.Clone(),- order: append([]user.OrderOption{}, _q.order...),- inters: append([]Interceptor{}, _q.inters...),- predicates: append([]predicate.User{}, _q.predicates...),- withGroups: _q.withGroups.Clone(),- withAuthTokens: _q.withAuthTokens.Clone(),- withAPIKeys: _q.withAPIKeys.Clone(),- withNotifiers: _q.withNotifiers.Clone(),- withUserGroups: _q.withUserGroups.Clone(),+ config: _q.config,+ ctx: _q.ctx.Clone(),+ order: append([]user.OrderOption{}, _q.order...),+ inters: append([]Interceptor{}, _q.inters...),+ predicates: append([]predicate.User{}, _q.predicates...),+ withGroups: _q.withGroups.Clone(),+ withAuthTokens: _q.withAuthTokens.Clone(),+ withPasswordResetTokens: _q.withPasswordResetTokens.Clone(),+ withAPIKeys: _q.withAPIKeys.Clone(),+ withNotifiers: _q.withNotifiers.Clone(),+ withUserGroups: _q.withUserGroups.Clone(),// clone intermediate query.sql: _q.sql.Clone(),path: _q.path,@@ -405,6 +430,17 @@ func (_q *UserQuery) WithAuthTokens(opts ...func(*AuthTokensQuery)) *UserQuery {return _q}+// WithPasswordResetTokens tells the query-builder to eager-load the nodes that are connected to+// the "password_reset_tokens" edge. The optional arguments are used to configure the query builder of the edge.+func (_q *UserQuery) WithPasswordResetTokens(opts ...func(*PasswordResetTokensQuery)) *UserQuery {+ query := (&PasswordResetTokensClient{config: _q.config}).Query()+ for _, opt := range opts {+ opt(query)+ }+ _q.withPasswordResetTokens = query+ return _q+}+// WithAPIKeys tells the query-builder to eager-load the nodes that are connected to// the "api_keys" edge. The optional arguments are used to configure the query builder of the edge.func (_q *UserQuery) WithAPIKeys(opts ...func(*APIKeyQuery)) *UserQuery {@@ -516,9 +552,10 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, evar (nodes = []*User{}_spec = _q.querySpec()- loadedTypes = [5]bool{+ loadedTypes = [6]bool{_q.withGroups != nil,_q.withAuthTokens != nil,+ _q.withPasswordResetTokens != nil,_q.withAPIKeys != nil,_q.withNotifiers != nil,_q.withUserGroups != nil,@@ -556,6 +593,15 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, ereturn nil, err}}+ if query := _q.withPasswordResetTokens; query != nil {+ if err := _q.loadPasswordResetTokens(ctx, query, nodes,+ func(n *User) { n.Edges.PasswordResetTokens = []*PasswordResetTokens{} },+ func(n *User, e *PasswordResetTokens) {+ n.Edges.PasswordResetTokens = append(n.Edges.PasswordResetTokens, e)+ }); err != nil {+ return nil, err+ }+ }if query := _q.withAPIKeys; query != nil {if err := _q.loadAPIKeys(ctx, query, nodes,func(n *User) { n.Edges.APIKeys = []*APIKey{} },@@ -672,6 +718,37 @@ func (_q *UserQuery) loadAuthTokens(ctx context.Context, query *AuthTokensQuery,}return nil}+func (_q *UserQuery) loadPasswordResetTokens(ctx context.Context, query *PasswordResetTokensQuery, nodes []*User, init func(*User), assign func(*User, *PasswordResetTokens)) error {+ fks := make([]driver.Value, 0, len(nodes))+ nodeids := make(map[uuid.UUID]*User)+ for i := range nodes {+ fks = append(fks, nodes[i].ID)+ nodeids[nodes[i].ID] = nodes[i]+ if init != nil {+ init(nodes[i])+ }+ }+ query.withFKs = true+ query.Where(predicate.PasswordResetTokens(func(s *sql.Selector) {+ s.Where(sql.InValues(s.C(user.PasswordResetTokensColumn), fks...))+ }))+ neighbors, err := query.All(ctx)+ if err != nil {+ return err+ }+ for _, n := range neighbors {+ fk := n.user_password_reset_tokens+ if fk == nil {+ return fmt.Errorf(`foreign-key "user_password_reset_tokens" is nil for node %v`, n.ID)+ }+ node, ok := nodeids[*fk]+ if !ok {+ return fmt.Errorf(`unexpected referenced foreign-key "user_password_reset_tokens" returned %v for node %v`, *fk, n.ID)+ }+ assign(node, n)+ }+ return nil+}func (_q *UserQuery) loadAPIKeys(ctx context.Context, query *APIKeyQuery, nodes []*User, init func(*User), assign func(*User, *APIKey)) error {fks := make([]driver.Value, 0, len(nodes))nodeids := make(map[uuid.UUID]*User)diff --git a/backend/internal/data/ent/user_update.go b/backend/internal/data/ent/user_update.goindex 2d61e4aa..cc1bf25d 100644--- a/backend/internal/data/ent/user_update.go+++ b/backend/internal/data/ent/user_update.go@@ -16,6 +16,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/group""github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens""github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate""github.com/sysadminsmedia/homebox/backend/internal/data/ent/user")@@ -237,6 +238,21 @@ func (_u *UserUpdate) AddAuthTokens(v ...*AuthTokens) *UserUpdate {return _u.AddAuthTokenIDs(ids...)}+// AddPasswordResetTokenIDs adds the "password_reset_tokens" edge to the PasswordResetTokens entity by IDs.+func (_u *UserUpdate) AddPasswordResetTokenIDs(ids ...uuid.UUID) *UserUpdate {+ _u.mutation.AddPasswordResetTokenIDs(ids...)+ return _u+}++// AddPasswordResetTokens adds the "password_reset_tokens" edges to the PasswordResetTokens entity.+func (_u *UserUpdate) AddPasswordResetTokens(v ...*PasswordResetTokens) *UserUpdate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.AddPasswordResetTokenIDs(ids...)+}+// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.func (_u *UserUpdate) AddAPIKeyIDs(ids ...uuid.UUID) *UserUpdate {_u.mutation.AddAPIKeyIDs(ids...)@@ -314,6 +330,27 @@ func (_u *UserUpdate) RemoveAuthTokens(v ...*AuthTokens) *UserUpdate {return _u.RemoveAuthTokenIDs(ids...)}+// ClearPasswordResetTokens clears all "password_reset_tokens" edges to the PasswordResetTokens entity.+func (_u *UserUpdate) ClearPasswordResetTokens() *UserUpdate {+ _u.mutation.ClearPasswordResetTokens()+ return _u+}++// RemovePasswordResetTokenIDs removes the "password_reset_tokens" edge to PasswordResetTokens entities by IDs.+func (_u *UserUpdate) RemovePasswordResetTokenIDs(ids ...uuid.UUID) *UserUpdate {+ _u.mutation.RemovePasswordResetTokenIDs(ids...)+ return _u+}++// RemovePasswordResetTokens removes "password_reset_tokens" edges to PasswordResetTokens entities.+func (_u *UserUpdate) RemovePasswordResetTokens(v ...*PasswordResetTokens) *UserUpdate {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.RemovePasswordResetTokenIDs(ids...)+}+// ClearAPIKeys clears all "api_keys" edges to the APIKey entity.func (_u *UserUpdate) ClearAPIKeys() *UserUpdate {_u.mutation.ClearAPIKeys()@@ -577,6 +614,51 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {}_spec.Edges.Add = append(_spec.Edges.Add, edge)}+ if _u.mutation.PasswordResetTokensCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.RemovedPasswordResetTokensIDs(); len(nodes) > 0 && !_u.mutation.PasswordResetTokensCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.PasswordResetTokensIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }if _u.mutation.APIKeysCleared() {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.O2M,@@ -891,6 +973,21 @@ func (_u *UserUpdateOne) AddAuthTokens(v ...*AuthTokens) *UserUpdateOne {return _u.AddAuthTokenIDs(ids...)}+// AddPasswordResetTokenIDs adds the "password_reset_tokens" edge to the PasswordResetTokens entity by IDs.+func (_u *UserUpdateOne) AddPasswordResetTokenIDs(ids ...uuid.UUID) *UserUpdateOne {+ _u.mutation.AddPasswordResetTokenIDs(ids...)+ return _u+}++// AddPasswordResetTokens adds the "password_reset_tokens" edges to the PasswordResetTokens entity.+func (_u *UserUpdateOne) AddPasswordResetTokens(v ...*PasswordResetTokens) *UserUpdateOne {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.AddPasswordResetTokenIDs(ids...)+}+// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.func (_u *UserUpdateOne) AddAPIKeyIDs(ids ...uuid.UUID) *UserUpdateOne {_u.mutation.AddAPIKeyIDs(ids...)@@ -968,6 +1065,27 @@ func (_u *UserUpdateOne) RemoveAuthTokens(v ...*AuthTokens) *UserUpdateOne {return _u.RemoveAuthTokenIDs(ids...)}+// ClearPasswordResetTokens clears all "password_reset_tokens" edges to the PasswordResetTokens entity.+func (_u *UserUpdateOne) ClearPasswordResetTokens() *UserUpdateOne {+ _u.mutation.ClearPasswordResetTokens()+ return _u+}++// RemovePasswordResetTokenIDs removes the "password_reset_tokens" edge to PasswordResetTokens entities by IDs.+func (_u *UserUpdateOne) RemovePasswordResetTokenIDs(ids ...uuid.UUID) *UserUpdateOne {+ _u.mutation.RemovePasswordResetTokenIDs(ids...)+ return _u+}++// RemovePasswordResetTokens removes "password_reset_tokens" edges to PasswordResetTokens entities.+func (_u *UserUpdateOne) RemovePasswordResetTokens(v ...*PasswordResetTokens) *UserUpdateOne {+ ids := make([]uuid.UUID, len(v))+ for i := range v {+ ids[i] = v[i].ID+ }+ return _u.RemovePasswordResetTokenIDs(ids...)+}+// ClearAPIKeys clears all "api_keys" edges to the APIKey entity.func (_u *UserUpdateOne) ClearAPIKeys() *UserUpdateOne {_u.mutation.ClearAPIKeys()@@ -1261,6 +1379,51 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {}_spec.Edges.Add = append(_spec.Edges.Add, edge)}+ if _u.mutation.PasswordResetTokensCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.RemovedPasswordResetTokensIDs(); len(nodes) > 0 && !_u.mutation.PasswordResetTokensCleared() {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)+ }+ if nodes := _u.mutation.PasswordResetTokensIDs(); len(nodes) > 0 {+ edge := &sqlgraph.EdgeSpec{+ Rel: sqlgraph.O2M,+ Inverse: false,+ Table: user.PasswordResetTokensTable,+ Columns: []string{user.PasswordResetTokensColumn},+ Bidi: false,+ Target: &sqlgraph.EdgeTarget{+ IDSpec: sqlgraph.NewFieldSpec(passwordresettokens.FieldID, field.TypeUUID),+ },+ }+ for _, k := range nodes {+ edge.Target.Nodes = append(edge.Target.Nodes, k)+ }+ _spec.Edges.Add = append(_spec.Edges.Add, edge)+ }if _u.mutation.APIKeysCleared() {edge := &sqlgraph.EdgeSpec{Rel: sqlgraph.O2M,diff --git a/backend/internal/data/migrations/postgres/20260512000001_add_password_reset_tokens.sql b/backend/internal/data/migrations/postgres/20260512000001_add_password_reset_tokens.sqlnew file mode 100644index 00000000..06d7f0a1--- /dev/null+++ b/backend/internal/data/migrations/postgres/20260512000001_add_password_reset_tokens.sql@@ -0,0 +1,21 @@+-- +goose Up+-- Single-use password reset tokens for the forgot-password flow. Tokens are+-- stored as a sha256 hash; the raw value is sent only over email/CLI exactly+-- once. used_at is set when consumed so a replay finds neither a fresh row+-- nor an unmarked one.+CREATE TABLE IF NOT EXISTS "password_reset_tokens" (+ "id" uuid NOT NULL,+ "created_at" timestamptz NOT NULL,+ "updated_at" timestamptz NOT NULL,+ "user_id" uuid NOT NULL,+ "token" bytea NOT NULL,+ "expires_at" timestamptz NOT NULL,+ "used_at" timestamptz NULL,+ PRIMARY KEY ("id"),+ CONSTRAINT "password_reset_tokens_users_password_reset_tokens" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON UPDATE NO ACTION ON DELETE CASCADE+);+CREATE UNIQUE INDEX IF NOT EXISTS "password_reset_tokens_token_key" ON "password_reset_tokens" ("token");+CREATE INDEX IF NOT EXISTS "passwordresettokens_user_id" ON "password_reset_tokens" ("user_id");++-- +goose Down+DROP TABLE IF EXISTS "password_reset_tokens";diff --git a/backend/internal/data/migrations/sqlite3/20260512000000_add_password_reset_tokens.sql b/backend/internal/data/migrations/sqlite3/20260512000000_add_password_reset_tokens.sqlnew file mode 100644index 00000000..1f1b73e3--- /dev/null+++ b/backend/internal/data/migrations/sqlite3/20260512000000_add_password_reset_tokens.sql@@ -0,0 +1,28 @@+-- +goose Up+-- Single-use password reset tokens for the forgot-password flow. Tokens are+-- stored as a sha256 hash; the raw value is sent only over email/CLI exactly+-- once. used_at is set when consumed so a replay finds neither a fresh row+-- nor an unmarked one.+create table if not exists password_reset_tokens+(+ id uuid not null+ primary key,+ created_at datetime not null,+ updated_at datetime not null,+ user_id uuid not null+ constraint password_reset_tokens_users_password_reset_tokens+ references users+ on delete cascade,+ token blob not null,+ expires_at datetime not null,+ used_at datetime+);++create unique index if not exists password_reset_tokens_token_key+ on password_reset_tokens (token);++create index if not exists passwordresettokens_user_id+ on password_reset_tokens (user_id);++-- +goose Down+drop table if exists password_reset_tokens;diff --git a/backend/internal/data/repo/repo_items_search_test.go b/backend/internal/data/repo/repo_items_search_test.goindex de62a8e5..4d3f2164 100644--- a/backend/internal/data/repo/repo_items_search_test.go+++ b/backend/internal/data/repo/repo_items_search_test.go@@ -7,6 +7,9 @@ import ("github.com/sysadminsmedia/homebox/backend/pkgs/textutils")+// Repeated test fixture; constant satisfies goconst across the test cases below.+const fixtureElectronicaAccented = "electrónica"+func TestEntityRepository_AccentInsensitiveSearch(t *testing.T) {// Test cases for accent-insensitive searchtestCases := []struct {@@ -18,22 +21,22 @@ func TestEntityRepository_AccentInsensitiveSearch(t *testing.T) {}{{name: "Spanish accented item, search without accents",- itemName: "electrónica",+ itemName: fixtureElectronicaAccented,searchQuery: "electronica",shouldMatch: true,description: "Should find 'electrónica' when searching for 'electronica'",},{name: "Spanish accented item, search with accents",- itemName: "electrónica",- searchQuery: "electrónica",+ itemName: fixtureElectronicaAccented,+ searchQuery: fixtureElectronicaAccented,shouldMatch: true,description: "Should find 'electrónica' when searching for 'electrónica'",},{name: "Non-accented item, search with accents",itemName: "electronica",- searchQuery: "electrónica",+ searchQuery: fixtureElectronicaAccented,shouldMatch: true,description: "Should find 'electronica' when searching for 'electrónica' (bidirectional search)",},@@ -186,7 +189,7 @@ func TestNormalizeSearchQueryIntegration(t *testing.T) {input stringexpected string}{- {"electrónica", "electronica"},+ {fixtureElectronicaAccented, "electronica"},{"café", "cafe"},{"ELECTRÓNICA", "electronica"},{"Café París", "cafe paris"},diff --git a/backend/internal/data/repo/repo_password_reset.go b/backend/internal/data/repo/repo_password_reset.gonew file mode 100644index 00000000..2c747a6a--- /dev/null+++ b/backend/internal/data/repo/repo_password_reset.go@@ -0,0 +1,198 @@+package repo++import (+ "context"+ "errors"+ "time"++ "github.com/google/uuid"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/trace"+)++type PasswordResetTokenRepository struct {+ db *ent.Client+}++type PasswordResetToken struct {+ ID uuid.UUID+ UserID uuid.UUID+ ExpiresAt time.Time+}++// Create persists a hashed reset token for the given user.+func (r *PasswordResetTokenRepository) Create(ctx context.Context, userID uuid.UUID, tokenHash []byte, expiresAt time.Time) (PasswordResetToken, error) {+ ctx, span := entityTracer().Start(ctx, "repo.PasswordResetTokenRepository.Create",+ trace.WithAttributes(+ attribute.String("user.id", userID.String()),+ attribute.String("token.expires_at", expiresAt.Format(time.RFC3339)),+ ))+ defer span.End()++ row, err := r.db.PasswordResetTokens.Create().+ SetUserID(userID).+ SetToken(tokenHash).+ SetExpiresAt(expiresAt).+ Save(ctx)+ if err != nil {+ recordSpanError(span, err)+ return PasswordResetToken{}, err+ }++ return PasswordResetToken{+ ID: row.ID,+ UserID: userID,+ ExpiresAt: row.ExpiresAt,+ }, nil+}++// GetValidByHash returns the token row matching the given hash if it has not+// expired and has not been used. Returns ent.NotFound otherwise so callers+// can't distinguish "wrong token" from "expired" from "used" — all three look+// the same from the outside, which is what we want.+func (r *PasswordResetTokenRepository) GetValidByHash(ctx context.Context, tokenHash []byte) (PasswordResetToken, error) {+ ctx, span := entityTracer().Start(ctx, "repo.PasswordResetTokenRepository.GetValidByHash",+ trace.WithAttributes(attribute.Int("token.hash.length", len(tokenHash))))+ defer span.End()++ row, err := r.db.PasswordResetTokens.Query().+ Where(+ passwordresettokens.Token(tokenHash),+ passwordresettokens.UsedAtIsNil(),+ passwordresettokens.ExpiresAtGT(time.Now()),+ ).+ WithUser().+ Only(ctx)+ if err != nil {+ span.SetAttributes(+ attribute.Bool("token.found", false),+ attribute.Bool("token.lookup.not_found", ent.IsNotFound(err)),+ )+ if !ent.IsNotFound(err) {+ recordSpanError(span, err)+ }+ return PasswordResetToken{}, err+ }++ span.SetAttributes(attribute.Bool("token.found", true))+ return PasswordResetToken{+ ID: row.ID,+ UserID: row.Edges.User.ID,+ ExpiresAt: row.ExpiresAt,+ }, nil+}++// ErrPasswordResetTokenAlreadyClaimed is returned by MarkUsed when no+// unclaimed row matched the predicate — i.e. the token was used by a+// concurrent request. Callers must treat this as the same kind of failure as+// "token not found" so a race doesn't let two resets succeed against the+// same token.+var ErrPasswordResetTokenAlreadyClaimed = errors.New("password reset token was already claimed")++// MarkUsed atomically sets used_at on the token, succeeding only if used_at+// was previously NULL AND the token has not yet expired. Returns+// ErrPasswordResetTokenAlreadyClaimed if a concurrent caller won the race or+// if the token expired between GetValidByHash and this call. Callers should+// claim BEFORE running any side effects (changing the password, etc.) so the+// token can be used at most once even under contention.+func (r *PasswordResetTokenRepository) MarkUsed(ctx context.Context, id uuid.UUID, at time.Time) error {+ ctx, span := entityTracer().Start(ctx, "repo.PasswordResetTokenRepository.MarkUsed",+ trace.WithAttributes(attribute.String("token.id", id.String())))+ defer span.End()++ affected, err := r.db.PasswordResetTokens.Update().+ Where(+ passwordresettokens.ID(id),+ passwordresettokens.UsedAtIsNil(),+ passwordresettokens.ExpiresAtGT(at),+ ).+ SetUsedAt(at).+ Save(ctx)+ if err != nil {+ recordSpanError(span, err)+ return err+ }+ span.SetAttributes(attribute.Int("tokens.claimed.count", affected))+ if affected == 0 {+ return ErrPasswordResetTokenAlreadyClaimed+ }+ return nil+}++// ConsumeAndChangePassword atomically claims the reset token (used_at IS NULL+// → now) and writes the new password hash to the user, in a single transaction.+// Either both writes commit or neither does — a transient DB failure between+// them can no longer leave the system in the half-state where the token is+// burned but the password is unchanged.+//+// The conditional UPDATE inside the tx still gives us the same race-loss+// semantics MarkUsed had: a concurrent reset against the same token sees 0+// rows affected here and gets ErrPasswordResetTokenAlreadyClaimed.+func (r *PasswordResetTokenRepository) ConsumeAndChangePassword(ctx context.Context, tokenID, userID uuid.UUID, hashedPassword string) error {+ ctx, span := entityTracer().Start(ctx, "repo.PasswordResetTokenRepository.ConsumeAndChangePassword",+ trace.WithAttributes(+ attribute.String("token.id", tokenID.String()),+ attribute.String("user.id", userID.String()),+ ))+ defer span.End()++ tx, err := r.db.Tx(ctx)+ if err != nil {+ recordSpanError(span, err)+ return err+ }++ now := time.Now()+ affected, err := tx.PasswordResetTokens.Update().+ Where(+ passwordresettokens.ID(tokenID),+ passwordresettokens.UsedAtIsNil(),+ passwordresettokens.ExpiresAtGT(now),+ ).+ SetUsedAt(now).+ Save(ctx)+ if err != nil {+ _ = tx.Rollback()+ recordSpanError(span, err)+ return err+ }+ if affected == 0 {+ _ = tx.Rollback()+ span.SetAttributes(attribute.Int("tokens.claimed.count", 0))+ return ErrPasswordResetTokenAlreadyClaimed+ }++ if err := tx.User.UpdateOneID(userID).SetPassword(hashedPassword).Exec(ctx); err != nil {+ _ = tx.Rollback()+ recordSpanError(span, err)+ return err+ }++ if err := tx.Commit(); err != nil {+ recordSpanError(span, err)+ return err+ }+ span.SetAttributes(attribute.Int("tokens.claimed.count", 1))+ return nil+}++// PurgeExpired deletes expired and already-used tokens. Run periodically.+func (r *PasswordResetTokenRepository) PurgeExpired(ctx context.Context) (int, error) {+ ctx, span := entityTracer().Start(ctx, "repo.PasswordResetTokenRepository.PurgeExpired")+ defer span.End()++ deleted, err := r.db.PasswordResetTokens.Delete().+ Where(passwordresettokens.Or(+ passwordresettokens.ExpiresAtLTE(time.Now()),+ passwordresettokens.UsedAtNotNil(),+ )).+ Exec(ctx)+ if err != nil {+ recordSpanError(span, err)+ return 0, err+ }+ span.SetAttributes(attribute.Int("tokens.deleted.count", deleted))+ return deleted, nil+}diff --git a/backend/internal/data/repo/repo_password_reset_test.go b/backend/internal/data/repo/repo_password_reset_test.gonew file mode 100644index 00000000..f456fd43--- /dev/null+++ b/backend/internal/data/repo/repo_password_reset_test.go@@ -0,0 +1,57 @@+package repo++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/passwordresettokens"+)++// TestPasswordResetTokens_AtomicClaim_RejectsExpired exercises the+// defense-in-depth expiry predicate on the atomic UPDATE inside MarkUsed and+// ConsumeAndChangePassword. Service callers normally filter expired tokens+// via GetValidByHash before reaching the claim, but if the token expires in+// the gap between the lookup and the claim, the UPDATE must still refuse to+// burn it.+func TestPasswordResetTokens_AtomicClaim_RejectsExpired(t *testing.T) {+ ctx := context.Background()++ // Create a token that's already expired by the time we try to claim it.+ tok, err := tRepos.PasswordResetTokens.Create(ctx, tUser.ID, []byte("hash-1-claim-test"), time.Now().Add(-time.Minute))+ require.NoError(t, err)++ err = tRepos.PasswordResetTokens.MarkUsed(ctx, tok.ID, time.Now())+ require.ErrorIs(t, err, ErrPasswordResetTokenAlreadyClaimed,+ "MarkUsed must refuse to burn an expired token even when used_at is still NULL")++ // Sanity: the row still has used_at = NULL, since the conditional UPDATE+ // matched zero rows.+ row, err := tClient.PasswordResetTokens.Query().+ Where(passwordresettokens.ID(tok.ID)).+ Only(ctx)+ require.NoError(t, err)+ assert.Nil(t, row.UsedAt, "used_at must remain NULL when the claim is rejected for expiry")+}++func TestPasswordResetTokens_ConsumeAndChangePassword_RejectsExpired(t *testing.T) {+ ctx := context.Background()++ tok, err := tRepos.PasswordResetTokens.Create(ctx, tUser.ID, []byte("hash-2-consume-test"), time.Now().Add(-time.Minute))+ require.NoError(t, err)++ originalHash, err := tRepos.Users.GetOneID(ctx, tUser.ID)+ require.NoError(t, err)++ err = tRepos.PasswordResetTokens.ConsumeAndChangePassword(ctx, tok.ID, tUser.ID, "new-hash-should-not-stick")+ require.ErrorIs(t, err, ErrPasswordResetTokenAlreadyClaimed)++ // The user's password must NOT have changed — the whole tx should have+ // rolled back when the conditional UPDATE matched zero rows.+ after, err := tRepos.Users.GetOneID(ctx, tUser.ID)+ require.NoError(t, err)+ assert.Equal(t, originalHash.PasswordHash, after.PasswordHash,+ "password must be unchanged when the token claim is rejected")+}diff --git a/backend/internal/data/repo/repo_tokens.go b/backend/internal/data/repo/repo_tokens.goindex b407f034..1b22eae8 100644--- a/backend/internal/data/repo/repo_tokens.go+++ b/backend/internal/data/repo/repo_tokens.go@@ -9,6 +9,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/data/ent""github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles""github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user""github.com/sysadminsmedia/homebox/backend/pkgs/hasher""github.com/sysadminsmedia/homebox/backend/pkgs/set""go.opentelemetry.io/otel/attribute"@@ -144,6 +145,25 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT}, nil}+// DeleteAllByUser revokes every session token for the given user. Called after+// a password reset so any session held by the attacker (or by the user on a+// shared device) is killed at the same moment the password changes.+func (r *TokenRepository) DeleteAllByUser(ctx context.Context, userID uuid.UUID) (int, error) {+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteAllByUser",+ trace.WithAttributes(attribute.String("user.id", userID.String())))+ defer span.End()++ deleted, err := r.db.AuthTokens.Delete().+ Where(authtokens.HasUserWith(user.ID(userID))).+ Exec(ctx)+ if err != nil {+ recordSpanError(span, err)+ return 0, err+ }+ span.SetAttributes(attribute.Int("tokens.deleted.count", deleted))+ return deleted, nil+}+// DeleteToken remove a single token from the database - equivalent to revoke or logoutfunc (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteToken",diff --git a/backend/internal/data/repo/repos_all.go b/backend/internal/data/repo/repos_all.goindex b28881c6..0c4d367d 100644--- a/backend/internal/data/repo/repos_all.go+++ b/backend/internal/data/repo/repos_all.go@@ -9,32 +9,34 @@ import (// AllRepos is a container for all the repository interfacestype AllRepos struct {- Users *UserRepository- AuthTokens *TokenRepository- APIKeys *APIKeyRepository- Groups *GroupRepository- Entities *EntityRepository- EntityTypes *EntityTypeRepository- EntityTemplates *EntityTemplatesRepository- Tags *TagRepository- Attachments *AttachmentRepo- MaintEntry *MaintenanceEntryRepository- Notifiers *NotifierRepository+ Users *UserRepository+ AuthTokens *TokenRepository+ PasswordResetTokens *PasswordResetTokenRepository+ APIKeys *APIKeyRepository+ Groups *GroupRepository+ Entities *EntityRepository+ EntityTypes *EntityTypeRepository+ EntityTemplates *EntityTemplatesRepository+ Tags *TagRepository+ Attachments *AttachmentRepo+ MaintEntry *MaintenanceEntryRepository+ Notifiers *NotifierRepository}func New(db *ent.Client, bus *eventbus.EventBus, storage config.Storage, pubSubConn string, thumbnail config.Thumbnail) *AllRepos {attachments := &AttachmentRepo{db, storage, pubSubConn, thumbnail}return &AllRepos{- Users: &UserRepository{db},- AuthTokens: &TokenRepository{db},- APIKeys: NewAPIKeyRepository(db),- Groups: NewGroupRepository(db),- Entities: &EntityRepository{db, bus, attachments},- EntityTypes: &EntityTypeRepository{db, bus},- EntityTemplates: &EntityTemplatesRepository{db, bus},- Tags: &TagRepository{db, bus},- Attachments: attachments,- MaintEntry: &MaintenanceEntryRepository{db},- Notifiers: NewNotifierRepository(db),+ Users: &UserRepository{db},+ AuthTokens: &TokenRepository{db},+ PasswordResetTokens: &PasswordResetTokenRepository{db},+ APIKeys: NewAPIKeyRepository(db),+ Groups: NewGroupRepository(db),+ Entities: &EntityRepository{db, bus, attachments},+ EntityTypes: &EntityTypeRepository{db, bus},+ EntityTemplates: &EntityTemplatesRepository{db, bus},+ Tags: &TagRepository{db, bus},+ Attachments: attachments,+ MaintEntry: &MaintenanceEntryRepository{db},+ Notifiers: NewNotifierRepository(db),}}diff --git a/backend/internal/sys/validate/notifier_url_test.go b/backend/internal/sys/validate/notifier_url_test.goindex 110f5f3b..e3e09358 100644--- a/backend/internal/sys/validate/notifier_url_test.go+++ b/backend/internal/sys/validate/notifier_url_test.go@@ -6,6 +6,13 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/sys/config")+// Repeated fixture values used across many test cases.+const (+ cidrPrivate24 = "192.168.1.0/24"+ urlGenericIPv6Local = "generic://http://[fd00::1]/webhook"+ urlGenericIPv4Local = "generic://http://192.168.1.100/webhook"+)+func TestValidateNotifierURL(t *testing.T) {tests := []struct {name string@@ -119,7 +126,7 @@ func TestValidateNotifierURL(t *testing.T) {name: "allow list permits private IP",url: "generic://http://192.168.1.1/webhook",config: config.NotifierConf{- AllowNets: []string{"192.168.1.0/24"},+ AllowNets: []string{cidrPrivate24},BlockLocalNets: true,},expectError: false,@@ -128,7 +135,7 @@ func TestValidateNotifierURL(t *testing.T) {name: "allow list blocks non-matching IP",url: "generic://http://10.0.0.1/webhook",config: config.NotifierConf{- AllowNets: []string{"192.168.1.0/24"},+ AllowNets: []string{cidrPrivate24},},expectError: true,},@@ -144,7 +151,7 @@ func TestValidateNotifierURL(t *testing.T) {name: "block_nets blocks specific network",url: "generic://http://192.168.1.1/webhook",config: config.NotifierConf{- BlockNets: []string{"192.168.1.0/24"},+ BlockNets: []string{cidrPrivate24},},expectError: true,},@@ -152,7 +159,7 @@ func TestValidateNotifierURL(t *testing.T) {name: "block_nets allows non-matching network",url: "generic://http://10.0.0.1/webhook",config: config.NotifierConf{- BlockNets: []string{"192.168.1.0/24"},+ BlockNets: []string{cidrPrivate24},},expectError: false,},@@ -176,8 +183,8 @@ func TestValidateNotifierURL(t *testing.T) {name: "allow_nets takes precedence over block_nets",url: "generic://http://192.168.1.1/webhook",config: config.NotifierConf{- AllowNets: []string{"192.168.1.0/24"},- BlockNets: []string{"192.168.1.0/24"},+ AllowNets: []string{cidrPrivate24},+ BlockNets: []string{cidrPrivate24},},expectError: false,},@@ -200,7 +207,7 @@ func TestValidateNotifierURL(t *testing.T) {},{name: "ipv6_ula_blocked_by_bogon_nets",- url: "generic://http://[fd00::1]/webhook",+ url: urlGenericIPv6Local,config: config.NotifierConf{BlockBogonNets: true,},@@ -208,7 +215,7 @@ func TestValidateNotifierURL(t *testing.T) {},{name: "ipv6_ula_allowed_when_bogon_nets_not_blocked",- url: "generic://http://[fd00::1]/webhook",+ url: urlGenericIPv6Local,config: config.NotifierConf{BlockBogonNets: false,},@@ -216,7 +223,7 @@ func TestValidateNotifierURL(t *testing.T) {},{name: "ipv6_ula_allowed_via_allow_nets",- url: "generic://http://[fd00::1]/webhook",+ url: urlGenericIPv6Local,config: config.NotifierConf{AllowNets: []string{"fd00::/8"},BlockBogonNets: true,@@ -273,7 +280,7 @@ func TestValidateNotifierURL(t *testing.T) {},{name: "ipv6_ula_blocked_by_local_nets",- url: "generic://http://[fd00::1]/webhook",+ url: urlGenericIPv6Local,config: config.NotifierConf{BlockLocalNets: true,},@@ -281,7 +288,7 @@ func TestValidateNotifierURL(t *testing.T) {},{name: "ipv6_ula_allowed_when_local_nets_not_blocked",- url: "generic://http://[fd00::1]/webhook",+ url: urlGenericIPv6Local,config: config.NotifierConf{BlockLocalNets: false,},@@ -392,11 +399,11 @@ func TestValidateNotifierURL_InvalidCIDR_AllowNets(t *testing.T) {}{{name: "invalid CIDR in AllowNets is skipped",- url: "generic://http://192.168.1.100/webhook",+ url: urlGenericIPv4Local,config: config.NotifierConf{AllowNets: []string{- "invalid-cidr", // Invalid - should be logged and skipped- "192.168.1.0/24", // Valid - should match+ "invalid-cidr", // Invalid - should be logged and skipped+ cidrPrivate24, // Valid - should match},},expectError: false,@@ -404,7 +411,7 @@ func TestValidateNotifierURL_InvalidCIDR_AllowNets(t *testing.T) {},{name: "all CIDRs invalid in AllowNets",- url: "generic://http://192.168.1.100/webhook",+ url: urlGenericIPv4Local,config: config.NotifierConf{AllowNets: []string{"invalid-cidr-1",@@ -454,7 +461,7 @@ func TestValidateNotifierURL_InvalidCIDR_BlockNets(t *testing.T) {}{{name: "invalid CIDR in BlockNets is skipped",- url: "generic://http://192.168.1.100/webhook",+ url: urlGenericIPv4Local,config: config.NotifierConf{BlockNets: []string{"invalid-cidr", // Invalid - should be logged and skipped@@ -466,11 +473,11 @@ func TestValidateNotifierURL_InvalidCIDR_BlockNets(t *testing.T) {},{name: "invalid CIDR doesn't prevent valid blocking",- url: "generic://http://192.168.1.100/webhook",+ url: urlGenericIPv4Local,config: config.NotifierConf{BlockNets: []string{"not-a-cidr",- "192.168.1.0/24", // Valid - should block+ cidrPrivate24, // Valid - should block"also-invalid",},},@@ -479,7 +486,7 @@ func TestValidateNotifierURL_InvalidCIDR_BlockNets(t *testing.T) {},{name: "all CIDRs invalid in BlockNets",- url: "generic://http://192.168.1.100/webhook",+ url: urlGenericIPv4Local,config: config.NotifierConf{BlockNets: []string{"invalid-1",diff --git a/backend/pkgs/hasher/token_test.go b/backend/pkgs/hasher/token_test.goindex a48e0212..eb5e0efc 100644--- a/backend/pkgs/hasher/token_test.go+++ b/backend/pkgs/hasher/token_test.go@@ -10,7 +10,7 @@ import (const ITERATIONS = 200-func init() {+func init() { // nolint:gochecknoinits// Tests need a pepper installed for HashAPIKey/GenerateAPIKey paths.SetAPIKeyPepper([]byte("test-pepper-not-for-production-use-only"))}diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.jsonindex f3a2ab32..d5a19e3d 100644--- a/docs/public/api/openapi-3.0.json+++ b/docs/public/api/openapi-3.0.json@@ -1548,33 +1548,6 @@}}}- },- "post": {- "security": [- {- "Bearer": []- }- ],- "tags": [- "Group"- ],- "summary": "Add User to Group",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/v1.GroupMemberAdd"- }- }- },- "description": "User ID",- "required": true- },- "responses": {- "204": {- "description": "No Content"- }- }}},"/v1/groups/members/{user_id}": {@@ -2682,6 +2655,61 @@}}},+ "/v1/users/forgot-password": {+ "post": {+ "description": "Sends a password reset email if the address is associated with a local account.\nAlways returns 204 on success to avoid leaking whether the email is registered.",+ "tags": [+ "Authentication"+ ],+ "summary": "Request Password Reset",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/v1.ForgotPasswordRequest"+ }+ }+ },+ "description": "Email",+ "required": true+ },+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "missing or invalid request body, or empty email field",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/v1/users/login": {"post": {"tags": [@@ -2845,6 +2873,61 @@}}},+ "/v1/users/reset-password": {+ "post": {+ "description": "Consumes a single-use reset token and changes the user's password.\nOn success, all existing sessions for the user are revoked.",+ "tags": [+ "Authentication"+ ],+ "summary": "Reset Password",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/v1.ResetPasswordRequest"+ }+ }+ },+ "description": "Token + new password",+ "required": true+ },+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "content": {+ "application/json": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/v1/users/self": {"get": {"security": [@@ -3922,6 +4005,13 @@"$ref": "#/components/schemas/ent.Tag"}},+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.UserGroup"+ }+ },"users": {"description": "Users holds the value of the users edge.","type": "array",@@ -4108,6 +4198,59 @@}}},+ "ent.PasswordResetTokens": {+ "type": "object",+ "properties": {+ "created_at": {+ "description": "CreatedAt holds the value of the \"created_at\" field.",+ "type": "string"+ },+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the PasswordResetTokensQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.PasswordResetTokensEdges"+ }+ ]+ },+ "expires_at": {+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",+ "type": "string"+ },+ "id": {+ "description": "ID of the ent.",+ "type": "string"+ },+ "token": {+ "description": "Token holds the value of the \"token\" field.",+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "updated_at": {+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",+ "type": "string"+ },+ "used_at": {+ "description": "UsedAt holds the value of the \"used_at\" field.",+ "type": "string"+ }+ }+ },+ "ent.PasswordResetTokensEdges": {+ "type": "object",+ "properties": {+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.User"+ }+ ]+ }+ }+ },"ent.Tag": {"type": "object","properties": {@@ -4301,14 +4444,6 @@"description": "OidcSubject holds the value of the \"oidc_subject\" field.","type": "string"},- "role": {- "description": "Role holds the value of the \"role\" field.",- "allOf": [- {- "$ref": "#/components/schemas/user.Role"- }- ]- },"settings": {"description": "Settings holds the value of the \"settings\" field.","type": "object",@@ -4354,6 +4489,70 @@"items": {"$ref": "#/components/schemas/ent.Notifier"}+ },+ "password_reset_tokens": {+ "description": "PasswordResetTokens holds the value of the password_reset_tokens edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.PasswordResetTokens"+ }+ },+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ent.UserGroup"+ }+ }+ }+ },+ "ent.UserGroup": {+ "type": "object",+ "properties": {+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserGroupQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.UserGroupEdges"+ }+ ]+ },+ "group_id": {+ "description": "GroupID holds the value of the \"group_id\" field.",+ "type": "string"+ },+ "role": {+ "description": "Role holds the value of the \"role\" field.",+ "allOf": [+ {+ "$ref": "#/components/schemas/usergroup.Role"+ }+ ]+ },+ "user_id": {+ "description": "UserID holds the value of the \"user_id\" field.",+ "type": "string"+ }+ }+ },+ "ent.UserGroupEdges": {+ "type": "object",+ "properties": {+ "group": {+ "description": "Group holds the value of the group edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.Group"+ }+ ]+ },+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/components/schemas/ent.User"+ }+ ]}}},@@ -5851,9 +6050,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"isSuperuser": {"type": "boolean"},@@ -5877,9 +6073,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"name": {"type": "string"}@@ -5976,7 +6169,7 @@"TypeTime"]},- "user.Role": {+ "usergroup.Role": {"type": "string","enum": ["user",@@ -6104,6 +6297,18 @@}}},+ "v1.ForgotPasswordRequest": {+ "type": "object",+ "required": [+ "email"+ ],+ "properties": {+ "email": {+ "type": "string",+ "example": "[email protected]"+ }+ }+ },"v1.GroupAcceptInvitationResponse": {"type": "object","properties": {@@ -6148,17 +6353,6 @@}}},- "v1.GroupMemberAdd": {- "type": "object",- "required": [- "userId"- ],- "properties": {- "userId": {- "type": "string"- }- }- },"v1.LoginForm": {"type": "object","properties": {@@ -6192,6 +6386,23 @@}}},+ "v1.ResetPasswordRequest": {+ "type": "object",+ "required": [+ "password",+ "token"+ ],+ "properties": {+ "password": {+ "type": "string",+ "minLength": 6+ },+ "token": {+ "type": "string",+ "minLength": 20+ }+ }+ },"v1.TelemetryStatus": {"type": "object","properties": {diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yamlindex 868713ae..33db3b0a 100644--- a/docs/public/api/openapi-3.0.yaml+++ b/docs/public/api/openapi-3.0.yaml@@ -923,22 +923,6 @@ paths:type: arrayitems:$ref: "#/components/schemas/repo.UserSummary"- post:- security:- - Bearer: []- tags:- - Group- summary: Add User to Group- requestBody:- content:- application/json:- schema:- $ref: "#/components/schemas/v1.GroupMemberAdd"- description: User ID- required: true- responses:- "204":- description: No Content"/v1/groups/members/{user_id}":delete:security:@@ -1588,6 +1572,44 @@ paths:responses:"204":description: No Content+ /v1/users/forgot-password:+ post:+ description: >-+ Sends a password reset email if the address is associated with a local+ account.++ Always returns 204 on success to avoid leaking whether the email is registered.+ tags:+ - Authentication+ summary: Request Password Reset+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/v1.ForgotPasswordRequest"+ description: Email+ required: true+ responses:+ "204":+ description: No Content+ "400":+ description: missing or invalid request body, or empty email field+ content:+ application/json:+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ content:+ application/json:+ schema:+ type: string+ "500":+ description: internal error while processing the request+ content:+ application/json:+ schema:+ type: string/v1/users/login:post:tags:@@ -1691,6 +1713,43 @@ paths:application/json:schema:type: string+ /v1/users/reset-password:+ post:+ description: |-+ Consumes a single-use reset token and changes the user's password.+ On success, all existing sessions for the user are revoked.+ tags:+ - Authentication+ summary: Reset Password+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/v1.ResetPasswordRequest"+ description: Token + new password+ required: true+ responses:+ "204":+ description: No Content+ "400":+ description: invalid request body, password shorter than the minimum length, or+ token that is invalid / expired / already used+ content:+ application/json:+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ content:+ application/json:+ schema:+ type: string+ "500":+ description: internal error while processing the request+ content:+ application/json:+ schema:+ type: string/v1/users/self:get:security:@@ -2409,6 +2468,11 @@ components:type: arrayitems:$ref: "#/components/schemas/ent.Tag"+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.UserGroup"users:description: Users holds the value of the users edge.type: array@@ -2537,6 +2601,43 @@ components:description: User holds the value of the user edge.allOf:- $ref: "#/components/schemas/ent.User"+ ent.PasswordResetTokens:+ type: object+ properties:+ created_at:+ description: CreatedAt holds the value of the "created_at" field.+ type: string+ edges:+ description: >-+ Edges holds the relations/edges for other nodes in the graph.++ The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ allOf:+ - $ref: "#/components/schemas/ent.PasswordResetTokensEdges"+ expires_at:+ description: ExpiresAt holds the value of the "expires_at" field.+ type: string+ id:+ description: ID of the ent.+ type: string+ token:+ description: Token holds the value of the "token" field.+ type: array+ items:+ type: integer+ updated_at:+ description: UpdatedAt holds the value of the "updated_at" field.+ type: string+ used_at:+ description: UsedAt holds the value of the "used_at" field.+ type: string+ ent.PasswordResetTokensEdges:+ type: object+ properties:+ user:+ description: User holds the value of the user edge.+ allOf:+ - $ref: "#/components/schemas/ent.User"ent.Tag:type: objectproperties:@@ -2674,10 +2775,6 @@ components:oidc_subject:description: OidcSubject holds the value of the "oidc_subject" field.type: string- role:- description: Role holds the value of the "role" field.- allOf:- - $ref: "#/components/schemas/user.Role"settings:description: Settings holds the value of the "settings" field.type: object@@ -2711,6 +2808,48 @@ components:type: arrayitems:$ref: "#/components/schemas/ent.Notifier"+ password_reset_tokens:+ description: PasswordResetTokens holds the value of the password_reset_tokens+ edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.PasswordResetTokens"+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ type: array+ items:+ $ref: "#/components/schemas/ent.UserGroup"+ ent.UserGroup:+ type: object+ properties:+ edges:+ description: >-+ Edges holds the relations/edges for other nodes in the graph.++ The values are being populated by the UserGroupQuery when eager-loading is set.+ allOf:+ - $ref: "#/components/schemas/ent.UserGroupEdges"+ group_id:+ description: GroupID holds the value of the "group_id" field.+ type: string+ role:+ description: Role holds the value of the "role" field.+ allOf:+ - $ref: "#/components/schemas/usergroup.Role"+ user_id:+ description: UserID holds the value of the "user_id" field.+ type: string+ ent.UserGroupEdges:+ type: object+ properties:+ group:+ description: Group holds the value of the group edge.+ allOf:+ - $ref: "#/components/schemas/ent.Group"+ user:+ description: User holds the value of the user edge.+ allOf:+ - $ref: "#/components/schemas/ent.User"entityfield.Type:type: stringenum:@@ -3734,8 +3873,6 @@ components:type: stringid:type: string- isOwner:- type: booleanisSuperuser:type: booleanname:@@ -3751,8 +3888,6 @@ components:type: stringid:type: string- isOwner:- type: booleanname:type: stringrepo.UserUpdate:@@ -3816,7 +3951,7 @@ components:- TypeNumber- TypeBoolean- TypeTime- user.Role:+ usergroup.Role:type: stringenum:- user@@ -3902,6 +4037,14 @@ components:type: arrayitems:type: string+ v1.ForgotPasswordRequest:+ type: object+ required:+ properties:+ email:+ type: string+ example: [email protected]v1.GroupAcceptInvitationResponse:type: objectproperties:@@ -3931,13 +4074,6 @@ components:type: integermaximum: 100minimum: 1- v1.GroupMemberAdd:- type: object- required:- - userId- properties:- userId:- type: stringv1.LoginForm:type: objectproperties:@@ -3960,6 +4096,18 @@ components:type: stringenabled:type: boolean+ v1.ResetPasswordRequest:+ type: object+ required:+ - password+ - token+ properties:+ password:+ type: string+ minLength: 6+ token:+ type: string+ minLength: 20v1.TelemetryStatus:type: objectproperties:diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.jsonindex c6b0d506..0852613e 100644--- a/docs/public/api/swagger-2.0.json+++ b/docs/public/api/swagger-2.0.json@@ -1436,36 +1436,6 @@}}}- },- "post": {- "security": [- {- "Bearer": []- }- ],- "produces": [- "application/json"- ],- "tags": [- "Group"- ],- "summary": "Add User to Group",- "parameters": [- {- "description": "User ID",- "name": "payload",- "in": "body",- "required": true,- "schema": {- "$ref": "#/definitions/v1.GroupMemberAdd"- }- }- ],- "responses": {- "204": {- "description": "No Content"- }- }}},"/v1/groups/members/{user_id}": {@@ -2502,6 +2472,55 @@}}},+ "/v1/users/forgot-password": {+ "post": {+ "description": "Sends a password reset email if the address is associated with a local account.\nAlways returns 204 on success to avoid leaking whether the email is registered.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Request Password Reset",+ "parameters": [+ {+ "description": "Email",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ForgotPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "missing or invalid request body, or empty email field",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/login": {"post": {"consumes": [@@ -2657,6 +2676,55 @@}}},+ "/v1/users/reset-password": {+ "post": {+ "description": "Consumes a single-use reset token and changes the user's password.\nOn success, all existing sessions for the user are revoked.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Authentication"+ ],+ "summary": "Reset Password",+ "parameters": [+ {+ "description": "Token + new password",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/v1.ResetPasswordRequest"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "No Content"+ },+ "400": {+ "description": "invalid request body, password shorter than the minimum length, or token that is invalid / expired / already used",+ "schema": {+ "type": "string"+ }+ },+ "403": {+ "description": "demo mode is enabled or local login is disabled",+ "schema": {+ "type": "string"+ }+ },+ "500": {+ "description": "internal error while processing the request",+ "schema": {+ "type": "string"+ }+ }+ }+ }+ },"/v1/users/self": {"get": {"security": [@@ -3715,6 +3783,13 @@"$ref": "#/definitions/ent.Tag"}},+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ },"users": {"description": "Users holds the value of the users edge.","type": "array",@@ -3901,6 +3976,59 @@}}},+ "ent.PasswordResetTokens": {+ "type": "object",+ "properties": {+ "created_at": {+ "description": "CreatedAt holds the value of the \"created_at\" field.",+ "type": "string"+ },+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the PasswordResetTokensQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.PasswordResetTokensEdges"+ }+ ]+ },+ "expires_at": {+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",+ "type": "string"+ },+ "id": {+ "description": "ID of the ent.",+ "type": "string"+ },+ "token": {+ "description": "Token holds the value of the \"token\" field.",+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "updated_at": {+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",+ "type": "string"+ },+ "used_at": {+ "description": "UsedAt holds the value of the \"used_at\" field.",+ "type": "string"+ }+ }+ },+ "ent.PasswordResetTokensEdges": {+ "type": "object",+ "properties": {+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]+ }+ }+ },"ent.Tag": {"type": "object","properties": {@@ -4094,14 +4222,6 @@"description": "OidcSubject holds the value of the \"oidc_subject\" field.","type": "string"},- "role": {- "description": "Role holds the value of the \"role\" field.",- "allOf": [- {- "$ref": "#/definitions/user.Role"- }- ]- },"settings": {"description": "Settings holds the value of the \"settings\" field.","type": "object",@@ -4147,6 +4267,70 @@"items": {"$ref": "#/definitions/ent.Notifier"}+ },+ "password_reset_tokens": {+ "description": "PasswordResetTokens holds the value of the password_reset_tokens edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.PasswordResetTokens"+ }+ },+ "user_groups": {+ "description": "UserGroups holds the value of the user_groups edge.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/ent.UserGroup"+ }+ }+ }+ },+ "ent.UserGroup": {+ "type": "object",+ "properties": {+ "edges": {+ "description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserGroupQuery when eager-loading is set.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.UserGroupEdges"+ }+ ]+ },+ "group_id": {+ "description": "GroupID holds the value of the \"group_id\" field.",+ "type": "string"+ },+ "role": {+ "description": "Role holds the value of the \"role\" field.",+ "allOf": [+ {+ "$ref": "#/definitions/usergroup.Role"+ }+ ]+ },+ "user_id": {+ "description": "UserID holds the value of the \"user_id\" field.",+ "type": "string"+ }+ }+ },+ "ent.UserGroupEdges": {+ "type": "object",+ "properties": {+ "group": {+ "description": "Group holds the value of the group edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.Group"+ }+ ]+ },+ "user": {+ "description": "User holds the value of the user edge.",+ "allOf": [+ {+ "$ref": "#/definitions/ent.User"+ }+ ]}}},@@ -5644,9 +5828,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"isSuperuser": {"type": "boolean"},@@ -5670,9 +5851,6 @@"id": {"type": "string"},- "isOwner": {- "type": "boolean"- },"name": {"type": "string"}@@ -5769,7 +5947,7 @@"TypeTime"]},- "user.Role": {+ "usergroup.Role": {"type": "string","enum": ["user",@@ -5897,6 +6075,18 @@}}},+ "v1.ForgotPasswordRequest": {+ "type": "object",+ "required": [+ "email"+ ],+ "properties": {+ "email": {+ "type": "string",+ "example": "[email protected]"+ }+ }+ },"v1.GroupAcceptInvitationResponse": {"type": "object","properties": {@@ -5941,17 +6131,6 @@}}},- "v1.GroupMemberAdd": {- "type": "object",- "required": [- "userId"- ],- "properties": {- "userId": {- "type": "string"- }- }- },"v1.LoginForm": {"type": "object","properties": {@@ -5985,6 +6164,23 @@}}},+ "v1.ResetPasswordRequest": {+ "type": "object",+ "required": [+ "password",+ "token"+ ],+ "properties": {+ "password": {+ "type": "string",+ "minLength": 6+ },+ "token": {+ "type": "string",+ "minLength": 20+ }+ }+ },"v1.TelemetryStatus": {"type": "object","properties": {diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yamlindex decc84da..b9e8b30c 100644--- a/docs/public/api/swagger-2.0.yaml+++ b/docs/public/api/swagger-2.0.yaml@@ -546,6 +546,11 @@ definitions:items:$ref: '#/definitions/ent.Tag'type: array+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ items:+ $ref: '#/definitions/ent.UserGroup'+ type: arrayusers:description: Users holds the value of the users edge.items:@@ -672,6 +677,42 @@ definitions:- $ref: '#/definitions/ent.User'description: User holds the value of the user edge.type: object+ ent.PasswordResetTokens:+ properties:+ created_at:+ description: CreatedAt holds the value of the "created_at" field.+ type: string+ edges:+ allOf:+ - $ref: '#/definitions/ent.PasswordResetTokensEdges'+ description: |-+ Edges holds the relations/edges for other nodes in the graph.+ The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ expires_at:+ description: ExpiresAt holds the value of the "expires_at" field.+ type: string+ id:+ description: ID of the ent.+ type: string+ token:+ description: Token holds the value of the "token" field.+ items:+ type: integer+ type: array+ updated_at:+ description: UpdatedAt holds the value of the "updated_at" field.+ type: string+ used_at:+ description: UsedAt holds the value of the "used_at" field.+ type: string+ type: object+ ent.PasswordResetTokensEdges:+ properties:+ user:+ allOf:+ - $ref: '#/definitions/ent.User'+ description: User holds the value of the user edge.+ type: objectent.Tag:properties:color:@@ -805,10 +846,6 @@ definitions:oidc_subject:description: OidcSubject holds the value of the "oidc_subject" field.type: string- role:- allOf:- - $ref: '#/definitions/user.Role'- description: Role holds the value of the "role" field.settings:additionalProperties: truedescription: Settings holds the value of the "settings" field.@@ -842,6 +879,47 @@ definitions:items:$ref: '#/definitions/ent.Notifier'type: array+ password_reset_tokens:+ description: PasswordResetTokens holds the value of the password_reset_tokens+ edge.+ items:+ $ref: '#/definitions/ent.PasswordResetTokens'+ type: array+ user_groups:+ description: UserGroups holds the value of the user_groups edge.+ items:+ $ref: '#/definitions/ent.UserGroup'+ type: array+ type: object+ ent.UserGroup:+ properties:+ edges:+ allOf:+ - $ref: '#/definitions/ent.UserGroupEdges'+ description: |-+ Edges holds the relations/edges for other nodes in the graph.+ The values are being populated by the UserGroupQuery when eager-loading is set.+ group_id:+ description: GroupID holds the value of the "group_id" field.+ type: string+ role:+ allOf:+ - $ref: '#/definitions/usergroup.Role'+ description: Role holds the value of the "role" field.+ user_id:+ description: UserID holds the value of the "user_id" field.+ type: string+ type: object+ ent.UserGroupEdges:+ properties:+ group:+ allOf:+ - $ref: '#/definitions/ent.Group'+ description: Group holds the value of the group edge.+ user:+ allOf:+ - $ref: '#/definitions/ent.User'+ description: User holds the value of the user edge.type: objectentityfield.Type:enum:@@ -1865,8 +1943,6 @@ definitions:type: arrayid:type: string- isOwner:- type: booleanisSuperuser:type: booleanname:@@ -1882,8 +1958,6 @@ definitions:type: stringid:type: string- isOwner:- type: booleanname:type: stringtype: object@@ -1948,7 +2022,7 @@ definitions:- TypeNumber- TypeBoolean- TypeTime- user.Role:+ usergroup.Role:enum:- user- user@@ -2034,6 +2108,14 @@ definitions:- name- parentIdtype: object+ v1.ForgotPasswordRequest:+ properties:+ email:+ example: [email protected]+ type: string+ required:+ type: objectv1.GroupAcceptInvitationResponse:properties:id:@@ -2063,13 +2145,6 @@ definitions:required:- usestype: object- v1.GroupMemberAdd:- properties:- userId:- type: string- required:- - userId- type: objectv1.LoginForm:properties:password:@@ -2092,6 +2167,18 @@ definitions:enabled:type: booleantype: object+ v1.ResetPasswordRequest:+ properties:+ password:+ minLength: 6+ type: string+ token:+ minLength: 20+ type: string+ required:+ - password+ - token+ type: objectv1.TelemetryStatus:properties:enabled:@@ -3020,24 +3107,6 @@ paths:summary: Get All Group Memberstags:- Group- post:- parameters:- - description: User ID- in: body- name: payload- required: true- schema:- $ref: '#/definitions/v1.GroupMemberAdd'- produces:- - application/json- responses:- "204":- description: No Content- security:- - Bearer: []- summary: Add User to Group- tags:- - Group/v1/groups/members/{user_id}:delete:parameters:@@ -3666,6 +3735,40 @@ paths:summary: Change Passwordtags:- User+ /v1/users/forgot-password:+ post:+ consumes:+ - application/json+ description: |-+ Sends a password reset email if the address is associated with a local account.+ Always returns 204 on success to avoid leaking whether the email is registered.+ parameters:+ - description: Email+ in: body+ name: payload+ required: true+ schema:+ $ref: '#/definitions/v1.ForgotPasswordRequest'+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "400":+ description: missing or invalid request body, or empty email field+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ schema:+ type: string+ "500":+ description: internal error while processing the request+ schema:+ type: string+ summary: Request Password Reset+ tags:+ - Authentication/v1/users/login:post:consumes:@@ -3765,6 +3868,41 @@ paths:summary: Register New Usertags:- User+ /v1/users/reset-password:+ post:+ consumes:+ - application/json+ description: |-+ Consumes a single-use reset token and changes the user's password.+ On success, all existing sessions for the user are revoked.+ parameters:+ - description: Token + new password+ in: body+ name: payload+ required: true+ schema:+ $ref: '#/definitions/v1.ResetPasswordRequest'+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ "400":+ description: invalid request body, password shorter than the minimum length,+ or token that is invalid / expired / already used+ schema:+ type: string+ "403":+ description: demo mode is enabled or local login is disabled+ schema:+ type: string+ "500":+ description: internal error while processing the request+ schema:+ type: string+ summary: Reset Password+ tags:+ - Authentication/v1/users/self:delete:produces:diff --git a/frontend/lib/api/public.ts b/frontend/lib/api/public.tsindex 513e4929..9124d2a8 100644--- a/frontend/lib/api/public.ts+++ b/frontend/lib/api/public.ts@@ -1,5 +1,12 @@import { BaseAPI, route } from "./base";-import type { APISummary, LoginForm, TokenResponse, UserRegistration } from "./types/data-contracts";+import type {+ APISummary,+ ForgotPasswordRequest,+ LoginForm,+ ResetPasswordRequest,+ TokenResponse,+ UserRegistration,+} from "./types/data-contracts";export type StatusResult = {health: boolean;@@ -27,4 +34,18 @@ export class PublicApi extends BaseAPI {public register(body: UserRegistration) {return this.http.post<UserRegistration, TokenResponse>({ url: route("/users/register"), body });}++ public forgotPassword(email: string) {+ return this.http.post<ForgotPasswordRequest, void>({+ url: route("/users/forgot-password"),+ body: { email },+ });+ }++ public resetPassword(token: string, password: string) {+ return this.http.post<ResetPasswordRequest, void>({+ url: route("/users/reset-password"),+ body: { token, password },+ });+ }}diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.tsindex 937db2c4..35b54fda 100644--- a/frontend/lib/api/types/data-contracts.ts+++ b/frontend/lib/api/types/data-contracts.ts@@ -11,7 +11,7 @@* ---------------------------------------------------------------*/-export enum UserRole {+export enum UsergroupRole {DefaultRole = "user",RoleUser = "user",RoleOwner = "owner",@@ -392,6 +392,8 @@ export interface EntGroupEdges {notifiers: EntNotifier[];/** Tags holds the value of the tags edge. */tags: EntTag[];+ /** UserGroups holds the value of the user_groups edge. */+ user_groups: EntUserGroup[];/** Users holds the value of the users edge. */users: EntUser[];}@@ -481,6 +483,31 @@ export interface EntNotifierEdges {user: EntUser;}+export interface EntPasswordResetTokens {+ /** CreatedAt holds the value of the "created_at" field. */+ created_at: string;+ /**+ * Edges holds the relations/edges for other nodes in the graph.+ * The values are being populated by the PasswordResetTokensQuery when eager-loading is set.+ */+ edges: EntPasswordResetTokensEdges;+ /** ExpiresAt holds the value of the "expires_at" field. */+ expires_at: string;+ /** ID of the ent. */+ id: string;+ /** Token holds the value of the "token" field. */+ token: number[];+ /** UpdatedAt holds the value of the "updated_at" field. */+ updated_at: string;+ /** UsedAt holds the value of the "used_at" field. */+ used_at: string;+}++export interface EntPasswordResetTokensEdges {+ /** User holds the value of the user edge. */+ user: EntUser;+}+export interface EntTag {/** Color holds the value of the "color" field. */color: string;@@ -571,8 +598,6 @@ export interface EntUser {oidc_issuer: string;/** OidcSubject holds the value of the "oidc_subject" field. */oidc_subject: string;- /** Role holds the value of the "role" field. */- role: UserRole;/** Settings holds the value of the "settings" field. */settings: Record<string, any>;/** Superuser holds the value of the "superuser" field. */@@ -590,6 +615,31 @@ export interface EntUserEdges {groups: EntGroup[];/** Notifiers holds the value of the notifiers edge. */notifiers: EntNotifier[];+ /** PasswordResetTokens holds the value of the password_reset_tokens edge. */+ password_reset_tokens: EntPasswordResetTokens[];+ /** UserGroups holds the value of the user_groups edge. */+ user_groups: EntUserGroup[];+}++export interface EntUserGroup {+ /**+ * Edges holds the relations/edges for other nodes in the graph.+ * The values are being populated by the UserGroupQuery when eager-loading is set.+ */+ edges: EntUserGroupEdges;+ /** GroupID holds the value of the "group_id" field. */+ group_id: string;+ /** Role holds the value of the "role" field. */+ role: UsergroupRole;+ /** UserID holds the value of the "user_id" field. */+ user_id: string;+}++export interface EntUserGroupEdges {+ /** Group holds the value of the group edge. */+ group: EntGroup;+ /** User holds the value of the user edge. */+ user: EntUser;}export interface APIKeyCreate {@@ -1146,7 +1196,6 @@ export interface UserOut {email: string;groupIds: string[];id: string;- isOwner: boolean;isSuperuser: boolean;name: string;oidcIssuer: string;@@ -1156,7 +1205,6 @@ export interface UserOut {export interface UserSummary {email: string;id: string;- isOwner: boolean;name: string;}@@ -1237,6 +1285,11 @@ export interface EntityTemplateCreateItemRequest {tagIds: string[];}+export interface ForgotPasswordRequest {+ /** @example "[email protected]" */+ email: string;+}+export interface GroupAcceptInvitationResponse {id: string;name: string;@@ -1258,10 +1311,6 @@ export interface GroupInvitationCreate {uses: number;}-export interface GroupMemberAdd {- userId: string;-}-export interface LoginForm {/** @example "admin" */password: string;@@ -1277,6 +1326,13 @@ export interface OIDCStatus {enabled: boolean;}+export interface ResetPasswordRequest {+ /** @minLength 6 */+ password: string;+ /** @minLength 20 */+ token: string;+}+export interface TelemetryStatus {enabled: boolean;}diff --git a/frontend/locales/en.json b/frontend/locales/en.jsonindex b04f5419..d2fb0ff4 100644--- a/frontend/locales/en.json+++ b/frontend/locales/en.json@@ -462,13 +462,25 @@"total_value": "Total Value"},"index": {+ "back_to_login": "Back to login","disabled_registration": "Registration Disabled","dont_join_group": "Don't want to join a group?",+ "forgot_password": "Forgot your password?",+ "forgot_password_check_email": "If that email is associated with an account, a reset link is on its way. The link expires in one hour.",+ "forgot_password_send": "Send reset link",+ "forgot_password_subtitle": "Enter the email for your account and we'll send you a link to reset your password.",+ "forgot_password_title": "Reset your password","joining_group": "You're Joining an Existing Group!","login": "Login","or": "or","register": "Register","remember_me": "Remember Me",+ "reset_password_invalid": "This reset link is invalid or has expired. Request a new one.",+ "reset_password_missing_token": "Missing reset token. Open the link from your email again, or request a new one.",+ "reset_password_set": "Set new password",+ "reset_password_subtitle": "Choose a new password for your account.",+ "reset_password_success": "Your password has been reset. Sign in with the new password.",+ "reset_password_title": "Reset your password","set_email": "What's your email?","set_name": "What's your name?","set_password": "Set your password",diff --git a/frontend/pages/forgot-password.vue b/frontend/pages/forgot-password.vuenew file mode 100644index 00000000..5f306bd6--- /dev/null+++ b/frontend/pages/forgot-password.vue@@ -0,0 +1,100 @@+<script setup lang="ts">+ import { useI18n } from "vue-i18n";+ import { toast } from "@/components/ui/sonner";+ import MdiEmailOutline from "~icons/mdi/email-outline";+ import MdiArrowLeft from "~icons/mdi/arrow-left";+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";+ import { Button } from "@/components/ui/button";+ import AppLogo from "~/components/App/Logo.vue";+ import FormTextField from "~/components/Form/TextField.vue";++ const { t } = useI18n();++ useHead({+ title: "HomeBox | " + t("index.forgot_password_title"),+ });++ definePageMeta({+ layout: "empty",+ });++ const api = usePublicApi();++ const email = ref("");+ const loading = ref(false);+ const submitted = ref(false);++ async function submit() {+ loading.value = true;+ const { error } = await api.forgotPassword(email.value.trim());+ loading.value = false;++ if (error) {+ // Server deliberately collapses configuration state and missing-account+ // cases into the same 204 — see HandleForgotPassword. So real errors+ // here are limited to rate limiting (429), demo mode (403), or network+ // failures, none of which we want to detail to an unauthenticated user.+ toast.error(t("index.toast.invalid_email"));+ return;+ }++ submitted.value = true;+ }+</script>++<template>+ <div class="flex min-h-screen flex-col items-center justify-center p-6">+ <div class="mb-6 flex items-center gap-2 text-3xl font-bold tracking-tight">+ HomeB+ <AppLogo class="-mb-2 w-10" />+ x+ </div>++ <Card class="md:w-[460px]">+ <CardHeader>+ <CardTitle class="flex items-center gap-2">+ <MdiEmailOutline class="size-6" />+ {{ $t("index.forgot_password_title") }}+ </CardTitle>+ </CardHeader>++ <CardContent>+ <template v-if="submitted">+ <p class="text-sm">{{ $t("index.forgot_password_check_email") }}</p>+ </template>+ <template v-else>+ <p class="mb-4 text-sm text-muted-foreground">{{ $t("index.forgot_password_subtitle") }}</p>+ <form id="forgot-password-form" @submit.prevent="submit">+ <FormTextField+ id="forgot-email"+ v-model="email"+ :label="$t('global.email')"+ type="email"+ name="email"+ autocomplete="username"+ :required="true"+ />+ </form>+ </template>+ </CardContent>++ <CardFooter class="flex flex-col gap-2">+ <Button+ v-if="!submitted"+ form="forgot-password-form"+ type="submit"+ class="w-full"+ :disabled="loading || !email"+ >+ {{ $t("index.forgot_password_send") }}+ </Button>+ <NuxtLink to="/" class="text-sm text-muted-foreground hover:underline">+ <span class="inline-flex items-center gap-1">+ <MdiArrowLeft class="size-4" />+ {{ $t("index.back_to_login") }}+ </span>+ </NuxtLink>+ </CardFooter>+ </Card>+ </div>+</template>diff --git a/frontend/pages/index.vue b/frontend/pages/index.vueindex 9a1f67f8..9c1c734c 100644--- a/frontend/pages/index.vue+++ b/frontend/pages/index.vue@@ -401,8 +401,13 @@autocomplete="current-password":required="true"/>- <div class="max-w-[140px]">- <FormCheckbox v-model="remember" :label="$t('index.remember_me')" />+ <div class="flex items-center justify-between">+ <div class="max-w-[140px]">+ <FormCheckbox v-model="remember" :label="$t('index.remember_me')" />+ </div>+ <NuxtLink to="/forgot-password" class="text-sm hover:underline">+ {{ $t("index.forgot_password") }}+ </NuxtLink></div></CardContent><CardFooter class="flex flex-col gap-2">diff --git a/frontend/pages/reset-password.vue b/frontend/pages/reset-password.vuenew file mode 100644index 00000000..94541478--- /dev/null+++ b/frontend/pages/reset-password.vue@@ -0,0 +1,112 @@+<script setup lang="ts">+ import { useI18n } from "vue-i18n";+ import { toast } from "@/components/ui/sonner";+ import MdiLockReset from "~icons/mdi/lock-reset";+ import MdiArrowLeft from "~icons/mdi/arrow-left";+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";+ import { Button } from "@/components/ui/button";+ import AppLogo from "~/components/App/Logo.vue";+ import FormPassword from "~/components/Form/Password.vue";+ import PasswordScore from "~/components/global/PasswordScore.vue";+ import { PASSWORD_MIN_LENGTH, PASSWORD_RULES } from "~/lib/passwords";++ const { t } = useI18n();++ useHead({+ title: "HomeBox | " + t("index.reset_password_title"),+ });++ definePageMeta({+ layout: "empty",+ });++ const route = useRoute();+ const router = useRouter();+ const api = usePublicApi();++ const token = computed(() => {+ const t = route.query.token;+ return typeof t === "string" ? t : "";+ });++ const password = ref("");+ const passwordValid = ref(false);+ const loading = ref(false);++ onMounted(() => {+ if (!token.value) {+ toast.error(t("index.reset_password_missing_token"));+ }+ });++ async function submit() {+ if (!token.value || !passwordValid.value) return;++ loading.value = true;+ const { error } = await api.resetPassword(token.value, password.value);+ loading.value = false;++ if (error) {+ // 400 means the token is invalid/expired/used; anything else is also+ // unactionable for the user. Show one message either way.+ toast.error(t("index.reset_password_invalid"));+ return;+ }++ toast.success(t("index.reset_password_success"));+ router.replace("/");+ }+</script>++<template>+ <div class="flex min-h-screen flex-col items-center justify-center p-6">+ <div class="mb-6 flex items-center gap-2 text-3xl font-bold tracking-tight">+ HomeB+ <AppLogo class="-mb-2 w-10" />+ x+ </div>++ <Card class="md:w-[460px]">+ <CardHeader>+ <CardTitle class="flex items-center gap-2">+ <MdiLockReset class="size-6" />+ {{ $t("index.reset_password_title") }}+ </CardTitle>+ </CardHeader>++ <CardContent>+ <p class="mb-4 text-sm text-muted-foreground">{{ $t("index.reset_password_subtitle") }}</p>+ <form id="reset-password-form" @submit.prevent="submit">+ <FormPassword+ id="reset-password-new"+ v-model="password"+ :label="$t('index.set_password')"+ name="new-password"+ autocomplete="new-password"+ :min-length="PASSWORD_MIN_LENGTH"+ :passwordrules="PASSWORD_RULES"+ :required="true"+ />+ <PasswordScore v-model:valid="passwordValid" :password="password" />+ </form>+ </CardContent>++ <CardFooter class="flex flex-col gap-2">+ <Button+ form="reset-password-form"+ type="submit"+ class="w-full"+ :disabled="loading || !passwordValid || !token"+ >+ {{ $t("index.reset_password_set") }}+ </Button>+ <NuxtLink to="/" class="text-sm text-muted-foreground hover:underline">+ <span class="inline-flex items-center gap-1">+ <MdiArrowLeft class="size-4" />+ {{ $t("index.back_to_login") }}+ </span>+ </NuxtLink>+ </CardFooter>+ </Card>+ </div>+</template>