Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

feat: API Key support

Matthew Kilgorefe0a18ba89de
diff --git a/backend/app/api/handlers/v1/v1_ctrl_api_keys.go b/backend/app/api/handlers/v1/v1_ctrl_api_keys.go
new file mode 100644
index 00000000..39785b8b
--- /dev/null
+++ b/backend/app/api/handlers/v1/v1_ctrl_api_keys.go
@@ -0,0 +1,60 @@
+package v1
+
+import (
+ "net/http"
+
+ "github.com/google/uuid"
+ "github.com/hay-kot/httpkit/errchain"
+ "github.com/sysadminsmedia/homebox/backend/internal/core/services"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
+)
+
+// HandleUserAPIKeysList godoc
+//
+// @Summary List API Keys
+// @Tags User
+// @Produce json
+// @Success 200 {object} []repo.APIKeyOut
+// @Router /v1/users/self/api-keys [GET]
+// @Security Bearer
+func (ctrl *V1Controller) HandleUserAPIKeysList() errchain.HandlerFunc {
+ fn := func(r *http.Request, _ struct{}) ([]repo.APIKeyOut, error) {
+ actor := services.UseUserCtx(r.Context())
+ return ctrl.svc.User.ListAPIKeys(r.Context(), actor.ID)
+ }
+ return adapters.Query(fn, http.StatusOK)
+}
+
+// HandleUserAPIKeyCreate godoc
+//
+// @Summary Create API Key
+// @Tags User
+// @Produce json
+// @Param payload body repo.APIKeyCreate true "API Key Data"
+// @Success 201 {object} repo.APIKeyCreatedOut
+// @Router /v1/users/self/api-keys [POST]
+// @Security Bearer
+func (ctrl *V1Controller) HandleUserAPIKeyCreate() errchain.HandlerFunc {
+ fn := func(r *http.Request, in repo.APIKeyCreate) (repo.APIKeyCreatedOut, error) {
+ actor := services.UseUserCtx(r.Context())
+ return ctrl.svc.User.CreateAPIKey(r.Context(), actor.ID, in)
+ }
+ return adapters.Action(fn, http.StatusCreated)
+}
+
+// HandleUserAPIKeyDelete godoc
+//
+// @Summary Delete API Key
+// @Tags User
+// @Param id path string true "API Key ID"
+// @Success 204
+// @Router /v1/users/self/api-keys/{id} [DELETE]
+// @Security Bearer
+func (ctrl *V1Controller) HandleUserAPIKeyDelete() errchain.HandlerFunc {
+ fn := func(r *http.Request, ID uuid.UUID) (any, error) {
+ actor := services.UseUserCtx(r.Context())
+ return nil, ctrl.svc.User.DeleteAPIKey(r.Context(), actor.ID, ID)
+ }
+ return adapters.CommandID("id", fn, http.StatusNoContent)
+}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_auth.go b/backend/app/api/handlers/v1/v1_ctrl_auth.go
index 77e65c12..89e2247e 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_auth.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_auth.go
@@ -161,6 +161,17 @@ func (ctrl *V1Controller) HandleAuthLogout() errchain.HandlerFunc {
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
}
+ // API keys are not session tokens — they live in their own table and
+ // are managed from the profile page. Returning 204 here would silently
+ // delete zero rows from auth_tokens and mislead the caller.
+ if services.IsAPIKeyAuth(spanCtx) {
+ span.SetAttributes(attribute.String("logout.outcome", "api_key_rejected"))
+ return validate.NewRequestError(
+ errors.New("API keys cannot be logged out; revoke them from the API keys page"),
+ http.StatusBadRequest,
+ )
+ }
+
err := ctrl.svc.User.Logout(spanCtx, token)
if err != nil {
recordCtrlSpanError(span, err)
@@ -194,6 +205,17 @@ func (ctrl *V1Controller) HandleAuthRefresh() errchain.HandlerFunc {
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
}
+ // API keys are long-lived and don't go through the session refresh
+ // flow. Reject the request with a clear error rather than the generic
+ // 401 RenewToken would otherwise produce.
+ if services.IsAPIKeyAuth(spanCtx) {
+ span.SetAttributes(attribute.String("refresh.outcome", "api_key_rejected"))
+ return validate.NewRequestError(
+ errors.New("API keys do not require refresh"),
+ http.StatusBadRequest,
+ )
+ }
+
newToken, err := ctrl.svc.User.RenewToken(spanCtx, requestToken)
if err != nil {
recordCtrlSpanError(span, err)
diff --git a/backend/app/api/handlers/v1/v1_ctrl_user.go b/backend/app/api/handlers/v1/v1_ctrl_user.go
index f8772d23..9794918c 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_user.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_user.go
@@ -1,6 +1,7 @@
package v1
import (
+ "errors"
"fmt"
"net/http"
@@ -84,18 +85,17 @@ func (ctrl *V1Controller) HandleUserSelf() errchain.HandlerFunc {
spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelf")
defer span.End()
- token := services.UseTokenCtx(spanCtx)
- span.SetAttributes(attribute.Bool("token.present", token != ""))
- usr, err := ctrl.svc.User.GetSelf(spanCtx, token)
- if usr.ID == uuid.Nil || err != nil {
- recordCtrlSpanError(span, err)
+ // The auth middleware has already loaded the user (handles both
+ // session tokens and API keys); just return what's in context.
+ usr := services.UseUserCtx(spanCtx)
+ if usr == nil || usr.ID == uuid.Nil {
span.SetAttributes(attribute.String("self.outcome", "lookup_failed"))
- log.Err(err).Msg("failed to get user")
- return validate.NewRequestError(err, http.StatusInternalServerError)
+ log.Err(errors.New("user context not found")).Msg("failed to get user")
+ return validate.NewRequestError(errors.New("user not found in context"), http.StatusInternalServerError)
}
span.SetAttributes(attribute.String("user.id", usr.ID.String()))
- return server.JSON(w, http.StatusOK, Wrap(usr))
+ return server.JSON(w, http.StatusOK, Wrap(*usr))
}
}
diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.go
index 7c6ea469..0570fb3c 100644
--- a/backend/app/api/middleware.go
+++ b/backend/app/api/middleware.go
@@ -11,11 +11,14 @@ import (
"sync"
"time"
+ "github.com/rs/zerolog/log"
v1 "github.com/sysadminsmedia/homebox/backend/app/api/handlers/v1"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/sys/config"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
+ "github.com/sysadminsmedia/homebox/backend/pkgs/set"
"github.com/google/uuid"
"github.com/hay-kot/httpkit/errchain"
@@ -73,10 +76,21 @@ func (a *app) mwRoles(rm RoleMode, required ...string) errchain.Middleware {
token := maybeToken.(string)
- roles, err := a.repos.AuthTokens.GetRoles(spanCtx, token)
- if err != nil {
- recordMwSpanError(span, err)
- return err
+ // API keys grant the same access as the owning user. They live
+ // outside the auth_roles table, so we synthesize the "user" role
+ // here rather than querying the DB.
+ var roles *set.Set[string]
+ if services.IsAPIKeyAuth(spanCtx) {
+ s := set.New("user")
+ roles = &s
+ span.SetAttributes(attribute.Bool("roles.api_key", true))
+ } else {
+ r, err := a.repos.AuthTokens.GetRoles(spanCtx, token)
+ if err != nil {
+ recordMwSpanError(span, err)
+ return err
+ }
+ roles = r
}
span.SetAttributes(attribute.Int("roles.actual.count", roles.Len()))
@@ -200,26 +214,58 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
r = r.WithContext(context.WithValue(spanCtx, hashedToken, requestToken))
usr, err := a.services.User.GetSelf(r.Context(), requestToken)
+ if err != nil && !ent.IsNotFound(err) {
+ recordMwSpanError(span, err)
+ span.SetAttributes(attribute.String("auth.outcome", "lookup_error"))
+ return err
+ }
+
+ isAPIKey := false
if err != nil {
- if ent.IsNotFound(err) {
+ // Session-token lookup missed. API keys are only accepted via the
+ // Authorization header — never via cookies or query params, since
+ // those paths leak credentials into logs, browser history, and
+ // referer headers. Reject without consulting the api_keys table.
+ if tokenSource != "bearer" {
span.SetAttributes(attribute.String("auth.outcome", "token_not_found"))
return validate.NewRequestError(errors.New("valid authorization token is required"), http.StatusUnauthorized)
}
- recordMwSpanError(span, err)
- span.SetAttributes(attribute.String("auth.outcome", "lookup_error"))
- return err
+ tokenHash := hasher.HashToken(requestToken)
+ keyUsr, keyID, keyErr := a.repos.APIKeys.GetUserFromToken(r.Context(), tokenHash)
+ if keyErr != nil {
+ if ent.IsNotFound(keyErr) {
+ span.SetAttributes(attribute.String("auth.outcome", "token_not_found"))
+ return validate.NewRequestError(errors.New("valid authorization token is required"), http.StatusUnauthorized)
+ }
+ recordMwSpanError(span, keyErr)
+ span.SetAttributes(attribute.String("auth.outcome", "lookup_error"))
+ return keyErr
+ }
+ usr = keyUsr
+ isAPIKey = true
+
+ // Best-effort last_used_at update; failure must not break the
+ // request, but we want it surfaced in logs.
+ if touchErr := a.repos.APIKeys.TouchLastUsed(r.Context(), keyID, time.Now()); touchErr != nil {
+ log.Warn().Err(touchErr).Str("api_key.id", keyID.String()).Msg("failed to update api key last_used_at")
+ }
}
span.SetAttributes(
attribute.String("auth.outcome", "authenticated"),
+ attribute.String("auth.method", map[bool]string{true: "api_key", false: "session"}[isAPIKey]),
attribute.String("user.id", usr.ID.String()),
attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
attribute.Int("user.groups.count", len(usr.GroupIDs)),
attribute.Bool("user.is_superuser", usr.IsSuperuser),
)
- r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))
+ ctxOut := services.SetUserCtx(r.Context(), &usr, requestToken)
+ if isAPIKey {
+ ctxOut = services.SetAPIKeyAuth(ctxOut)
+ }
+ r = r.WithContext(ctxOut)
return next.ServeHTTP(w, r)
})
}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index 4cbc9fdc..473470ff 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -112,6 +112,11 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Get("/users/refresh", chain.ToHandlerFunc(v1Ctrl.HandleAuthRefresh(), userMW...))
r.Put("/users/self/change-password", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfChangePassword(), userMW...))
+ // User API keys (static tokens that authenticate as the owning user)
+ r.Get("/users/self/api-keys", chain.ToHandlerFunc(v1Ctrl.HandleUserAPIKeysList(), userMW...))
+ r.Post("/users/self/api-keys", chain.ToHandlerFunc(v1Ctrl.HandleUserAPIKeyCreate(), userMW...))
+ r.Delete("/users/self/api-keys/{id}", chain.ToHandlerFunc(v1Ctrl.HandleUserAPIKeyDelete(), userMW...))
+
// Group management endpoints
r.Get("/groups/all", chain.ToHandlerFunc(v1Ctrl.HandleGroupsGetAll(), userMW...))
r.Post("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupCreate(), userMW...))
diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.go
index 4fd78299..d45a2d10 100644
--- a/backend/app/api/static/docs/docs.go
+++ b/backend/app/api/static/docs/docs.go
@@ -2760,6 +2760,93 @@ const docTemplate = `{
}
}
},
+ "/v1/users/self/api-keys": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "List API Keys",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.APIKeyOut"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Create API Key",
+ "parameters": [
+ {
+ "description": "API Key Data",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreate"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreatedOut"
+ }
+ }
+ }
+ }
+ },
+ "/v1/users/self/api-keys/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Delete API Key",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "API Key ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/users/self/settings": {
"get": {
"security": [
@@ -2902,6 +2989,60 @@ const docTemplate = `{
}
}
},
+ "ent.APIKey": {
+ "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 APIKeyQuery when eager-loading is set.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.APIKeyEdges"
+ }
+ ]
+ },
+ "expires_at": {
+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",
+ "type": "string"
+ },
+ "id": {
+ "description": "ID of the ent.",
+ "type": "string"
+ },
+ "last_used_at": {
+ "description": "LastUsedAt holds the value of the \"last_used_at\" field.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name holds the value of the \"name\" field.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",
+ "type": "string"
+ },
+ "user_id": {
+ "description": "UserID holds the value of the \"user_id\" field.",
+ "type": "string"
+ }
+ }
+ },
+ "ent.APIKeyEdges": {
+ "type": "object",
+ "properties": {
+ "user": {
+ "description": "User holds the value of the user edge.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.User"
+ }
+ ]
+ }
+ }
+ },
"ent.Attachment": {
"type": "object",
"properties": {
@@ -3982,6 +4123,13 @@ const docTemplate = `{
"ent.UserEdges": {
"type": "object",
"properties": {
+ "api_keys": {
+ "description": "APIKeys holds the value of the api_keys edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.APIKey"
+ }
+ },
"auth_tokens": {
"description": "AuthTokens holds the value of the auth_tokens edge.",
"type": "array",
@@ -4020,6 +4168,76 @@ const docTemplate = `{
"TypeTime"
]
},
+ "repo.APIKeyCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ }
+ }
+ },
+ "repo.APIKeyCreatedOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
+ "repo.APIKeyOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"repo.BarcodeProduct": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.json
index 6df20892..f3a2ab32 100644
--- a/backend/app/api/static/docs/openapi-3.json
+++ b/backend/app/api/static/docs/openapi-3.json
@@ -2944,6 +2944,97 @@
}
}
},
+ "/v1/users/self/api-keys": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "List API Keys",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.APIKeyOut"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Create API Key",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.APIKeyCreate"
+ }
+ }
+ },
+ "description": "API Key Data",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.APIKeyCreatedOut"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/v1/users/self/api-keys/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Delete API Key",
+ "parameters": [
+ {
+ "description": "API Key ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/users/self/settings": {
"get": {
"security": [
@@ -3102,6 +3193,60 @@
}
}
},
+ "ent.APIKey": {
+ "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 APIKeyQuery when eager-loading is set.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ent.APIKeyEdges"
+ }
+ ]
+ },
+ "expires_at": {
+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",
+ "type": "string"
+ },
+ "id": {
+ "description": "ID of the ent.",
+ "type": "string"
+ },
+ "last_used_at": {
+ "description": "LastUsedAt holds the value of the \"last_used_at\" field.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name holds the value of the \"name\" field.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",
+ "type": "string"
+ },
+ "user_id": {
+ "description": "UserID holds the value of the \"user_id\" field.",
+ "type": "string"
+ }
+ }
+ },
+ "ent.APIKeyEdges": {
+ "type": "object",
+ "properties": {
+ "user": {
+ "description": "User holds the value of the user edge.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ent.User"
+ }
+ ]
+ }
+ }
+ },
"ent.Attachment": {
"type": "object",
"properties": {
@@ -4182,6 +4327,13 @@
"ent.UserEdges": {
"type": "object",
"properties": {
+ "api_keys": {
+ "description": "APIKeys holds the value of the api_keys edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ent.APIKey"
+ }
+ },
"auth_tokens": {
"description": "AuthTokens holds the value of the auth_tokens edge.",
"type": "array",
@@ -4220,6 +4372,76 @@
"TypeTime"
]
},
+ "repo.APIKeyCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ }
+ }
+ },
+ "repo.APIKeyCreatedOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
+ "repo.APIKeyOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"repo.BarcodeProduct": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yaml
index 4c7fd14f..868713ae 100644
--- a/backend/app/api/static/docs/openapi-3.yaml
+++ b/backend/app/api/static/docs/openapi-3.yaml
@@ -1744,6 +1744,59 @@ paths:
responses:
"204":
description: No Content
+ /v1/users/self/api-keys:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: List API Keys
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.APIKeyOut"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: Create API Key
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.APIKeyCreate"
+ description: API Key Data
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.APIKeyCreatedOut"
+ "/v1/users/self/api-keys/{id}":
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: Delete API Key
+ parameters:
+ - description: API Key ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
/v1/users/self/settings:
get:
security:
@@ -1844,6 +1897,44 @@ components:
type: string
symbol:
type: string
+ ent.APIKey:
+ 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 APIKeyQuery when eager-loading is set.
+ allOf:
+ - $ref: "#/components/schemas/ent.APIKeyEdges"
+ expires_at:
+ description: ExpiresAt holds the value of the "expires_at" field.
+ type: string
+ id:
+ description: ID of the ent.
+ type: string
+ last_used_at:
+ description: LastUsedAt holds the value of the "last_used_at" field.
+ type: string
+ name:
+ description: Name holds the value of the "name" field.
+ type: string
+ updated_at:
+ description: UpdatedAt holds the value of the "updated_at" field.
+ type: string
+ user_id:
+ description: UserID holds the value of the "user_id" field.
+ type: string
+ ent.APIKeyEdges:
+ type: object
+ properties:
+ user:
+ description: User holds the value of the user edge.
+ allOf:
+ - $ref: "#/components/schemas/ent.User"
ent.Attachment:
type: object
properties:
@@ -2600,6 +2691,11 @@ components:
ent.UserEdges:
type: object
properties:
+ api_keys:
+ description: APIKeys holds the value of the api_keys edge.
+ type: array
+ items:
+ $ref: "#/components/schemas/ent.APIKey"
auth_tokens:
description: AuthTokens holds the value of the auth_tokens edge.
type: array
@@ -2627,6 +2723,54 @@ components:
- TypeNumber
- TypeBoolean
- TypeTime
+ repo.APIKeyCreate:
+ type: object
+ required:
+ - name
+ properties:
+ expiresAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ maxLength: 255
+ minLength: 1
+ repo.APIKeyCreatedOut:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ token:
+ type: string
+ userId:
+ type: string
+ repo.APIKeyOut:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ userId:
+ type: string
repo.BarcodeProduct:
type: object
properties:
diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.json
index 03988e58..c6b0d506 100644
--- a/backend/app/api/static/docs/swagger.json
+++ b/backend/app/api/static/docs/swagger.json
@@ -2757,6 +2757,93 @@
}
}
},
+ "/v1/users/self/api-keys": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "List API Keys",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.APIKeyOut"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Create API Key",
+ "parameters": [
+ {
+ "description": "API Key Data",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreate"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreatedOut"
+ }
+ }
+ }
+ }
+ },
+ "/v1/users/self/api-keys/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Delete API Key",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "API Key ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/users/self/settings": {
"get": {
"security": [
@@ -2899,6 +2986,60 @@
}
}
},
+ "ent.APIKey": {
+ "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 APIKeyQuery when eager-loading is set.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.APIKeyEdges"
+ }
+ ]
+ },
+ "expires_at": {
+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",
+ "type": "string"
+ },
+ "id": {
+ "description": "ID of the ent.",
+ "type": "string"
+ },
+ "last_used_at": {
+ "description": "LastUsedAt holds the value of the \"last_used_at\" field.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name holds the value of the \"name\" field.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",
+ "type": "string"
+ },
+ "user_id": {
+ "description": "UserID holds the value of the \"user_id\" field.",
+ "type": "string"
+ }
+ }
+ },
+ "ent.APIKeyEdges": {
+ "type": "object",
+ "properties": {
+ "user": {
+ "description": "User holds the value of the user edge.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.User"
+ }
+ ]
+ }
+ }
+ },
"ent.Attachment": {
"type": "object",
"properties": {
@@ -3979,6 +4120,13 @@
"ent.UserEdges": {
"type": "object",
"properties": {
+ "api_keys": {
+ "description": "APIKeys holds the value of the api_keys edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.APIKey"
+ }
+ },
"auth_tokens": {
"description": "AuthTokens holds the value of the auth_tokens edge.",
"type": "array",
@@ -4017,6 +4165,76 @@
"TypeTime"
]
},
+ "repo.APIKeyCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ }
+ }
+ },
+ "repo.APIKeyCreatedOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
+ "repo.APIKeyOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"repo.BarcodeProduct": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yaml
index a94de2f1..decc84da 100644
--- a/backend/app/api/static/docs/swagger.yaml
+++ b/backend/app/api/static/docs/swagger.yaml
@@ -43,6 +43,43 @@ definitions:
symbol:
type: string
type: object
+ ent.APIKey:
+ properties:
+ created_at:
+ description: CreatedAt holds the value of the "created_at" field.
+ type: string
+ edges:
+ allOf:
+ - $ref: '#/definitions/ent.APIKeyEdges'
+ description: |-
+ Edges holds the relations/edges for other nodes in the graph.
+ The values are being populated by the APIKeyQuery 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
+ last_used_at:
+ description: LastUsedAt holds the value of the "last_used_at" field.
+ type: string
+ name:
+ description: Name holds the value of the "name" field.
+ type: string
+ updated_at:
+ description: UpdatedAt holds the value of the "updated_at" field.
+ type: string
+ user_id:
+ description: UserID holds the value of the "user_id" field.
+ type: string
+ type: object
+ ent.APIKeyEdges:
+ properties:
+ user:
+ allOf:
+ - $ref: '#/definitions/ent.User'
+ description: User holds the value of the user edge.
+ type: object
ent.Attachment:
properties:
created_at:
@@ -785,6 +822,11 @@ definitions:
type: object
ent.UserEdges:
properties:
+ api_keys:
+ description: APIKeys holds the value of the api_keys edge.
+ items:
+ $ref: '#/definitions/ent.APIKey'
+ type: array
auth_tokens:
description: AuthTokens holds the value of the auth_tokens edge.
items:
@@ -813,6 +855,54 @@ definitions:
- TypeNumber
- TypeBoolean
- TypeTime
+ repo.APIKeyCreate:
+ properties:
+ expiresAt:
+ type: string
+ x-nullable: true
+ name:
+ maxLength: 255
+ minLength: 1
+ type: string
+ required:
+ - name
+ type: object
+ repo.APIKeyCreatedOut:
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ x-nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ x-nullable: true
+ name:
+ type: string
+ token:
+ type: string
+ userId:
+ type: string
+ type: object
+ repo.APIKeyOut:
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ x-nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ x-nullable: true
+ name:
+ type: string
+ userId:
+ type: string
+ type: object
repo.BarcodeProduct:
properties:
barcode:
@@ -3730,6 +3820,58 @@ paths:
summary: Update Account
tags:
- User
+ /v1/users/self/api-keys:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.APIKeyOut'
+ type: array
+ security:
+ - Bearer: []
+ summary: List API Keys
+ tags:
+ - User
+ post:
+ parameters:
+ - description: API Key Data
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/repo.APIKeyCreate'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.APIKeyCreatedOut'
+ security:
+ - Bearer: []
+ summary: Create API Key
+ tags:
+ - User
+ /v1/users/self/api-keys/{id}:
+ delete:
+ parameters:
+ - description: API Key ID
+ in: path
+ name: id
+ required: true
+ type: string
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete API Key
+ tags:
+ - User
/v1/users/self/settings:
get:
produces:
diff --git a/backend/internal/core/services/contexts.go b/backend/internal/core/services/contexts.go
index 8f1a4153..0687b525 100644
--- a/backend/internal/core/services/contexts.go
+++ b/backend/internal/core/services/contexts.go
@@ -15,6 +15,7 @@ var (
ContextUser = &contextKeys{name: "User"}
ContextUserToken = &contextKeys{name: "UserToken"}
ContextTenant = &contextKeys{name: "Tenant"}
+ ContextAPIKey = &contextKeys{name: "APIKey"}
)
type Context struct {
@@ -89,3 +90,17 @@ func UseTenantCtx(ctx context.Context) uuid.UUID {
func SetTenantCtx(ctx context.Context, tenantID uuid.UUID) context.Context {
return context.WithValue(ctx, ContextTenant, tenantID)
}
+
+// SetAPIKeyAuth marks the request context as authenticated via a static API
+// key rather than a session token. Handlers that are session-specific (logout,
+// refresh) consult this flag via IsAPIKeyAuth.
+func SetAPIKeyAuth(ctx context.Context) context.Context {
+ return context.WithValue(ctx, ContextAPIKey, true)
+}
+
+// IsAPIKeyAuth reports whether the current request was authenticated via a
+// static API key.
+func IsAPIKeyAuth(ctx context.Context) bool {
+ v, _ := ctx.Value(ContextAPIKey).(bool)
+ return v
+}
diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go
index fc7c4fc2..51502d0b 100644
--- a/backend/internal/core/services/service_user.go
+++ b/backend/internal/core/services/service_user.go
@@ -713,6 +713,64 @@ func (svc *UserService) EnsureUserPassword(ctx context.Context, email, password
return nil
}
+// ============================================================================
+// User API Keys
+
+// CreateAPIKey generates a new static API key for the user. The raw token is
+// returned exactly once and must be displayed to the user immediately — only
+// the hash is persisted.
+func (svc *UserService) CreateAPIKey(ctx context.Context, userID uuid.UUID, in repo.APIKeyCreate) (repo.APIKeyCreatedOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.CreateAPIKey",
+ trace.WithAttributes(
+ attribute.String("user.id", userID.String()),
+ attribute.Int("api_key.name.length", len(in.Name)),
+ attribute.Bool("api_key.has_expiration", in.ExpiresAt != nil),
+ ))
+ defer span.End()
+
+ token := hasher.GenerateAPIKeyCtx(ctx)
+ out, err := svc.repos.APIKeys.Create(ctx, userID, in.Name, token.Hash, in.ExpiresAt)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ return repo.APIKeyCreatedOut{}, err
+ }
+
+ span.SetAttributes(attribute.String("api_key.id", out.ID.String()))
+ return repo.APIKeyCreatedOut{
+ APIKeyOut: out,
+ Token: token.Raw,
+ }, nil
+}
+
+func (svc *UserService) ListAPIKeys(ctx context.Context, userID uuid.UUID) ([]repo.APIKeyOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.ListAPIKeys",
+ trace.WithAttributes(attribute.String("user.id", userID.String())))
+ defer span.End()
+
+ out, err := svc.repos.APIKeys.GetByUser(ctx, userID)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ return nil, err
+ }
+ span.SetAttributes(attribute.Int("api_keys.count", len(out)))
+ return out, nil
+}
+
+func (svc *UserService) DeleteAPIKey(ctx context.Context, userID, id uuid.UUID) error {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.DeleteAPIKey",
+ trace.WithAttributes(
+ attribute.String("user.id", userID.String()),
+ attribute.String("api_key.id", id.String()),
+ ))
+ defer span.End()
+
+ err := svc.repos.APIKeys.Delete(ctx, userID, id)
+ if err != nil && !ent.IsNotFound(err) {
+ recordServiceSpanError(span, err)
+ }
+ return err
+}
+
// ExistsByEmail returns true if a user with the given email exists.
func (svc *UserService) ExistsByEmail(ctx context.Context, email string) bool {
ctx, span := entityServiceTracer().Start(ctx, "service.UserService.ExistsByEmail",
diff --git a/backend/internal/data/ent/apikey.go b/backend/internal/data/ent/apikey.go
new file mode 100644
index 00000000..b42c8126
--- /dev/null
+++ b/backend/internal/data/ent/apikey.go
@@ -0,0 +1,209 @@
+// 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/apikey"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+)
+
+// APIKey is the model entity for the APIKey schema.
+type APIKey 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"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // Name holds the value of the "name" field.
+ Name string `json:"name,omitempty"`
+ // Token holds the value of the "token" field.
+ Token []byte `json:"-"`
+ // ExpiresAt holds the value of the "expires_at" field.
+ ExpiresAt *time.Time `json:"expires_at,omitempty"`
+ // LastUsedAt holds the value of the "last_used_at" field.
+ LastUsedAt *time.Time `json:"last_used_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the APIKeyQuery when eager-loading is set.
+ Edges APIKeyEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// APIKeyEdges holds the relations/edges for other nodes in the graph.
+type APIKeyEdges 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 APIKeyEdges) 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 (*APIKey) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case apikey.FieldToken:
+ values[i] = new([]byte)
+ case apikey.FieldName:
+ values[i] = new(sql.NullString)
+ case apikey.FieldCreatedAt, apikey.FieldUpdatedAt, apikey.FieldExpiresAt, apikey.FieldLastUsedAt:
+ values[i] = new(sql.NullTime)
+ case apikey.FieldID, apikey.FieldUserID:
+ values[i] = 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 APIKey fields.
+func (_m *APIKey) 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 apikey.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 apikey.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 apikey.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 apikey.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ _m.UserID = *value
+ }
+ case apikey.FieldName:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field name", values[i])
+ } else if value.Valid {
+ _m.Name = value.String
+ }
+ case apikey.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 apikey.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 = new(time.Time)
+ *_m.ExpiresAt = value.Time
+ }
+ case apikey.FieldLastUsedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field last_used_at", values[i])
+ } else if value.Valid {
+ _m.LastUsedAt = new(time.Time)
+ *_m.LastUsedAt = value.Time
+ }
+ default:
+ _m.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the APIKey.
+// This includes values selected through modifiers, order, etc.
+func (_m *APIKey) Value(name string) (ent.Value, error) {
+ return _m.selectValues.Get(name)
+}
+
+// QueryUser queries the "user" edge of the APIKey entity.
+func (_m *APIKey) QueryUser() *UserQuery {
+ return NewAPIKeyClient(_m.config).QueryUser(_m)
+}
+
+// Update returns a builder for updating this APIKey.
+// Note that you need to call APIKey.Unwrap() before calling this method if this APIKey
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (_m *APIKey) Update() *APIKeyUpdateOne {
+ return NewAPIKeyClient(_m.config).UpdateOne(_m)
+}
+
+// Unwrap unwraps the APIKey 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 *APIKey) Unwrap() *APIKey {
+ _tx, ok := _m.config.driver.(*txDriver)
+ if !ok {
+ panic("ent: APIKey is not a transactional entity")
+ }
+ _m.config.driver = _tx.drv
+ return _m
+}
+
+// String implements the fmt.Stringer.
+func (_m *APIKey) String() string {
+ var builder strings.Builder
+ builder.WriteString("APIKey(")
+ 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("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", _m.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("name=")
+ builder.WriteString(_m.Name)
+ builder.WriteString(", ")
+ builder.WriteString("token=<sensitive>")
+ builder.WriteString(", ")
+ if v := _m.ExpiresAt; v != nil {
+ builder.WriteString("expires_at=")
+ builder.WriteString(v.Format(time.ANSIC))
+ }
+ builder.WriteString(", ")
+ if v := _m.LastUsedAt; v != nil {
+ builder.WriteString("last_used_at=")
+ builder.WriteString(v.Format(time.ANSIC))
+ }
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// APIKeys is a parsable slice of APIKey.
+type APIKeys []*APIKey
diff --git a/backend/internal/data/ent/apikey/apikey.go b/backend/internal/data/ent/apikey/apikey.go
new file mode 100644
index 00000000..1a614a8c
--- /dev/null
+++ b/backend/internal/data/ent/apikey/apikey.go
@@ -0,0 +1,130 @@
+// Code generated by ent, DO NOT EDIT.
+
+package apikey
+
+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 apikey type in the database.
+ Label = "api_key"
+ // 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"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldName holds the string denoting the name field in the database.
+ FieldName = "name"
+ // 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"
+ // FieldLastUsedAt holds the string denoting the last_used_at field in the database.
+ FieldLastUsedAt = "last_used_at"
+ // EdgeUser holds the string denoting the user edge name in mutations.
+ EdgeUser = "user"
+ // Table holds the table name of the apikey in the database.
+ Table = "api_keys"
+ // UserTable is the table that holds the user relation/edge.
+ UserTable = "api_keys"
+ // 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_id"
+)
+
+// Columns holds all SQL columns for apikey fields.
+var Columns = []string{
+ FieldID,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+ FieldUserID,
+ FieldName,
+ FieldToken,
+ FieldExpiresAt,
+ FieldLastUsedAt,
+}
+
+// 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
+ }
+ }
+ 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
+ // NameValidator is a validator for the "name" field. It is called by the builders before save.
+ NameValidator func(string) error
+ // DefaultID holds the default value on creation for the "id" field.
+ DefaultID func() uuid.UUID
+)
+
+// OrderOption defines the ordering options for the APIKey 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()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByName orders the results by the name field.
+func ByName(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldName, opts...).ToFunc()
+}
+
+// ByExpiresAt orders the results by the expires_at field.
+func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
+}
+
+// ByLastUsedAt orders the results by the last_used_at field.
+func ByLastUsedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldLastUsedAt, 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/apikey/where.go b/backend/internal/data/ent/apikey/where.go
new file mode 100644
index 00000000..2f5e1295
--- /dev/null
+++ b/backend/internal/data/ent/apikey/where.go
@@ -0,0 +1,435 @@
+// Code generated by ent, DO NOT EDIT.
+
+package apikey
+
+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.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(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.APIKey {
+ return predicate.APIKey(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.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldUserID, v))
+}
+
+// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
+func Name(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldName, v))
+}
+
+// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
+func Token(v []byte) predicate.APIKey {
+ return predicate.APIKey(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.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldExpiresAt, v))
+}
+
+// LastUsedAt applies equality check predicate on the "last_used_at" field. It's identical to LastUsedAtEQ.
+func LastUsedAt(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldLastUsedAt, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// NameEQ applies the EQ predicate on the "name" field.
+func NameEQ(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldName, v))
+}
+
+// NameNEQ applies the NEQ predicate on the "name" field.
+func NameNEQ(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldName, v))
+}
+
+// NameIn applies the In predicate on the "name" field.
+func NameIn(vs ...string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldName, vs...))
+}
+
+// NameNotIn applies the NotIn predicate on the "name" field.
+func NameNotIn(vs ...string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldName, vs...))
+}
+
+// NameGT applies the GT predicate on the "name" field.
+func NameGT(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldName, v))
+}
+
+// NameGTE applies the GTE predicate on the "name" field.
+func NameGTE(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldName, v))
+}
+
+// NameLT applies the LT predicate on the "name" field.
+func NameLT(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldName, v))
+}
+
+// NameLTE applies the LTE predicate on the "name" field.
+func NameLTE(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldName, v))
+}
+
+// NameContains applies the Contains predicate on the "name" field.
+func NameContains(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldContains(FieldName, v))
+}
+
+// NameHasPrefix applies the HasPrefix predicate on the "name" field.
+func NameHasPrefix(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldHasPrefix(FieldName, v))
+}
+
+// NameHasSuffix applies the HasSuffix predicate on the "name" field.
+func NameHasSuffix(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldHasSuffix(FieldName, v))
+}
+
+// NameEqualFold applies the EqualFold predicate on the "name" field.
+func NameEqualFold(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEqualFold(FieldName, v))
+}
+
+// NameContainsFold applies the ContainsFold predicate on the "name" field.
+func NameContainsFold(v string) predicate.APIKey {
+ return predicate.APIKey(sql.FieldContainsFold(FieldName, v))
+}
+
+// TokenEQ applies the EQ predicate on the "token" field.
+func TokenEQ(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldToken, v))
+}
+
+// TokenNEQ applies the NEQ predicate on the "token" field.
+func TokenNEQ(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldToken, v))
+}
+
+// TokenIn applies the In predicate on the "token" field.
+func TokenIn(vs ...[]byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldToken, vs...))
+}
+
+// TokenNotIn applies the NotIn predicate on the "token" field.
+func TokenNotIn(vs ...[]byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldToken, vs...))
+}
+
+// TokenGT applies the GT predicate on the "token" field.
+func TokenGT(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldToken, v))
+}
+
+// TokenGTE applies the GTE predicate on the "token" field.
+func TokenGTE(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldToken, v))
+}
+
+// TokenLT applies the LT predicate on the "token" field.
+func TokenLT(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldToken, v))
+}
+
+// TokenLTE applies the LTE predicate on the "token" field.
+func TokenLTE(v []byte) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldToken, v))
+}
+
+// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
+func ExpiresAtEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldExpiresAt, v))
+}
+
+// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
+func ExpiresAtNEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldExpiresAt, v))
+}
+
+// ExpiresAtIn applies the In predicate on the "expires_at" field.
+func ExpiresAtIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldExpiresAt, vs...))
+}
+
+// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
+func ExpiresAtNotIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldExpiresAt, vs...))
+}
+
+// ExpiresAtGT applies the GT predicate on the "expires_at" field.
+func ExpiresAtGT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldExpiresAt, v))
+}
+
+// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
+func ExpiresAtGTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldExpiresAt, v))
+}
+
+// ExpiresAtLT applies the LT predicate on the "expires_at" field.
+func ExpiresAtLT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldExpiresAt, v))
+}
+
+// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
+func ExpiresAtLTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldExpiresAt, v))
+}
+
+// ExpiresAtIsNil applies the IsNil predicate on the "expires_at" field.
+func ExpiresAtIsNil() predicate.APIKey {
+ return predicate.APIKey(sql.FieldIsNull(FieldExpiresAt))
+}
+
+// ExpiresAtNotNil applies the NotNil predicate on the "expires_at" field.
+func ExpiresAtNotNil() predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotNull(FieldExpiresAt))
+}
+
+// LastUsedAtEQ applies the EQ predicate on the "last_used_at" field.
+func LastUsedAtEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldEQ(FieldLastUsedAt, v))
+}
+
+// LastUsedAtNEQ applies the NEQ predicate on the "last_used_at" field.
+func LastUsedAtNEQ(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNEQ(FieldLastUsedAt, v))
+}
+
+// LastUsedAtIn applies the In predicate on the "last_used_at" field.
+func LastUsedAtIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldIn(FieldLastUsedAt, vs...))
+}
+
+// LastUsedAtNotIn applies the NotIn predicate on the "last_used_at" field.
+func LastUsedAtNotIn(vs ...time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotIn(FieldLastUsedAt, vs...))
+}
+
+// LastUsedAtGT applies the GT predicate on the "last_used_at" field.
+func LastUsedAtGT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGT(FieldLastUsedAt, v))
+}
+
+// LastUsedAtGTE applies the GTE predicate on the "last_used_at" field.
+func LastUsedAtGTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldGTE(FieldLastUsedAt, v))
+}
+
+// LastUsedAtLT applies the LT predicate on the "last_used_at" field.
+func LastUsedAtLT(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLT(FieldLastUsedAt, v))
+}
+
+// LastUsedAtLTE applies the LTE predicate on the "last_used_at" field.
+func LastUsedAtLTE(v time.Time) predicate.APIKey {
+ return predicate.APIKey(sql.FieldLTE(FieldLastUsedAt, v))
+}
+
+// LastUsedAtIsNil applies the IsNil predicate on the "last_used_at" field.
+func LastUsedAtIsNil() predicate.APIKey {
+ return predicate.APIKey(sql.FieldIsNull(FieldLastUsedAt))
+}
+
+// LastUsedAtNotNil applies the NotNil predicate on the "last_used_at" field.
+func LastUsedAtNotNil() predicate.APIKey {
+ return predicate.APIKey(sql.FieldNotNull(FieldLastUsedAt))
+}
+
+// HasUser applies the HasEdge predicate on the "user" edge.
+func HasUser() predicate.APIKey {
+ return predicate.APIKey(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.APIKey {
+ return predicate.APIKey(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.APIKey) predicate.APIKey {
+ return predicate.APIKey(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.APIKey) predicate.APIKey {
+ return predicate.APIKey(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.APIKey) predicate.APIKey {
+ return predicate.APIKey(sql.NotPredicates(p))
+}
diff --git a/backend/internal/data/ent/apikey_create.go b/backend/internal/data/ent/apikey_create.go
new file mode 100644
index 00000000..13e49161
--- /dev/null
+++ b/backend/internal/data/ent/apikey_create.go
@@ -0,0 +1,353 @@
+// 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/apikey"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+)
+
+// APIKeyCreate is the builder for creating a APIKey entity.
+type APIKeyCreate struct {
+ config
+ mutation *APIKeyMutation
+ hooks []Hook
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (_c *APIKeyCreate) SetCreatedAt(v time.Time) *APIKeyCreate {
+ _c.mutation.SetCreatedAt(v)
+ return _c
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (_c *APIKeyCreate) SetNillableCreatedAt(v *time.Time) *APIKeyCreate {
+ if v != nil {
+ _c.SetCreatedAt(*v)
+ }
+ return _c
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (_c *APIKeyCreate) SetUpdatedAt(v time.Time) *APIKeyCreate {
+ _c.mutation.SetUpdatedAt(v)
+ return _c
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (_c *APIKeyCreate) SetNillableUpdatedAt(v *time.Time) *APIKeyCreate {
+ if v != nil {
+ _c.SetUpdatedAt(*v)
+ }
+ return _c
+}
+
+// SetUserID sets the "user_id" field.
+func (_c *APIKeyCreate) SetUserID(v uuid.UUID) *APIKeyCreate {
+ _c.mutation.SetUserID(v)
+ return _c
+}
+
+// SetName sets the "name" field.
+func (_c *APIKeyCreate) SetName(v string) *APIKeyCreate {
+ _c.mutation.SetName(v)
+ return _c
+}
+
+// SetToken sets the "token" field.
+func (_c *APIKeyCreate) SetToken(v []byte) *APIKeyCreate {
+ _c.mutation.SetToken(v)
+ return _c
+}
+
+// SetExpiresAt sets the "expires_at" field.
+func (_c *APIKeyCreate) SetExpiresAt(v time.Time) *APIKeyCreate {
+ _c.mutation.SetExpiresAt(v)
+ return _c
+}
+
+// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
+func (_c *APIKeyCreate) SetNillableExpiresAt(v *time.Time) *APIKeyCreate {
+ if v != nil {
+ _c.SetExpiresAt(*v)
+ }
+ return _c
+}
+
+// SetLastUsedAt sets the "last_used_at" field.
+func (_c *APIKeyCreate) SetLastUsedAt(v time.Time) *APIKeyCreate {
+ _c.mutation.SetLastUsedAt(v)
+ return _c
+}
+
+// SetNillableLastUsedAt sets the "last_used_at" field if the given value is not nil.
+func (_c *APIKeyCreate) SetNillableLastUsedAt(v *time.Time) *APIKeyCreate {
+ if v != nil {
+ _c.SetLastUsedAt(*v)
+ }
+ return _c
+}
+
+// SetID sets the "id" field.
+func (_c *APIKeyCreate) SetID(v uuid.UUID) *APIKeyCreate {
+ _c.mutation.SetID(v)
+ return _c
+}
+
+// SetNillableID sets the "id" field if the given value is not nil.
+func (_c *APIKeyCreate) SetNillableID(v *uuid.UUID) *APIKeyCreate {
+ if v != nil {
+ _c.SetID(*v)
+ }
+ return _c
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_c *APIKeyCreate) SetUser(v *User) *APIKeyCreate {
+ return _c.SetUserID(v.ID)
+}
+
+// Mutation returns the APIKeyMutation object of the builder.
+func (_c *APIKeyCreate) Mutation() *APIKeyMutation {
+ return _c.mutation
+}
+
+// Save creates the APIKey in the database.
+func (_c *APIKeyCreate) Save(ctx context.Context) (*APIKey, error) {
+ _c.defaults()
+ return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (_c *APIKeyCreate) SaveX(ctx context.Context) *APIKey {
+ v, err := _c.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (_c *APIKeyCreate) Exec(ctx context.Context) error {
+ _, err := _c.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_c *APIKeyCreate) 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 *APIKeyCreate) defaults() {
+ if _, ok := _c.mutation.CreatedAt(); !ok {
+ v := apikey.DefaultCreatedAt()
+ _c.mutation.SetCreatedAt(v)
+ }
+ if _, ok := _c.mutation.UpdatedAt(); !ok {
+ v := apikey.DefaultUpdatedAt()
+ _c.mutation.SetUpdatedAt(v)
+ }
+ if _, ok := _c.mutation.ID(); !ok {
+ v := apikey.DefaultID()
+ _c.mutation.SetID(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_c *APIKeyCreate) check() error {
+ if _, ok := _c.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "APIKey.created_at"`)}
+ }
+ if _, ok := _c.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "APIKey.updated_at"`)}
+ }
+ if _, ok := _c.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "APIKey.user_id"`)}
+ }
+ if _, ok := _c.mutation.Name(); !ok {
+ return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "APIKey.name"`)}
+ }
+ if v, ok := _c.mutation.Name(); ok {
+ if err := apikey.NameValidator(v); err != nil {
+ return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "APIKey.name": %w`, err)}
+ }
+ }
+ if _, ok := _c.mutation.Token(); !ok {
+ return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "APIKey.token"`)}
+ }
+ if len(_c.mutation.UserIDs()) == 0 {
+ return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "APIKey.user"`)}
+ }
+ return nil
+}
+
+func (_c *APIKeyCreate) sqlSave(ctx context.Context) (*APIKey, 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 *APIKeyCreate) createSpec() (*APIKey, *sqlgraph.CreateSpec) {
+ var (
+ _node = &APIKey{config: _c.config}
+ _spec = sqlgraph.NewCreateSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.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(apikey.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := _c.mutation.UpdatedAt(); ok {
+ _spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ if value, ok := _c.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ _node.Name = value
+ }
+ if value, ok := _c.mutation.Token(); ok {
+ _spec.SetField(apikey.FieldToken, field.TypeBytes, value)
+ _node.Token = value
+ }
+ if value, ok := _c.mutation.ExpiresAt(); ok {
+ _spec.SetField(apikey.FieldExpiresAt, field.TypeTime, value)
+ _node.ExpiresAt = &value
+ }
+ if value, ok := _c.mutation.LastUsedAt(); ok {
+ _spec.SetField(apikey.FieldLastUsedAt, field.TypeTime, value)
+ _node.LastUsedAt = &value
+ }
+ if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: apikey.UserTable,
+ Columns: []string{apikey.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.UserID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// APIKeyCreateBulk is the builder for creating many APIKey entities in bulk.
+type APIKeyCreateBulk struct {
+ config
+ err error
+ builders []*APIKeyCreate
+}
+
+// Save creates the APIKey entities in the database.
+func (_c *APIKeyCreateBulk) Save(ctx context.Context) ([]*APIKey, error) {
+ if _c.err != nil {
+ return nil, _c.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
+ nodes := make([]*APIKey, 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.(*APIKeyMutation)
+ 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 *APIKeyCreateBulk) SaveX(ctx context.Context) []*APIKey {
+ v, err := _c.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (_c *APIKeyCreateBulk) Exec(ctx context.Context) error {
+ _, err := _c.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_c *APIKeyCreateBulk) ExecX(ctx context.Context) {
+ if err := _c.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/internal/data/ent/apikey_delete.go b/backend/internal/data/ent/apikey_delete.go
new file mode 100644
index 00000000..b65b54b8
--- /dev/null
+++ b/backend/internal/data/ent/apikey_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/apikey"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+)
+
+// APIKeyDelete is the builder for deleting a APIKey entity.
+type APIKeyDelete struct {
+ config
+ hooks []Hook
+ mutation *APIKeyMutation
+}
+
+// Where appends a list predicates to the APIKeyDelete builder.
+func (_d *APIKeyDelete) Where(ps ...predicate.APIKey) *APIKeyDelete {
+ _d.mutation.Where(ps...)
+ return _d
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (_d *APIKeyDelete) 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 *APIKeyDelete) ExecX(ctx context.Context) int {
+ n, err := _d.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (_d *APIKeyDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.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
+}
+
+// APIKeyDeleteOne is the builder for deleting a single APIKey entity.
+type APIKeyDeleteOne struct {
+ _d *APIKeyDelete
+}
+
+// Where appends a list predicates to the APIKeyDelete builder.
+func (_d *APIKeyDeleteOne) Where(ps ...predicate.APIKey) *APIKeyDeleteOne {
+ _d._d.mutation.Where(ps...)
+ return _d
+}
+
+// Exec executes the deletion query.
+func (_d *APIKeyDeleteOne) Exec(ctx context.Context) error {
+ n, err := _d._d.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{apikey.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_d *APIKeyDeleteOne) ExecX(ctx context.Context) {
+ if err := _d.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/internal/data/ent/apikey_query.go b/backend/internal/data/ent/apikey_query.go
new file mode 100644
index 00000000..40261f4b
--- /dev/null
+++ b/backend/internal/data/ent/apikey_query.go
@@ -0,0 +1,607 @@
+// 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/apikey"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+)
+
+// APIKeyQuery is the builder for querying APIKey entities.
+type APIKeyQuery struct {
+ config
+ ctx *QueryContext
+ order []apikey.OrderOption
+ inters []Interceptor
+ predicates []predicate.APIKey
+ withUser *UserQuery
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the APIKeyQuery builder.
+func (_q *APIKeyQuery) Where(ps ...predicate.APIKey) *APIKeyQuery {
+ _q.predicates = append(_q.predicates, ps...)
+ return _q
+}
+
+// Limit the number of records to be returned by this query.
+func (_q *APIKeyQuery) Limit(limit int) *APIKeyQuery {
+ _q.ctx.Limit = &limit
+ return _q
+}
+
+// Offset to start from.
+func (_q *APIKeyQuery) Offset(offset int) *APIKeyQuery {
+ _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 *APIKeyQuery) Unique(unique bool) *APIKeyQuery {
+ _q.ctx.Unique = &unique
+ return _q
+}
+
+// Order specifies how the records should be ordered.
+func (_q *APIKeyQuery) Order(o ...apikey.OrderOption) *APIKeyQuery {
+ _q.order = append(_q.order, o...)
+ return _q
+}
+
+// QueryUser chains the current query on the "user" edge.
+func (_q *APIKeyQuery) 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(apikey.Table, apikey.FieldID, selector),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, apikey.UserTable, apikey.UserColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first APIKey entity from the query.
+// Returns a *NotFoundError when no APIKey was found.
+func (_q *APIKeyQuery) First(ctx context.Context) (*APIKey, 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{apikey.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (_q *APIKeyQuery) FirstX(ctx context.Context) *APIKey {
+ node, err := _q.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first APIKey ID from the query.
+// Returns a *NotFoundError when no APIKey ID was found.
+func (_q *APIKeyQuery) 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{apikey.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (_q *APIKeyQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := _q.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single APIKey entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one APIKey entity is found.
+// Returns a *NotFoundError when no APIKey entities are found.
+func (_q *APIKeyQuery) Only(ctx context.Context) (*APIKey, 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{apikey.Label}
+ default:
+ return nil, &NotSingularError{apikey.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (_q *APIKeyQuery) OnlyX(ctx context.Context) *APIKey {
+ node, err := _q.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only APIKey ID in the query.
+// Returns a *NotSingularError when more than one APIKey ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (_q *APIKeyQuery) 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{apikey.Label}
+ default:
+ err = &NotSingularError{apikey.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (_q *APIKeyQuery) 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 APIKeys.
+func (_q *APIKeyQuery) All(ctx context.Context) ([]*APIKey, error) {
+ ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
+ if err := _q.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*APIKey, *APIKeyQuery]()
+ return withInterceptors[[]*APIKey](ctx, _q, qr, _q.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (_q *APIKeyQuery) AllX(ctx context.Context) []*APIKey {
+ nodes, err := _q.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of APIKey IDs.
+func (_q *APIKeyQuery) 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(apikey.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (_q *APIKeyQuery) 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 *APIKeyQuery) 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[*APIKeyQuery](), _q.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (_q *APIKeyQuery) 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 *APIKeyQuery) 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 *APIKeyQuery) ExistX(ctx context.Context) bool {
+ exist, err := _q.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the APIKeyQuery 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 *APIKeyQuery) Clone() *APIKeyQuery {
+ if _q == nil {
+ return nil
+ }
+ return &APIKeyQuery{
+ config: _q.config,
+ ctx: _q.ctx.Clone(),
+ order: append([]apikey.OrderOption{}, _q.order...),
+ inters: append([]Interceptor{}, _q.inters...),
+ predicates: append([]predicate.APIKey{}, _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 *APIKeyQuery) WithUser(opts ...func(*UserQuery)) *APIKeyQuery {
+ 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.APIKey.Query().
+// GroupBy(apikey.FieldCreatedAt).
+// Aggregate(ent.Count()).
+// Scan(ctx, &v)
+func (_q *APIKeyQuery) GroupBy(field string, fields ...string) *APIKeyGroupBy {
+ _q.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &APIKeyGroupBy{build: _q}
+ grbuild.flds = &_q.ctx.Fields
+ grbuild.label = apikey.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.APIKey.Query().
+// Select(apikey.FieldCreatedAt).
+// Scan(ctx, &v)
+func (_q *APIKeyQuery) Select(fields ...string) *APIKeySelect {
+ _q.ctx.Fields = append(_q.ctx.Fields, fields...)
+ sbuild := &APIKeySelect{APIKeyQuery: _q}
+ sbuild.label = apikey.Label
+ sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a APIKeySelect configured with the given aggregations.
+func (_q *APIKeyQuery) Aggregate(fns ...AggregateFunc) *APIKeySelect {
+ return _q.Select().Aggregate(fns...)
+}
+
+func (_q *APIKeyQuery) 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 !apikey.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 *APIKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*APIKey, error) {
+ var (
+ nodes = []*APIKey{}
+ _spec = _q.querySpec()
+ loadedTypes = [1]bool{
+ _q.withUser != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*APIKey).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &APIKey{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 *APIKey, e *User) { n.Edges.User = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (_q *APIKeyQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*APIKey, init func(*APIKey), assign func(*APIKey, *User)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*APIKey)
+ for i := range nodes {
+ fk := nodes[i].UserID
+ 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_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (_q *APIKeyQuery) 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 *APIKeyQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.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, apikey.FieldID)
+ for i := range fields {
+ if fields[i] != apikey.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ if _q.withUser != nil {
+ _spec.Node.AddColumnOnce(apikey.FieldUserID)
+ }
+ }
+ 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 *APIKeyQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(_q.driver.Dialect())
+ t1 := builder.Table(apikey.Table)
+ columns := _q.ctx.Fields
+ if len(columns) == 0 {
+ columns = apikey.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
+}
+
+// APIKeyGroupBy is the group-by builder for APIKey entities.
+type APIKeyGroupBy struct {
+ selector
+ build *APIKeyQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (_g *APIKeyGroupBy) Aggregate(fns ...AggregateFunc) *APIKeyGroupBy {
+ _g.fns = append(_g.fns, fns...)
+ return _g
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (_g *APIKeyGroupBy) 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[*APIKeyQuery, *APIKeyGroupBy](ctx, _g.build, _g, _g.build.inters, v)
+}
+
+func (_g *APIKeyGroupBy) sqlScan(ctx context.Context, root *APIKeyQuery, 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)
+}
+
+// APIKeySelect is the builder for selecting fields of APIKey entities.
+type APIKeySelect struct {
+ *APIKeyQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (_s *APIKeySelect) Aggregate(fns ...AggregateFunc) *APIKeySelect {
+ _s.fns = append(_s.fns, fns...)
+ return _s
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (_s *APIKeySelect) 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[*APIKeyQuery, *APIKeySelect](ctx, _s.APIKeyQuery, _s, _s.inters, v)
+}
+
+func (_s *APIKeySelect) sqlScan(ctx context.Context, root *APIKeyQuery, 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/apikey_update.go b/backend/internal/data/ent/apikey_update.go
new file mode 100644
index 00000000..7e538833
--- /dev/null
+++ b/backend/internal/data/ent/apikey_update.go
@@ -0,0 +1,510 @@
+// 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/apikey"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+)
+
+// APIKeyUpdate is the builder for updating APIKey entities.
+type APIKeyUpdate struct {
+ config
+ hooks []Hook
+ mutation *APIKeyMutation
+}
+
+// Where appends a list predicates to the APIKeyUpdate builder.
+func (_u *APIKeyUpdate) Where(ps ...predicate.APIKey) *APIKeyUpdate {
+ _u.mutation.Where(ps...)
+ return _u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (_u *APIKeyUpdate) SetUpdatedAt(v time.Time) *APIKeyUpdate {
+ _u.mutation.SetUpdatedAt(v)
+ return _u
+}
+
+// SetUserID sets the "user_id" field.
+func (_u *APIKeyUpdate) SetUserID(v uuid.UUID) *APIKeyUpdate {
+ _u.mutation.SetUserID(v)
+ return _u
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (_u *APIKeyUpdate) SetNillableUserID(v *uuid.UUID) *APIKeyUpdate {
+ if v != nil {
+ _u.SetUserID(*v)
+ }
+ return _u
+}
+
+// SetName sets the "name" field.
+func (_u *APIKeyUpdate) SetName(v string) *APIKeyUpdate {
+ _u.mutation.SetName(v)
+ return _u
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (_u *APIKeyUpdate) SetNillableName(v *string) *APIKeyUpdate {
+ if v != nil {
+ _u.SetName(*v)
+ }
+ return _u
+}
+
+// SetToken sets the "token" field.
+func (_u *APIKeyUpdate) SetToken(v []byte) *APIKeyUpdate {
+ _u.mutation.SetToken(v)
+ return _u
+}
+
+// SetExpiresAt sets the "expires_at" field.
+func (_u *APIKeyUpdate) SetExpiresAt(v time.Time) *APIKeyUpdate {
+ _u.mutation.SetExpiresAt(v)
+ return _u
+}
+
+// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
+func (_u *APIKeyUpdate) SetNillableExpiresAt(v *time.Time) *APIKeyUpdate {
+ if v != nil {
+ _u.SetExpiresAt(*v)
+ }
+ return _u
+}
+
+// ClearExpiresAt clears the value of the "expires_at" field.
+func (_u *APIKeyUpdate) ClearExpiresAt() *APIKeyUpdate {
+ _u.mutation.ClearExpiresAt()
+ return _u
+}
+
+// SetLastUsedAt sets the "last_used_at" field.
+func (_u *APIKeyUpdate) SetLastUsedAt(v time.Time) *APIKeyUpdate {
+ _u.mutation.SetLastUsedAt(v)
+ return _u
+}
+
+// SetNillableLastUsedAt sets the "last_used_at" field if the given value is not nil.
+func (_u *APIKeyUpdate) SetNillableLastUsedAt(v *time.Time) *APIKeyUpdate {
+ if v != nil {
+ _u.SetLastUsedAt(*v)
+ }
+ return _u
+}
+
+// ClearLastUsedAt clears the value of the "last_used_at" field.
+func (_u *APIKeyUpdate) ClearLastUsedAt() *APIKeyUpdate {
+ _u.mutation.ClearLastUsedAt()
+ return _u
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_u *APIKeyUpdate) SetUser(v *User) *APIKeyUpdate {
+ return _u.SetUserID(v.ID)
+}
+
+// Mutation returns the APIKeyMutation object of the builder.
+func (_u *APIKeyUpdate) Mutation() *APIKeyMutation {
+ return _u.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (_u *APIKeyUpdate) ClearUser() *APIKeyUpdate {
+ _u.mutation.ClearUser()
+ return _u
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (_u *APIKeyUpdate) 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 *APIKeyUpdate) SaveX(ctx context.Context) int {
+ affected, err := _u.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (_u *APIKeyUpdate) Exec(ctx context.Context) error {
+ _, err := _u.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_u *APIKeyUpdate) 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 *APIKeyUpdate) defaults() {
+ if _, ok := _u.mutation.UpdatedAt(); !ok {
+ v := apikey.UpdateDefaultUpdatedAt()
+ _u.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_u *APIKeyUpdate) check() error {
+ if v, ok := _u.mutation.Name(); ok {
+ if err := apikey.NameValidator(v); err != nil {
+ return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "APIKey.name": %w`, err)}
+ }
+ }
+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "APIKey.user"`)
+ }
+ return nil
+}
+
+func (_u *APIKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
+ if err := _u.check(); err != nil {
+ return _node, err
+ }
+ _spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.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(apikey.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if value, ok := _u.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ }
+ if value, ok := _u.mutation.Token(); ok {
+ _spec.SetField(apikey.FieldToken, field.TypeBytes, value)
+ }
+ if value, ok := _u.mutation.ExpiresAt(); ok {
+ _spec.SetField(apikey.FieldExpiresAt, field.TypeTime, value)
+ }
+ if _u.mutation.ExpiresAtCleared() {
+ _spec.ClearField(apikey.FieldExpiresAt, field.TypeTime)
+ }
+ if value, ok := _u.mutation.LastUsedAt(); ok {
+ _spec.SetField(apikey.FieldLastUsedAt, field.TypeTime, value)
+ }
+ if _u.mutation.LastUsedAtCleared() {
+ _spec.ClearField(apikey.FieldLastUsedAt, field.TypeTime)
+ }
+ if _u.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: apikey.UserTable,
+ Columns: []string{apikey.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: apikey.UserTable,
+ Columns: []string{apikey.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{apikey.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ _u.mutation.done = true
+ return _node, nil
+}
+
+// APIKeyUpdateOne is the builder for updating a single APIKey entity.
+type APIKeyUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *APIKeyMutation
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (_u *APIKeyUpdateOne) SetUpdatedAt(v time.Time) *APIKeyUpdateOne {
+ _u.mutation.SetUpdatedAt(v)
+ return _u
+}
+
+// SetUserID sets the "user_id" field.
+func (_u *APIKeyUpdateOne) SetUserID(v uuid.UUID) *APIKeyUpdateOne {
+ _u.mutation.SetUserID(v)
+ return _u
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (_u *APIKeyUpdateOne) SetNillableUserID(v *uuid.UUID) *APIKeyUpdateOne {
+ if v != nil {
+ _u.SetUserID(*v)
+ }
+ return _u
+}
+
+// SetName sets the "name" field.
+func (_u *APIKeyUpdateOne) SetName(v string) *APIKeyUpdateOne {
+ _u.mutation.SetName(v)
+ return _u
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (_u *APIKeyUpdateOne) SetNillableName(v *string) *APIKeyUpdateOne {
+ if v != nil {
+ _u.SetName(*v)
+ }
+ return _u
+}
+
+// SetToken sets the "token" field.
+func (_u *APIKeyUpdateOne) SetToken(v []byte) *APIKeyUpdateOne {
+ _u.mutation.SetToken(v)
+ return _u
+}
+
+// SetExpiresAt sets the "expires_at" field.
+func (_u *APIKeyUpdateOne) SetExpiresAt(v time.Time) *APIKeyUpdateOne {
+ _u.mutation.SetExpiresAt(v)
+ return _u
+}
+
+// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
+func (_u *APIKeyUpdateOne) SetNillableExpiresAt(v *time.Time) *APIKeyUpdateOne {
+ if v != nil {
+ _u.SetExpiresAt(*v)
+ }
+ return _u
+}
+
+// ClearExpiresAt clears the value of the "expires_at" field.
+func (_u *APIKeyUpdateOne) ClearExpiresAt() *APIKeyUpdateOne {
+ _u.mutation.ClearExpiresAt()
+ return _u
+}
+
+// SetLastUsedAt sets the "last_used_at" field.
+func (_u *APIKeyUpdateOne) SetLastUsedAt(v time.Time) *APIKeyUpdateOne {
+ _u.mutation.SetLastUsedAt(v)
+ return _u
+}
+
+// SetNillableLastUsedAt sets the "last_used_at" field if the given value is not nil.
+func (_u *APIKeyUpdateOne) SetNillableLastUsedAt(v *time.Time) *APIKeyUpdateOne {
+ if v != nil {
+ _u.SetLastUsedAt(*v)
+ }
+ return _u
+}
+
+// ClearLastUsedAt clears the value of the "last_used_at" field.
+func (_u *APIKeyUpdateOne) ClearLastUsedAt() *APIKeyUpdateOne {
+ _u.mutation.ClearLastUsedAt()
+ return _u
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (_u *APIKeyUpdateOne) SetUser(v *User) *APIKeyUpdateOne {
+ return _u.SetUserID(v.ID)
+}
+
+// Mutation returns the APIKeyMutation object of the builder.
+func (_u *APIKeyUpdateOne) Mutation() *APIKeyMutation {
+ return _u.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (_u *APIKeyUpdateOne) ClearUser() *APIKeyUpdateOne {
+ _u.mutation.ClearUser()
+ return _u
+}
+
+// Where appends a list predicates to the APIKeyUpdate builder.
+func (_u *APIKeyUpdateOne) Where(ps ...predicate.APIKey) *APIKeyUpdateOne {
+ _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 *APIKeyUpdateOne) Select(field string, fields ...string) *APIKeyUpdateOne {
+ _u.fields = append([]string{field}, fields...)
+ return _u
+}
+
+// Save executes the query and returns the updated APIKey entity.
+func (_u *APIKeyUpdateOne) Save(ctx context.Context) (*APIKey, error) {
+ _u.defaults()
+ return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (_u *APIKeyUpdateOne) SaveX(ctx context.Context) *APIKey {
+ node, err := _u.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (_u *APIKeyUpdateOne) Exec(ctx context.Context) error {
+ _, err := _u.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (_u *APIKeyUpdateOne) 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 *APIKeyUpdateOne) defaults() {
+ if _, ok := _u.mutation.UpdatedAt(); !ok {
+ v := apikey.UpdateDefaultUpdatedAt()
+ _u.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (_u *APIKeyUpdateOne) check() error {
+ if v, ok := _u.mutation.Name(); ok {
+ if err := apikey.NameValidator(v); err != nil {
+ return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "APIKey.name": %w`, err)}
+ }
+ }
+ if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
+ return errors.New(`ent: clearing a required unique edge "APIKey.user"`)
+ }
+ return nil
+}
+
+func (_u *APIKeyUpdateOne) sqlSave(ctx context.Context) (_node *APIKey, err error) {
+ if err := _u.check(); err != nil {
+ return _node, err
+ }
+ _spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ id, ok := _u.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "APIKey.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, apikey.FieldID)
+ for _, f := range fields {
+ if !apikey.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
+ }
+ if f != apikey.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(apikey.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if value, ok := _u.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ }
+ if value, ok := _u.mutation.Token(); ok {
+ _spec.SetField(apikey.FieldToken, field.TypeBytes, value)
+ }
+ if value, ok := _u.mutation.ExpiresAt(); ok {
+ _spec.SetField(apikey.FieldExpiresAt, field.TypeTime, value)
+ }
+ if _u.mutation.ExpiresAtCleared() {
+ _spec.ClearField(apikey.FieldExpiresAt, field.TypeTime)
+ }
+ if value, ok := _u.mutation.LastUsedAt(); ok {
+ _spec.SetField(apikey.FieldLastUsedAt, field.TypeTime, value)
+ }
+ if _u.mutation.LastUsedAtCleared() {
+ _spec.ClearField(apikey.FieldLastUsedAt, field.TypeTime)
+ }
+ if _u.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: apikey.UserTable,
+ Columns: []string{apikey.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: apikey.UserTable,
+ Columns: []string{apikey.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 = &APIKey{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{apikey.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/client.go b/backend/internal/data/ent/client.go
index 9ff6e888..e9fc8975 100644
--- a/backend/internal/data/ent/client.go
+++ b/backend/internal/data/ent/client.go
@@ -16,6 +16,7 @@ import (
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
@@ -37,6 +38,8 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
+ // APIKey is the client for interacting with the APIKey builders.
+ APIKey *APIKeyClient
// Attachment is the client for interacting with the Attachment builders.
Attachment *AttachmentClient
// AuthRoles is the client for interacting with the AuthRoles builders.
@@ -76,6 +79,7 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
+ c.APIKey = NewAPIKeyClient(c.config)
c.Attachment = NewAttachmentClient(c.config)
c.AuthRoles = NewAuthRolesClient(c.config)
c.AuthTokens = NewAuthTokensClient(c.config)
@@ -182,6 +186,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
return &Tx{
ctx: ctx,
config: cfg,
+ APIKey: NewAPIKeyClient(cfg),
Attachment: NewAttachmentClient(cfg),
AuthRoles: NewAuthRolesClient(cfg),
AuthTokens: NewAuthTokensClient(cfg),
@@ -215,6 +220,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
return &Tx{
ctx: ctx,
config: cfg,
+ APIKey: NewAPIKeyClient(cfg),
Attachment: NewAttachmentClient(cfg),
AuthRoles: NewAuthRolesClient(cfg),
AuthTokens: NewAuthTokensClient(cfg),
@@ -235,7 +241,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
-// Attachment.
+// APIKey.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
@@ -258,7 +264,7 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
- c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,
+ 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,
} {
@@ -270,7 +276,7 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
- c.Attachment, c.AuthRoles, c.AuthTokens, c.Entity, c.EntityField,
+ 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,
} {
@@ -281,6 +287,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) {
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
+ case *APIKeyMutation:
+ return c.APIKey.mutate(ctx, m)
case *AttachmentMutation:
return c.Attachment.mutate(ctx, m)
case *AuthRolesMutation:
@@ -314,6 +322,155 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
}
}
+// APIKeyClient is a client for the APIKey schema.
+type APIKeyClient struct {
+ config
+}
+
+// NewAPIKeyClient returns a client for the APIKey from the given config.
+func NewAPIKeyClient(c config) *APIKeyClient {
+ return &APIKeyClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `apikey.Hooks(f(g(h())))`.
+func (c *APIKeyClient) Use(hooks ...Hook) {
+ c.hooks.APIKey = append(c.hooks.APIKey, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `apikey.Intercept(f(g(h())))`.
+func (c *APIKeyClient) Intercept(interceptors ...Interceptor) {
+ c.inters.APIKey = append(c.inters.APIKey, interceptors...)
+}
+
+// Create returns a builder for creating a APIKey entity.
+func (c *APIKeyClient) Create() *APIKeyCreate {
+ mutation := newAPIKeyMutation(c.config, OpCreate)
+ return &APIKeyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of APIKey entities.
+func (c *APIKeyClient) CreateBulk(builders ...*APIKeyCreate) *APIKeyCreateBulk {
+ return &APIKeyCreateBulk{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 *APIKeyClient) MapCreateBulk(slice any, setFunc func(*APIKeyCreate, int)) *APIKeyCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &APIKeyCreateBulk{err: fmt.Errorf("calling to APIKeyClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*APIKeyCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &APIKeyCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for APIKey.
+func (c *APIKeyClient) Update() *APIKeyUpdate {
+ mutation := newAPIKeyMutation(c.config, OpUpdate)
+ return &APIKeyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *APIKeyClient) UpdateOne(_m *APIKey) *APIKeyUpdateOne {
+ mutation := newAPIKeyMutation(c.config, OpUpdateOne, withAPIKey(_m))
+ return &APIKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *APIKeyClient) UpdateOneID(id uuid.UUID) *APIKeyUpdateOne {
+ mutation := newAPIKeyMutation(c.config, OpUpdateOne, withAPIKeyID(id))
+ return &APIKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for APIKey.
+func (c *APIKeyClient) Delete() *APIKeyDelete {
+ mutation := newAPIKeyMutation(c.config, OpDelete)
+ return &APIKeyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *APIKeyClient) DeleteOne(_m *APIKey) *APIKeyDeleteOne {
+ return c.DeleteOneID(_m.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *APIKeyClient) DeleteOneID(id uuid.UUID) *APIKeyDeleteOne {
+ builder := c.Delete().Where(apikey.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &APIKeyDeleteOne{builder}
+}
+
+// Query returns a query builder for APIKey.
+func (c *APIKeyClient) Query() *APIKeyQuery {
+ return &APIKeyQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeAPIKey},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a APIKey entity by its id.
+func (c *APIKeyClient) Get(ctx context.Context, id uuid.UUID) (*APIKey, error) {
+ return c.Query().Where(apikey.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *APIKeyClient) GetX(ctx context.Context, id uuid.UUID) *APIKey {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryUser queries the user edge of a APIKey.
+func (c *APIKeyClient) QueryUser(_m *APIKey) *UserQuery {
+ query := (&UserClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := _m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(apikey.Table, apikey.FieldID, id),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, apikey.UserTable, apikey.UserColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *APIKeyClient) Hooks() []Hook {
+ return c.hooks.APIKey
+}
+
+// Interceptors returns the client interceptors.
+func (c *APIKeyClient) Interceptors() []Interceptor {
+ return c.inters.APIKey
+}
+
+func (c *APIKeyClient) mutate(ctx context.Context, m *APIKeyMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&APIKeyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&APIKeyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&APIKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&APIKeyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("ent: unknown APIKey mutation op: %q", m.Op())
+ }
+}
+
// AttachmentClient is a client for the Attachment schema.
type AttachmentClient struct {
config
@@ -2759,6 +2916,22 @@ func (c *UserClient) QueryAuthTokens(_m *User) *AuthTokensQuery {
return query
}
+// QueryAPIKeys queries the api_keys edge of a User.
+func (c *UserClient) QueryAPIKeys(_m *User) *APIKeyQuery {
+ query := (&APIKeyClient{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(apikey.Table, apikey.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.APIKeysTable, user.APIKeysColumn),
+ )
+ fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
// QueryNotifiers queries the notifiers edge of a User.
func (c *UserClient) QueryNotifiers(_m *User) *NotifierQuery {
query := (&NotifierClient{config: c.config}).Query()
@@ -2803,12 +2976,12 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error)
// hooks and interceptors per client, for fast access.
type (
hooks struct {
- Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
+ APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,
TemplateField, User []ent.Hook
}
inters struct {
- Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
+ APIKey, Attachment, AuthRoles, AuthTokens, Entity, EntityField, EntityTemplate,
EntityType, Group, GroupInvitationToken, MaintenanceEntry, Notifier, Tag,
TemplateField, User []ent.Interceptor
}
diff --git a/backend/internal/data/ent/ent.go b/backend/internal/data/ent/ent.go
index 72e6d381..834abdd7 100644
--- a/backend/internal/data/ent/ent.go
+++ b/backend/internal/data/ent/ent.go
@@ -12,6 +12,7 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
@@ -86,6 +87,7 @@ var (
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
+ apikey.Table: apikey.ValidColumn,
attachment.Table: attachment.ValidColumn,
authroles.Table: authroles.ValidColumn,
authtokens.Table: authtokens.ValidColumn,
diff --git a/backend/internal/data/ent/has_id.go b/backend/internal/data/ent/has_id.go
index 1e4d0b6c..e1e483ca 100644
--- a/backend/internal/data/ent/has_id.go
+++ b/backend/internal/data/ent/has_id.go
@@ -4,6 +4,10 @@ package ent
import "github.com/google/uuid"
+func (_m *APIKey) GetID() uuid.UUID {
+ return _m.ID
+}
+
func (_m *Attachment) GetID() uuid.UUID {
return _m.ID
}
diff --git a/backend/internal/data/ent/hook/hook.go b/backend/internal/data/ent/hook/hook.go
index e680552d..cc26469c 100644
--- a/backend/internal/data/ent/hook/hook.go
+++ b/backend/internal/data/ent/hook/hook.go
@@ -9,6 +9,18 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
)
+// The APIKeyFunc type is an adapter to allow the use of ordinary
+// function as APIKey mutator.
+type APIKeyFunc func(context.Context, *ent.APIKeyMutation) (ent.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f APIKeyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
+ if mv, ok := m.(*ent.APIKeyMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.APIKeyMutation", m)
+}
+
// The AttachmentFunc type is an adapter to allow the use of ordinary
// function as Attachment mutator.
type AttachmentFunc func(context.Context, *ent.AttachmentMutation) (ent.Value, error)
diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.go
index b5823b37..e53a7883 100644
--- a/backend/internal/data/ent/migrate/schema.go
+++ b/backend/internal/data/ent/migrate/schema.go
@@ -8,6 +8,43 @@ import (
)
var (
+ // APIKeysColumns holds the columns for the "api_keys" table.
+ APIKeysColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ {Name: "name", Type: field.TypeString, Size: 255},
+ {Name: "token", Type: field.TypeBytes, Unique: true},
+ {Name: "expires_at", Type: field.TypeTime, Nullable: true},
+ {Name: "last_used_at", Type: field.TypeTime, Nullable: true},
+ {Name: "user_id", Type: field.TypeUUID},
+ }
+ // APIKeysTable holds the schema information for the "api_keys" table.
+ APIKeysTable = &schema.Table{
+ Name: "api_keys",
+ Columns: APIKeysColumns,
+ PrimaryKey: []*schema.Column{APIKeysColumns[0]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "api_keys_users_api_keys",
+ Columns: []*schema.Column{APIKeysColumns[7]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ },
+ Indexes: []*schema.Index{
+ {
+ Name: "apikey_token",
+ Unique: false,
+ Columns: []*schema.Column{APIKeysColumns[4]},
+ },
+ {
+ Name: "apikey_user_id",
+ Unique: false,
+ Columns: []*schema.Column{APIKeysColumns[7]},
+ },
+ },
+ }
// AttachmentsColumns holds the columns for the "attachments" table.
AttachmentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
@@ -549,6 +586,7 @@ var (
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
+ APIKeysTable,
AttachmentsTable,
AuthRolesTable,
AuthTokensTable,
@@ -569,6 +607,7 @@ var (
)
func init() {
+ APIKeysTable.ForeignKeys[0].RefTable = UsersTable
AttachmentsTable.ForeignKeys[0].RefTable = AttachmentsTable
AttachmentsTable.ForeignKeys[1].RefTable = EntitiesTable
AuthRolesTable.ForeignKeys[0].RefTable = AuthTokensTable
diff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.go
index ab24e953..dbbd2c89 100644
--- a/backend/internal/data/ent/mutation.go
+++ b/backend/internal/data/ent/mutation.go
@@ -12,6 +12,7 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
@@ -38,6 +39,7 @@ const (
OpUpdateOne = ent.OpUpdateOne
// Node types.
+ TypeAPIKey = "APIKey"
TypeAttachment = "Attachment"
TypeAuthRoles = "AuthRoles"
TypeAuthTokens = "AuthTokens"
@@ -54,6 +56,757 @@ const (
TypeUser = "User"
)
+// APIKeyMutation represents an operation that mutates the APIKey nodes in the graph.
+type APIKeyMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ created_at *time.Time
+ updated_at *time.Time
+ name *string
+ token *[]byte
+ expires_at *time.Time
+ last_used_at *time.Time
+ clearedFields map[string]struct{}
+ user *uuid.UUID
+ cleareduser bool
+ done bool
+ oldValue func(context.Context) (*APIKey, error)
+ predicates []predicate.APIKey
+}
+
+var _ ent.Mutation = (*APIKeyMutation)(nil)
+
+// apikeyOption allows management of the mutation configuration using functional options.
+type apikeyOption func(*APIKeyMutation)
+
+// newAPIKeyMutation creates new mutation for the APIKey entity.
+func newAPIKeyMutation(c config, op Op, opts ...apikeyOption) *APIKeyMutation {
+ m := &APIKeyMutation{
+ config: c,
+ op: op,
+ typ: TypeAPIKey,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withAPIKeyID sets the ID field of the mutation.
+func withAPIKeyID(id uuid.UUID) apikeyOption {
+ return func(m *APIKeyMutation) {
+ var (
+ err error
+ once sync.Once
+ value *APIKey
+ )
+ m.oldValue = func(ctx context.Context) (*APIKey, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().APIKey.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withAPIKey sets the old APIKey of the mutation.
+func withAPIKey(node *APIKey) apikeyOption {
+ return func(m *APIKeyMutation) {
+ m.oldValue = func(context.Context) (*APIKey, 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 APIKeyMutation) 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 APIKeyMutation) 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 APIKey entities.
+func (m *APIKeyMutation) 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 *APIKeyMutation) 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 *APIKeyMutation) 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().APIKey.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 *APIKeyMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *APIKeyMutation) 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 APIKey entity.
+// If the APIKey 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 *APIKeyMutation) 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 *APIKeyMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *APIKeyMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *APIKeyMutation) 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 APIKey entity.
+// If the APIKey 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 *APIKeyMutation) 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 *APIKeyMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// SetUserID sets the "user_id" field.
+func (m *APIKeyMutation) SetUserID(u uuid.UUID) {
+ m.user = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *APIKeyMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the APIKey entity.
+// If the APIKey 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 *APIKeyMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldUserID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldUserID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldUserID: %w", err)
+ }
+ return oldValue.UserID, nil
+}
+
+// ResetUserID resets all changes to the "user_id" field.
+func (m *APIKeyMutation) ResetUserID() {
+ m.user = nil
+}
+
+// SetName sets the "name" field.
+func (m *APIKeyMutation) SetName(s string) {
+ m.name = &s
+}
+
+// Name returns the value of the "name" field in the mutation.
+func (m *APIKeyMutation) Name() (r string, exists bool) {
+ v := m.name
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldName returns the old "name" field's value of the APIKey entity.
+// If the APIKey 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 *APIKeyMutation) OldName(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldName is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldName requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldName: %w", err)
+ }
+ return oldValue.Name, nil
+}
+
+// ResetName resets all changes to the "name" field.
+func (m *APIKeyMutation) ResetName() {
+ m.name = nil
+}
+
+// SetToken sets the "token" field.
+func (m *APIKeyMutation) SetToken(b []byte) {
+ m.token = &b
+}
+
+// Token returns the value of the "token" field in the mutation.
+func (m *APIKeyMutation) 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 APIKey entity.
+// If the APIKey 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 *APIKeyMutation) 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 *APIKeyMutation) ResetToken() {
+ m.token = nil
+}
+
+// SetExpiresAt sets the "expires_at" field.
+func (m *APIKeyMutation) SetExpiresAt(t time.Time) {
+ m.expires_at = &t
+}
+
+// ExpiresAt returns the value of the "expires_at" field in the mutation.
+func (m *APIKeyMutation) 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 APIKey entity.
+// If the APIKey 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 *APIKeyMutation) 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
+}
+
+// ClearExpiresAt clears the value of the "expires_at" field.
+func (m *APIKeyMutation) ClearExpiresAt() {
+ m.expires_at = nil
+ m.clearedFields[apikey.FieldExpiresAt] = struct{}{}
+}
+
+// ExpiresAtCleared returns if the "expires_at" field was cleared in this mutation.
+func (m *APIKeyMutation) ExpiresAtCleared() bool {
+ _, ok := m.clearedFields[apikey.FieldExpiresAt]
+ return ok
+}
+
+// ResetExpiresAt resets all changes to the "expires_at" field.
+func (m *APIKeyMutation) ResetExpiresAt() {
+ m.expires_at = nil
+ delete(m.clearedFields, apikey.FieldExpiresAt)
+}
+
+// SetLastUsedAt sets the "last_used_at" field.
+func (m *APIKeyMutation) SetLastUsedAt(t time.Time) {
+ m.last_used_at = &t
+}
+
+// LastUsedAt returns the value of the "last_used_at" field in the mutation.
+func (m *APIKeyMutation) LastUsedAt() (r time.Time, exists bool) {
+ v := m.last_used_at
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldLastUsedAt returns the old "last_used_at" field's value of the APIKey entity.
+// If the APIKey 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 *APIKeyMutation) OldLastUsedAt(ctx context.Context) (v *time.Time, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldLastUsedAt is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldLastUsedAt requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldLastUsedAt: %w", err)
+ }
+ return oldValue.LastUsedAt, nil
+}
+
+// ClearLastUsedAt clears the value of the "last_used_at" field.
+func (m *APIKeyMutation) ClearLastUsedAt() {
+ m.last_used_at = nil
+ m.clearedFields[apikey.FieldLastUsedAt] = struct{}{}
+}
+
+// LastUsedAtCleared returns if the "last_used_at" field was cleared in this mutation.
+func (m *APIKeyMutation) LastUsedAtCleared() bool {
+ _, ok := m.clearedFields[apikey.FieldLastUsedAt]
+ return ok
+}
+
+// ResetLastUsedAt resets all changes to the "last_used_at" field.
+func (m *APIKeyMutation) ResetLastUsedAt() {
+ m.last_used_at = nil
+ delete(m.clearedFields, apikey.FieldLastUsedAt)
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (m *APIKeyMutation) ClearUser() {
+ m.cleareduser = true
+ m.clearedFields[apikey.FieldUserID] = struct{}{}
+}
+
+// UserCleared reports if the "user" edge to the User entity was cleared.
+func (m *APIKeyMutation) UserCleared() bool {
+ return m.cleareduser
+}
+
+// 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 *APIKeyMutation) 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 *APIKeyMutation) ResetUser() {
+ m.user = nil
+ m.cleareduser = false
+}
+
+// Where appends a list predicates to the APIKeyMutation builder.
+func (m *APIKeyMutation) Where(ps ...predicate.APIKey) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the APIKeyMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *APIKeyMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.APIKey, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *APIKeyMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *APIKeyMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (APIKey).
+func (m *APIKeyMutation) 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 *APIKeyMutation) Fields() []string {
+ fields := make([]string, 0, 7)
+ if m.created_at != nil {
+ fields = append(fields, apikey.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, apikey.FieldUpdatedAt)
+ }
+ if m.user != nil {
+ fields = append(fields, apikey.FieldUserID)
+ }
+ if m.name != nil {
+ fields = append(fields, apikey.FieldName)
+ }
+ if m.token != nil {
+ fields = append(fields, apikey.FieldToken)
+ }
+ if m.expires_at != nil {
+ fields = append(fields, apikey.FieldExpiresAt)
+ }
+ if m.last_used_at != nil {
+ fields = append(fields, apikey.FieldLastUsedAt)
+ }
+ 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 *APIKeyMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case apikey.FieldCreatedAt:
+ return m.CreatedAt()
+ case apikey.FieldUpdatedAt:
+ return m.UpdatedAt()
+ case apikey.FieldUserID:
+ return m.UserID()
+ case apikey.FieldName:
+ return m.Name()
+ case apikey.FieldToken:
+ return m.Token()
+ case apikey.FieldExpiresAt:
+ return m.ExpiresAt()
+ case apikey.FieldLastUsedAt:
+ return m.LastUsedAt()
+ }
+ 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 *APIKeyMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case apikey.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case apikey.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ case apikey.FieldUserID:
+ return m.OldUserID(ctx)
+ case apikey.FieldName:
+ return m.OldName(ctx)
+ case apikey.FieldToken:
+ return m.OldToken(ctx)
+ case apikey.FieldExpiresAt:
+ return m.OldExpiresAt(ctx)
+ case apikey.FieldLastUsedAt:
+ return m.OldLastUsedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown APIKey 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 *APIKeyMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case apikey.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 apikey.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 apikey.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case apikey.FieldName:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetName(v)
+ return nil
+ case apikey.FieldToken:
+ v, ok := value.([]byte)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetToken(v)
+ return nil
+ case apikey.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 apikey.FieldLastUsedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetLastUsedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown APIKey field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *APIKeyMutation) 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 *APIKeyMutation) 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 *APIKeyMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown APIKey numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *APIKeyMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(apikey.FieldExpiresAt) {
+ fields = append(fields, apikey.FieldExpiresAt)
+ }
+ if m.FieldCleared(apikey.FieldLastUsedAt) {
+ fields = append(fields, apikey.FieldLastUsedAt)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *APIKeyMutation) 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 *APIKeyMutation) ClearField(name string) error {
+ switch name {
+ case apikey.FieldExpiresAt:
+ m.ClearExpiresAt()
+ return nil
+ case apikey.FieldLastUsedAt:
+ m.ClearLastUsedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown APIKey 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 *APIKeyMutation) ResetField(name string) error {
+ switch name {
+ case apikey.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case apikey.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ case apikey.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case apikey.FieldName:
+ m.ResetName()
+ return nil
+ case apikey.FieldToken:
+ m.ResetToken()
+ return nil
+ case apikey.FieldExpiresAt:
+ m.ResetExpiresAt()
+ return nil
+ case apikey.FieldLastUsedAt:
+ m.ResetLastUsedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown APIKey field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *APIKeyMutation) AddedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.user != nil {
+ edges = append(edges, apikey.EdgeUser)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *APIKeyMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case apikey.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 *APIKeyMutation) 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 *APIKeyMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *APIKeyMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.cleareduser {
+ edges = append(edges, apikey.EdgeUser)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *APIKeyMutation) EdgeCleared(name string) bool {
+ switch name {
+ case apikey.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 *APIKeyMutation) ClearEdge(name string) error {
+ switch name {
+ case apikey.EdgeUser:
+ m.ClearUser()
+ return nil
+ }
+ return fmt.Errorf("unknown APIKey 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 *APIKeyMutation) ResetEdge(name string) error {
+ switch name {
+ case apikey.EdgeUser:
+ m.ResetUser()
+ return nil
+ }
+ return fmt.Errorf("unknown APIKey edge %s", name)
+}
+
// AttachmentMutation represents an operation that mutates the Attachment nodes in the graph.
type AttachmentMutation struct {
config
@@ -13069,6 +13822,9 @@ type UserMutation struct {
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
@@ -13835,6 +14591,60 @@ func (m *UserMutation) ResetAuthTokens() {
m.removedauth_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 {
+ m.api_keys = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.api_keys[ids[i]] = struct{}{}
+ }
+}
+
+// ClearAPIKeys clears the "api_keys" edge to the APIKey entity.
+func (m *UserMutation) ClearAPIKeys() {
+ m.clearedapi_keys = true
+}
+
+// APIKeysCleared reports if the "api_keys" edge to the APIKey entity was cleared.
+func (m *UserMutation) APIKeysCleared() bool {
+ return m.clearedapi_keys
+}
+
+// RemoveAPIKeyIDs removes the "api_keys" edge to the APIKey entity by IDs.
+func (m *UserMutation) RemoveAPIKeyIDs(ids ...uuid.UUID) {
+ if m.removedapi_keys == nil {
+ m.removedapi_keys = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.api_keys, ids[i])
+ m.removedapi_keys[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedAPIKeys returns the removed IDs of the "api_keys" edge to the APIKey entity.
+func (m *UserMutation) RemovedAPIKeysIDs() (ids []uuid.UUID) {
+ for id := range m.removedapi_keys {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// APIKeysIDs returns the "api_keys" edge IDs in the mutation.
+func (m *UserMutation) APIKeysIDs() (ids []uuid.UUID) {
+ for id := range m.api_keys {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetAPIKeys resets all changes to the "api_keys" edge.
+func (m *UserMutation) ResetAPIKeys() {
+ m.api_keys = nil
+ m.clearedapi_keys = false
+ m.removedapi_keys = nil
+}
+
// AddNotifierIDs adds the "notifiers" edge to the Notifier entity by ids.
func (m *UserMutation) AddNotifierIDs(ids ...uuid.UUID) {
if m.notifiers == nil {
@@ -14265,13 +15075,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, 3)
+ edges := make([]string, 0, 4)
if m.groups != nil {
edges = append(edges, user.EdgeGroups)
}
if m.auth_tokens != nil {
edges = append(edges, user.EdgeAuthTokens)
}
+ if m.api_keys != nil {
+ edges = append(edges, user.EdgeAPIKeys)
+ }
if m.notifiers != nil {
edges = append(edges, user.EdgeNotifiers)
}
@@ -14294,6 +15107,12 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
+ case user.EdgeAPIKeys:
+ ids := make([]ent.Value, 0, len(m.api_keys))
+ for id := range m.api_keys {
+ ids = append(ids, id)
+ }
+ return ids
case user.EdgeNotifiers:
ids := make([]ent.Value, 0, len(m.notifiers))
for id := range m.notifiers {
@@ -14306,13 +15125,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, 3)
+ edges := make([]string, 0, 4)
if m.removedgroups != nil {
edges = append(edges, user.EdgeGroups)
}
if m.removedauth_tokens != nil {
edges = append(edges, user.EdgeAuthTokens)
}
+ if m.removedapi_keys != nil {
+ edges = append(edges, user.EdgeAPIKeys)
+ }
if m.removednotifiers != nil {
edges = append(edges, user.EdgeNotifiers)
}
@@ -14335,6 +15157,12 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
+ case user.EdgeAPIKeys:
+ ids := make([]ent.Value, 0, len(m.removedapi_keys))
+ for id := range m.removedapi_keys {
+ ids = append(ids, id)
+ }
+ return ids
case user.EdgeNotifiers:
ids := make([]ent.Value, 0, len(m.removednotifiers))
for id := range m.removednotifiers {
@@ -14347,13 +15175,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, 3)
+ edges := make([]string, 0, 4)
if m.clearedgroups {
edges = append(edges, user.EdgeGroups)
}
if m.clearedauth_tokens {
edges = append(edges, user.EdgeAuthTokens)
}
+ if m.clearedapi_keys {
+ edges = append(edges, user.EdgeAPIKeys)
+ }
if m.clearednotifiers {
edges = append(edges, user.EdgeNotifiers)
}
@@ -14368,6 +15199,8 @@ func (m *UserMutation) EdgeCleared(name string) bool {
return m.clearedgroups
case user.EdgeAuthTokens:
return m.clearedauth_tokens
+ case user.EdgeAPIKeys:
+ return m.clearedapi_keys
case user.EdgeNotifiers:
return m.clearednotifiers
}
@@ -14392,6 +15225,9 @@ func (m *UserMutation) ResetEdge(name string) error {
case user.EdgeAuthTokens:
m.ResetAuthTokens()
return nil
+ case user.EdgeAPIKeys:
+ m.ResetAPIKeys()
+ return nil
case user.EdgeNotifiers:
m.ResetNotifiers()
return nil
diff --git a/backend/internal/data/ent/predicate/predicate.go b/backend/internal/data/ent/predicate/predicate.go
index 3a5e59df..c5f8e7af 100644
--- a/backend/internal/data/ent/predicate/predicate.go
+++ b/backend/internal/data/ent/predicate/predicate.go
@@ -6,6 +6,9 @@ import (
"entgo.io/ent/dialect/sql"
)
+// APIKey is the predicate function for apikey builders.
+type APIKey func(*sql.Selector)
+
// Attachment is the predicate function for attachment builders.
type Attachment func(*sql.Selector)
diff --git a/backend/internal/data/ent/runtime.go b/backend/internal/data/ent/runtime.go
index ef6c1bcb..b268e9a8 100644
--- a/backend/internal/data/ent/runtime.go
+++ b/backend/internal/data/ent/runtime.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/entity"
@@ -26,6 +27,43 @@ import (
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
+ apikeyMixin := schema.APIKey{}.Mixin()
+ apikeyMixinFields0 := apikeyMixin[0].Fields()
+ _ = apikeyMixinFields0
+ apikeyFields := schema.APIKey{}.Fields()
+ _ = apikeyFields
+ // apikeyDescCreatedAt is the schema descriptor for created_at field.
+ apikeyDescCreatedAt := apikeyMixinFields0[1].Descriptor()
+ // apikey.DefaultCreatedAt holds the default value on creation for the created_at field.
+ apikey.DefaultCreatedAt = apikeyDescCreatedAt.Default.(func() time.Time)
+ // apikeyDescUpdatedAt is the schema descriptor for updated_at field.
+ apikeyDescUpdatedAt := apikeyMixinFields0[2].Descriptor()
+ // apikey.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ apikey.DefaultUpdatedAt = apikeyDescUpdatedAt.Default.(func() time.Time)
+ // apikey.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ apikey.UpdateDefaultUpdatedAt = apikeyDescUpdatedAt.UpdateDefault.(func() time.Time)
+ // apikeyDescName is the schema descriptor for name field.
+ apikeyDescName := apikeyFields[0].Descriptor()
+ // apikey.NameValidator is a validator for the "name" field. It is called by the builders before save.
+ apikey.NameValidator = func() func(string) error {
+ validators := apikeyDescName.Validators
+ fns := [...]func(string) error{
+ validators[0].(func(string) error),
+ validators[1].(func(string) error),
+ }
+ return func(name string) error {
+ for _, fn := range fns {
+ if err := fn(name); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ }()
+ // apikeyDescID is the schema descriptor for id field.
+ apikeyDescID := apikeyMixinFields0[0].Descriptor()
+ // apikey.DefaultID holds the default value on creation for the id field.
+ apikey.DefaultID = apikeyDescID.Default.(func() uuid.UUID)
attachmentMixin := schema.Attachment{}.Mixin()
attachmentMixinFields0 := attachmentMixin[0].Fields()
_ = attachmentMixinFields0
diff --git a/backend/internal/data/ent/schema/api_key.go b/backend/internal/data/ent/schema/api_key.go
new file mode 100644
index 00000000..99c7f4c7
--- /dev/null
+++ b/backend/internal/data/ent/schema/api_key.go
@@ -0,0 +1,48 @@
+package schema
+
+import (
+ "entgo.io/ent"
+ "entgo.io/ent/schema/field"
+ "entgo.io/ent/schema/index"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/schema/mixins"
+)
+
+// APIKey holds the schema definition for static, user-issued API keys that
+// authenticate as the owning user.
+type APIKey struct {
+ ent.Schema
+}
+
+func (APIKey) Mixin() []ent.Mixin {
+ return []ent.Mixin{
+ mixins.BaseMixin{},
+ UserMixin{
+ ref: "api_keys",
+ field: "user_id",
+ },
+ }
+}
+
+func (APIKey) Fields() []ent.Field {
+ return []ent.Field{
+ field.String("name").
+ MaxLen(255).
+ NotEmpty(),
+ field.Bytes("token").
+ Unique().
+ Sensitive(),
+ field.Time("expires_at").
+ Optional().
+ Nillable(),
+ field.Time("last_used_at").
+ Optional().
+ Nillable(),
+ }
+}
+
+func (APIKey) Indexes() []ent.Index {
+ return []ent.Index{
+ index.Fields("token"),
+ index.Fields("user_id"),
+ }
+}
diff --git a/backend/internal/data/ent/schema/user.go b/backend/internal/data/ent/schema/user.go
index 32daa88e..567b6629 100644
--- a/backend/internal/data/ent/schema/user.go
+++ b/backend/internal/data/ent/schema/user.go
@@ -76,6 +76,10 @@ func (User) Edges() []ent.Edge {
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
+ edge.To("api_keys", APIKey.Type).
+ Annotations(entsql.Annotation{
+ OnDelete: entsql.Cascade,
+ }),
edge.To("notifiers", Notifier.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
diff --git a/backend/internal/data/ent/tx.go b/backend/internal/data/ent/tx.go
index 1648548c..c9559986 100644
--- a/backend/internal/data/ent/tx.go
+++ b/backend/internal/data/ent/tx.go
@@ -12,6 +12,8 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
+ // APIKey is the client for interacting with the APIKey builders.
+ APIKey *APIKeyClient
// Attachment is the client for interacting with the Attachment builders.
Attachment *AttachmentClient
// AuthRoles is the client for interacting with the AuthRoles builders.
@@ -171,6 +173,7 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
+ tx.APIKey = NewAPIKeyClient(tx.config)
tx.Attachment = NewAttachmentClient(tx.config)
tx.AuthRoles = NewAuthRolesClient(tx.config)
tx.AuthTokens = NewAuthTokensClient(tx.config)
@@ -194,7 +197,7 @@ func (tx *Tx) init() {
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
-// applies a query, for example: Attachment.QueryXXX(), the query will be executed
+// applies a query, for example: APIKey.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
diff --git a/backend/internal/data/ent/user.go b/backend/internal/data/ent/user.go
index d2ea0069..f78121f0 100644
--- a/backend/internal/data/ent/user.go
+++ b/backend/internal/data/ent/user.go
@@ -57,11 +57,13 @@ type UserEdges struct {
Groups []*Group `json:"groups,omitempty"`
// AuthTokens holds the value of the auth_tokens edge.
AuthTokens []*AuthTokens `json:"auth_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.
Notifiers []*Notifier `json:"notifiers,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
- loadedTypes [3]bool
+ loadedTypes [4]bool
}
// GroupsOrErr returns the Groups value or an error if the edge
@@ -82,10 +84,19 @@ func (e UserEdges) AuthTokensOrErr() ([]*AuthTokens, error) {
return nil, &NotLoadedError{edge: "auth_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] {
+ return e.APIKeys, nil
+ }
+ return nil, &NotLoadedError{edge: "api_keys"}
+}
+
// 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[2] {
+ if e.loadedTypes[3] {
return e.Notifiers, nil
}
return nil, &NotLoadedError{edge: "notifiers"}
@@ -236,6 +247,11 @@ func (_m *User) QueryAuthTokens() *AuthTokensQuery {
return NewUserClient(_m.config).QueryAuthTokens(_m)
}
+// QueryAPIKeys queries the "api_keys" edge of the User entity.
+func (_m *User) QueryAPIKeys() *APIKeyQuery {
+ return NewUserClient(_m.config).QueryAPIKeys(_m)
+}
+
// QueryNotifiers queries the "notifiers" edge of the User entity.
func (_m *User) QueryNotifiers() *NotifierQuery {
return NewUserClient(_m.config).QueryNotifiers(_m)
diff --git a/backend/internal/data/ent/user/user.go b/backend/internal/data/ent/user/user.go
index 53eb866f..97a5e716 100644
--- a/backend/internal/data/ent/user/user.go
+++ b/backend/internal/data/ent/user/user.go
@@ -46,6 +46,8 @@ const (
EdgeGroups = "groups"
// EdgeAuthTokens holds the string denoting the auth_tokens edge name in mutations.
EdgeAuthTokens = "auth_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.
EdgeNotifiers = "notifiers"
// Table holds the table name of the user in the database.
@@ -62,6 +64,13 @@ const (
AuthTokensInverseTable = "auth_tokens"
// AuthTokensColumn is the table column denoting the auth_tokens relation/edge.
AuthTokensColumn = "user_auth_tokens"
+ // APIKeysTable is the table that holds the api_keys relation/edge.
+ APIKeysTable = "api_keys"
+ // APIKeysInverseTable is the table name for the APIKey entity.
+ // It exists in this package in order to avoid circular dependency with the "apikey" package.
+ APIKeysInverseTable = "api_keys"
+ // APIKeysColumn is the table column denoting the api_keys relation/edge.
+ APIKeysColumn = "user_id"
// NotifiersTable is the table that holds the notifiers relation/edge.
NotifiersTable = "notifiers"
// NotifiersInverseTable is the table name for the Notifier entity.
@@ -248,6 +257,20 @@ func ByAuthTokens(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
}
}
+// ByAPIKeysCount orders the results by api_keys count.
+func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newAPIKeysStep(), opts...)
+ }
+}
+
+// ByAPIKeys orders the results by api_keys terms.
+func ByAPIKeys(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newAPIKeysStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+
// ByNotifiersCount orders the results by notifiers count.
func ByNotifiersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -275,6 +298,13 @@ func newAuthTokensStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, AuthTokensTable, AuthTokensColumn),
)
}
+func newAPIKeysStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(APIKeysInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
+ )
+}
func newNotifiersStep() *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.go
index fb31d18b..66209ae8 100644
--- a/backend/internal/data/ent/user/where.go
+++ b/backend/internal/data/ent/user/where.go
@@ -742,6 +742,29 @@ func HasAuthTokensWith(preds ...predicate.AuthTokens) predicate.User {
})
}
+// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
+func HasAPIKeys() predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasAPIKeysWith applies the HasEdge predicate on the "api_keys" edge with a given conditions (other predicates).
+func HasAPIKeysWith(preds ...predicate.APIKey) predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := newAPIKeysStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
// HasNotifiers applies the HasEdge predicate on the "notifiers" edge.
func HasNotifiers() 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.go
index 0248479e..e108a076 100644
--- a/backend/internal/data/ent/user_create.go
+++ b/backend/internal/data/ent/user_create.go
@@ -11,6 +11,7 @@ import (
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"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"
@@ -226,6 +227,21 @@ func (_c *UserCreate) AddAuthTokens(v ...*AuthTokens) *UserCreate {
return _c.AddAuthTokenIDs(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...)
+ return _c
+}
+
+// AddAPIKeys adds the "api_keys" edges to the APIKey entity.
+func (_c *UserCreate) AddAPIKeys(v ...*APIKey) *UserCreate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _c.AddAPIKeyIDs(ids...)
+}
+
// AddNotifierIDs adds the "notifiers" edge to the Notifier entity by IDs.
func (_c *UserCreate) AddNotifierIDs(ids ...uuid.UUID) *UserCreate {
_c.mutation.AddNotifierIDs(ids...)
@@ -464,6 +480,22 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
}
_spec.Edges = append(_spec.Edges, edge)
}
+ if nodes := _c.mutation.APIKeysIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.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.NotifiersIDs(); 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.go
index 95600062..12b3a3e7 100644
--- a/backend/internal/data/ent/user_query.go
+++ b/backend/internal/data/ent/user_query.go
@@ -13,6 +13,7 @@ import (
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"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"
@@ -29,6 +30,7 @@ type UserQuery struct {
predicates []predicate.User
withGroups *GroupQuery
withAuthTokens *AuthTokensQuery
+ withAPIKeys *APIKeyQuery
withNotifiers *NotifierQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
@@ -110,6 +112,28 @@ func (_q *UserQuery) QueryAuthTokens() *AuthTokensQuery {
return query
}
+// QueryAPIKeys chains the current query on the "api_keys" edge.
+func (_q *UserQuery) QueryAPIKeys() *APIKeyQuery {
+ query := (&APIKeyClient{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(apikey.Table, apikey.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.APIKeysTable, user.APIKeysColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
// QueryNotifiers chains the current query on the "notifiers" edge.
func (_q *UserQuery) QueryNotifiers() *NotifierQuery {
query := (&NotifierClient{config: _q.config}).Query()
@@ -326,6 +350,7 @@ func (_q *UserQuery) Clone() *UserQuery {
predicates: append([]predicate.User{}, _q.predicates...),
withGroups: _q.withGroups.Clone(),
withAuthTokens: _q.withAuthTokens.Clone(),
+ withAPIKeys: _q.withAPIKeys.Clone(),
withNotifiers: _q.withNotifiers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
@@ -355,6 +380,17 @@ func (_q *UserQuery) WithAuthTokens(opts ...func(*AuthTokensQuery)) *UserQuery {
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 {
+ query := (&APIKeyClient{config: _q.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ _q.withAPIKeys = query
+ return _q
+}
+
// WithNotifiers tells the query-builder to eager-load the nodes that are connected to
// the "notifiers" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithNotifiers(opts ...func(*NotifierQuery)) *UserQuery {
@@ -444,9 +480,10 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
var (
nodes = []*User{}
_spec = _q.querySpec()
- loadedTypes = [3]bool{
+ loadedTypes = [4]bool{
_q.withGroups != nil,
_q.withAuthTokens != nil,
+ _q.withAPIKeys != nil,
_q.withNotifiers != nil,
}
)
@@ -482,6 +519,13 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
return nil, err
}
}
+ if query := _q.withAPIKeys; query != nil {
+ if err := _q.loadAPIKeys(ctx, query, nodes,
+ func(n *User) { n.Edges.APIKeys = []*APIKey{} },
+ func(n *User, e *APIKey) { n.Edges.APIKeys = append(n.Edges.APIKeys, e) }); err != nil {
+ return nil, err
+ }
+ }
if query := _q.withNotifiers; query != nil {
if err := _q.loadNotifiers(ctx, query, nodes,
func(n *User) { n.Edges.Notifiers = []*Notifier{} },
@@ -584,6 +628,36 @@ func (_q *UserQuery) loadAuthTokens(ctx context.Context, query *AuthTokensQuery,
}
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)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(apikey.FieldUserID)
+ }
+ query.Where(predicate.APIKey(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(user.APIKeysColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.UserID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
func (_q *UserQuery) loadNotifiers(ctx context.Context, query *NotifierQuery, nodes []*User, init func(*User), assign func(*User, *Notifier)) 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.go
index 8b3361ff..80dcb8bf 100644
--- a/backend/internal/data/ent/user_update.go
+++ b/backend/internal/data/ent/user_update.go
@@ -12,6 +12,7 @@ import (
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
"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"
@@ -250,6 +251,21 @@ func (_u *UserUpdate) AddAuthTokens(v ...*AuthTokens) *UserUpdate {
return _u.AddAuthTokenIDs(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...)
+ return _u
+}
+
+// AddAPIKeys adds the "api_keys" edges to the APIKey entity.
+func (_u *UserUpdate) AddAPIKeys(v ...*APIKey) *UserUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddAPIKeyIDs(ids...)
+}
+
// AddNotifierIDs adds the "notifiers" edge to the Notifier entity by IDs.
func (_u *UserUpdate) AddNotifierIDs(ids ...uuid.UUID) *UserUpdate {
_u.mutation.AddNotifierIDs(ids...)
@@ -312,6 +328,27 @@ func (_u *UserUpdate) RemoveAuthTokens(v ...*AuthTokens) *UserUpdate {
return _u.RemoveAuthTokenIDs(ids...)
}
+// ClearAPIKeys clears all "api_keys" edges to the APIKey entity.
+func (_u *UserUpdate) ClearAPIKeys() *UserUpdate {
+ _u.mutation.ClearAPIKeys()
+ return _u
+}
+
+// RemoveAPIKeyIDs removes the "api_keys" edge to APIKey entities by IDs.
+func (_u *UserUpdate) RemoveAPIKeyIDs(ids ...uuid.UUID) *UserUpdate {
+ _u.mutation.RemoveAPIKeyIDs(ids...)
+ return _u
+}
+
+// RemoveAPIKeys removes "api_keys" edges to APIKey entities.
+func (_u *UserUpdate) RemoveAPIKeys(v ...*APIKey) *UserUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveAPIKeyIDs(ids...)
+}
+
// ClearNotifiers clears all "notifiers" edges to the Notifier entity.
func (_u *UserUpdate) ClearNotifiers() *UserUpdate {
_u.mutation.ClearNotifiers()
@@ -550,6 +587,51 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.APIKeysCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedAPIKeysIDs(); len(nodes) > 0 && !_u.mutation.APIKeysCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.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.APIKeysIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.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.NotifiersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -833,6 +915,21 @@ func (_u *UserUpdateOne) AddAuthTokens(v ...*AuthTokens) *UserUpdateOne {
return _u.AddAuthTokenIDs(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...)
+ return _u
+}
+
+// AddAPIKeys adds the "api_keys" edges to the APIKey entity.
+func (_u *UserUpdateOne) AddAPIKeys(v ...*APIKey) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddAPIKeyIDs(ids...)
+}
+
// AddNotifierIDs adds the "notifiers" edge to the Notifier entity by IDs.
func (_u *UserUpdateOne) AddNotifierIDs(ids ...uuid.UUID) *UserUpdateOne {
_u.mutation.AddNotifierIDs(ids...)
@@ -895,6 +992,27 @@ func (_u *UserUpdateOne) RemoveAuthTokens(v ...*AuthTokens) *UserUpdateOne {
return _u.RemoveAuthTokenIDs(ids...)
}
+// ClearAPIKeys clears all "api_keys" edges to the APIKey entity.
+func (_u *UserUpdateOne) ClearAPIKeys() *UserUpdateOne {
+ _u.mutation.ClearAPIKeys()
+ return _u
+}
+
+// RemoveAPIKeyIDs removes the "api_keys" edge to APIKey entities by IDs.
+func (_u *UserUpdateOne) RemoveAPIKeyIDs(ids ...uuid.UUID) *UserUpdateOne {
+ _u.mutation.RemoveAPIKeyIDs(ids...)
+ return _u
+}
+
+// RemoveAPIKeys removes "api_keys" edges to APIKey entities.
+func (_u *UserUpdateOne) RemoveAPIKeys(v ...*APIKey) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveAPIKeyIDs(ids...)
+}
+
// ClearNotifiers clears all "notifiers" edges to the Notifier entity.
func (_u *UserUpdateOne) ClearNotifiers() *UserUpdateOne {
_u.mutation.ClearNotifiers()
@@ -1163,6 +1281,51 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
+ if _u.mutation.APIKeysCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedAPIKeysIDs(); len(nodes) > 0 && !_u.mutation.APIKeysCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.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.APIKeysIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.APIKeysTable,
+ Columns: []string{user.APIKeysColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(apikey.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.NotifiersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
diff --git a/backend/internal/data/migrations/postgres/20260510000000_add_api_keys.sql b/backend/internal/data/migrations/postgres/20260510000000_add_api_keys.sql
new file mode 100644
index 00000000..9715dd67
--- /dev/null
+++ b/backend/internal/data/migrations/postgres/20260510000000_add_api_keys.sql
@@ -0,0 +1,22 @@
+-- +goose Up
+-- Add static, user-scoped API keys. Each key authenticates as the owning
+-- user and grants the same access. Tokens are stored hashed (sha256) and
+-- never persisted in plaintext.
+CREATE TABLE IF NOT EXISTS "api_keys" (
+ "id" uuid NOT NULL,
+ "created_at" timestamptz NOT NULL,
+ "updated_at" timestamptz NOT NULL,
+ "user_id" uuid NOT NULL,
+ "name" character varying NOT NULL,
+ "token" bytea NOT NULL,
+ "expires_at" timestamptz NULL,
+ "last_used_at" timestamptz NULL,
+ PRIMARY KEY ("id"),
+ CONSTRAINT "api_keys_users_api_keys" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON UPDATE NO ACTION ON DELETE CASCADE
+);
+CREATE UNIQUE INDEX IF NOT EXISTS "api_keys_token_key" ON "api_keys" ("token");
+CREATE INDEX IF NOT EXISTS "apikey_token" ON "api_keys" ("token");
+CREATE INDEX IF NOT EXISTS "apikey_user_id" ON "api_keys" ("user_id");
+
+-- +goose Down
+DROP TABLE IF EXISTS "api_keys";
diff --git a/backend/internal/data/migrations/sqlite3/20260510000000_add_api_keys.sql b/backend/internal/data/migrations/sqlite3/20260510000000_add_api_keys.sql
new file mode 100644
index 00000000..9dbb8975
--- /dev/null
+++ b/backend/internal/data/migrations/sqlite3/20260510000000_add_api_keys.sql
@@ -0,0 +1,31 @@
+-- +goose Up
+-- Add static, user-scoped API keys. Each key authenticates as the owning
+-- user and grants the same access. Tokens are stored hashed (sha256) and
+-- never persisted in plaintext.
+create table if not exists api_keys
+(
+ id uuid not null
+ primary key,
+ created_at datetime not null,
+ updated_at datetime not null,
+ user_id uuid not null
+ constraint api_keys_users_api_keys
+ references users
+ on delete cascade,
+ name text not null,
+ token blob not null,
+ expires_at datetime,
+ last_used_at datetime
+);
+
+create unique index if not exists api_keys_token_key
+ on api_keys (token);
+
+create index if not exists apikey_token
+ on api_keys (token);
+
+create index if not exists apikey_user_id
+ on api_keys (user_id);
+
+-- +goose Down
+drop table if exists api_keys;
diff --git a/backend/internal/data/repo/repo_api_keys.go b/backend/internal/data/repo/repo_api_keys.go
new file mode 100644
index 00000000..7886829f
--- /dev/null
+++ b/backend/internal/data/repo/repo_api_keys.go
@@ -0,0 +1,184 @@
+package repo
+
+import (
+ "context"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/apikey"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
+)
+
+type APIKeyRepository struct {
+ db *ent.Client
+ mapper MapFunc[*ent.APIKey, APIKeyOut]
+}
+
+func NewAPIKeyRepository(db *ent.Client) *APIKeyRepository {
+ return &APIKeyRepository{
+ db: db,
+ mapper: func(k *ent.APIKey) APIKeyOut {
+ return APIKeyOut{
+ ID: k.ID,
+ UserID: k.UserID,
+ Name: k.Name,
+ CreatedAt: k.CreatedAt,
+ ExpiresAt: k.ExpiresAt,
+ LastUsedAt: k.LastUsedAt,
+ }
+ },
+ }
+}
+
+type (
+ APIKeyCreate struct {
+ Name string `json:"name" validate:"required,min=1,max=255"`
+ ExpiresAt *time.Time `json:"expiresAt" extensions:"x-nullable"`
+ }
+
+ // APIKeyOut is the metadata of an API key, returned for list views. The raw
+ // token is never included here — see APIKeyCreatedOut for that.
+ APIKeyOut struct {
+ ID uuid.UUID `json:"id"`
+ UserID uuid.UUID `json:"userId"`
+ Name string `json:"name"`
+ CreatedAt time.Time `json:"createdAt"`
+ ExpiresAt *time.Time `json:"expiresAt" extensions:"x-nullable"`
+ LastUsedAt *time.Time `json:"lastUsedAt" extensions:"x-nullable"`
+ }
+
+ // APIKeyCreatedOut is returned exactly once at creation time and contains
+ // the raw token. After this response the raw token is unrecoverable.
+ APIKeyCreatedOut struct {
+ APIKeyOut
+ Token string `json:"token"`
+ }
+)
+
+// Create persists a new API key for the given user. The caller supplies the
+// pre-hashed token bytes; the raw token is never stored.
+func (r *APIKeyRepository) Create(ctx context.Context, userID uuid.UUID, name string, tokenHash []byte, expiresAt *time.Time) (APIKeyOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.APIKeyRepository.Create",
+ trace.WithAttributes(
+ attribute.String("user.id", userID.String()),
+ attribute.Int("api_key.name.length", len(name)),
+ attribute.Bool("api_key.has_expiration", expiresAt != nil),
+ ))
+ defer span.End()
+
+ q := r.db.APIKey.Create().
+ SetUserID(userID).
+ SetName(name).
+ SetToken(tokenHash)
+
+ if expiresAt != nil {
+ q.SetExpiresAt(*expiresAt)
+ }
+
+ key, err := q.Save(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ return APIKeyOut{}, err
+ }
+ span.SetAttributes(attribute.String("api_key.id", key.ID.String()))
+ return r.mapper.Map(key), nil
+}
+
+// GetUserFromToken returns the user that owns the API key with the given hash,
+// if it exists and has not expired. The matching key's ID is returned so that
+// the caller can update last_used_at.
+func (r *APIKeyRepository) GetUserFromToken(ctx context.Context, tokenHash []byte) (UserOut, uuid.UUID, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.APIKeyRepository.GetUserFromToken",
+ trace.WithAttributes(attribute.Int("token.hash.length", len(tokenHash))))
+ defer span.End()
+
+ key, err := r.db.APIKey.Query().
+ Where(apikey.Token(tokenHash)).
+ WithUser(func(uq *ent.UserQuery) {
+ uq.WithGroups()
+ }).
+ Only(ctx)
+ if err != nil {
+ span.SetAttributes(
+ attribute.Bool("api_key.found", false),
+ attribute.Bool("api_key.lookup.not_found", ent.IsNotFound(err)),
+ )
+ if !ent.IsNotFound(err) {
+ recordSpanError(span, err)
+ }
+ return UserOut{}, uuid.Nil, err
+ }
+
+ if key.ExpiresAt != nil && key.ExpiresAt.Before(time.Now()) {
+ span.SetAttributes(
+ attribute.Bool("api_key.found", true),
+ attribute.Bool("api_key.expired", true),
+ )
+ return UserOut{}, uuid.Nil, &ent.NotFoundError{}
+ }
+
+ out := mapUserOut(key.Edges.User)
+ span.SetAttributes(
+ attribute.Bool("api_key.found", true),
+ attribute.String("api_key.id", key.ID.String()),
+ )
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, key.ID, nil
+}
+
+// TouchLastUsed updates the last_used_at timestamp on the given API key.
+// Failures are best-effort: callers should log but not abort the request.
+func (r *APIKeyRepository) TouchLastUsed(ctx context.Context, id uuid.UUID, at time.Time) error {
+ ctx, span := entityTracer().Start(ctx, "repo.APIKeyRepository.TouchLastUsed",
+ trace.WithAttributes(attribute.String("api_key.id", id.String())))
+ defer span.End()
+
+ err := r.db.APIKey.UpdateOneID(id).SetLastUsedAt(at).Exec(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ }
+ return err
+}
+
+func (r *APIKeyRepository) GetByUser(ctx context.Context, userID uuid.UUID) ([]APIKeyOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.APIKeyRepository.GetByUser",
+ trace.WithAttributes(attribute.String("user.id", userID.String())))
+ defer span.End()
+
+ keys, err := r.db.APIKey.Query().
+ Where(apikey.UserID(userID)).
+ Order(ent.Desc(apikey.FieldCreatedAt)).
+ All(ctx)
+
+ out, err := r.mapper.MapEachErr(keys, err)
+ if err != nil {
+ recordSpanError(span, err)
+ return nil, err
+ }
+ span.SetAttributes(attribute.Int("api_keys.count", len(out)))
+ return out, nil
+}
+
+func (r *APIKeyRepository) Delete(ctx context.Context, userID, id uuid.UUID) error {
+ ctx, span := entityTracer().Start(ctx, "repo.APIKeyRepository.Delete",
+ trace.WithAttributes(
+ attribute.String("user.id", userID.String()),
+ attribute.String("api_key.id", id.String()),
+ ))
+ defer span.End()
+
+ deleted, err := r.db.APIKey.Delete().
+ Where(apikey.UserID(userID), apikey.ID(id)).
+ Exec(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ return err
+ }
+ span.SetAttributes(attribute.Int("api_keys.deleted.count", deleted))
+ if deleted == 0 {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
diff --git a/backend/internal/data/repo/repos_all.go b/backend/internal/data/repo/repos_all.go
index b2e08a2d..b28881c6 100644
--- a/backend/internal/data/repo/repos_all.go
+++ b/backend/internal/data/repo/repos_all.go
@@ -11,6 +11,7 @@ import (
type AllRepos struct {
Users *UserRepository
AuthTokens *TokenRepository
+ APIKeys *APIKeyRepository
Groups *GroupRepository
Entities *EntityRepository
EntityTypes *EntityTypeRepository
@@ -26,6 +27,7 @@ func New(db *ent.Client, bus *eventbus.EventBus, storage config.Storage, pubSubC
return &AllRepos{
Users: &UserRepository{db},
AuthTokens: &TokenRepository{db},
+ APIKeys: NewAPIKeyRepository(db),
Groups: NewGroupRepository(db),
Entities: &EntityRepository{db, bus, attachments},
EntityTypes: &EntityTypeRepository{db, bus},
diff --git a/backend/pkgs/hasher/token.go b/backend/pkgs/hasher/token.go
index d8e3d8d9..e11c7ad3 100644
--- a/backend/pkgs/hasher/token.go
+++ b/backend/pkgs/hasher/token.go
@@ -5,10 +5,15 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/base32"
+ "encoding/base64"
"go.opentelemetry.io/otel/attribute"
)
+// APIKeyPrefix is prepended to every static API key so they can be identified
+// at a glance (e.g. in logs or secret scanners).
+const APIKeyPrefix = "hb_"
+
type Token struct {
Raw string
Hash []byte
@@ -46,3 +51,31 @@ func HashToken(plainTextToken string) []byte {
hash := sha256.Sum256([]byte(plainTextToken))
return hash[:]
}
+
+// GenerateAPIKey produces a static API key with 256 bits of entropy and a
+// recognizable prefix. The format is `hb_<base64url(32 bytes)>` — long enough
+// to discourage guessing, mixed-case + symbols for visual distinctness from
+// short session tokens, and identifiable by secret-scanning tools.
+func GenerateAPIKey() Token {
+ return GenerateAPIKeyCtx(context.Background())
+}
+
+func GenerateAPIKeyCtx(ctx context.Context) Token {
+ _, span := hasherTracer().Start(ctx, "hasher.GenerateAPIKey")
+ defer span.End()
+
+ randomBytes := make([]byte, 32)
+ _, _ = rand.Read(randomBytes)
+
+ plainText := APIKeyPrefix + base64.RawURLEncoding.EncodeToString(randomBytes)
+ hash := HashToken(plainText)
+
+ span.SetAttributes(
+ attribute.Int("token.raw.length", len(plainText)),
+ attribute.Int("token.hash.length", len(hash)),
+ )
+ return Token{
+ Raw: plainText,
+ Hash: hash,
+ }
+}
diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.json
index 6df20892..f3a2ab32 100644
--- a/docs/public/api/openapi-3.0.json
+++ b/docs/public/api/openapi-3.0.json
@@ -2944,6 +2944,97 @@
}
}
},
+ "/v1/users/self/api-keys": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "List API Keys",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.APIKeyOut"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Create API Key",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.APIKeyCreate"
+ }
+ }
+ },
+ "description": "API Key Data",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.APIKeyCreatedOut"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/v1/users/self/api-keys/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Delete API Key",
+ "parameters": [
+ {
+ "description": "API Key ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/users/self/settings": {
"get": {
"security": [
@@ -3102,6 +3193,60 @@
}
}
},
+ "ent.APIKey": {
+ "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 APIKeyQuery when eager-loading is set.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ent.APIKeyEdges"
+ }
+ ]
+ },
+ "expires_at": {
+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",
+ "type": "string"
+ },
+ "id": {
+ "description": "ID of the ent.",
+ "type": "string"
+ },
+ "last_used_at": {
+ "description": "LastUsedAt holds the value of the \"last_used_at\" field.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name holds the value of the \"name\" field.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",
+ "type": "string"
+ },
+ "user_id": {
+ "description": "UserID holds the value of the \"user_id\" field.",
+ "type": "string"
+ }
+ }
+ },
+ "ent.APIKeyEdges": {
+ "type": "object",
+ "properties": {
+ "user": {
+ "description": "User holds the value of the user edge.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ent.User"
+ }
+ ]
+ }
+ }
+ },
"ent.Attachment": {
"type": "object",
"properties": {
@@ -4182,6 +4327,13 @@
"ent.UserEdges": {
"type": "object",
"properties": {
+ "api_keys": {
+ "description": "APIKeys holds the value of the api_keys edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ent.APIKey"
+ }
+ },
"auth_tokens": {
"description": "AuthTokens holds the value of the auth_tokens edge.",
"type": "array",
@@ -4220,6 +4372,76 @@
"TypeTime"
]
},
+ "repo.APIKeyCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ }
+ }
+ },
+ "repo.APIKeyCreatedOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
+ "repo.APIKeyOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"repo.BarcodeProduct": {
"type": "object",
"properties": {
diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yaml
index 4c7fd14f..868713ae 100644
--- a/docs/public/api/openapi-3.0.yaml
+++ b/docs/public/api/openapi-3.0.yaml
@@ -1744,6 +1744,59 @@ paths:
responses:
"204":
description: No Content
+ /v1/users/self/api-keys:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: List API Keys
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.APIKeyOut"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: Create API Key
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.APIKeyCreate"
+ description: API Key Data
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.APIKeyCreatedOut"
+ "/v1/users/self/api-keys/{id}":
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - User
+ summary: Delete API Key
+ parameters:
+ - description: API Key ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
/v1/users/self/settings:
get:
security:
@@ -1844,6 +1897,44 @@ components:
type: string
symbol:
type: string
+ ent.APIKey:
+ 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 APIKeyQuery when eager-loading is set.
+ allOf:
+ - $ref: "#/components/schemas/ent.APIKeyEdges"
+ expires_at:
+ description: ExpiresAt holds the value of the "expires_at" field.
+ type: string
+ id:
+ description: ID of the ent.
+ type: string
+ last_used_at:
+ description: LastUsedAt holds the value of the "last_used_at" field.
+ type: string
+ name:
+ description: Name holds the value of the "name" field.
+ type: string
+ updated_at:
+ description: UpdatedAt holds the value of the "updated_at" field.
+ type: string
+ user_id:
+ description: UserID holds the value of the "user_id" field.
+ type: string
+ ent.APIKeyEdges:
+ type: object
+ properties:
+ user:
+ description: User holds the value of the user edge.
+ allOf:
+ - $ref: "#/components/schemas/ent.User"
ent.Attachment:
type: object
properties:
@@ -2600,6 +2691,11 @@ components:
ent.UserEdges:
type: object
properties:
+ api_keys:
+ description: APIKeys holds the value of the api_keys edge.
+ type: array
+ items:
+ $ref: "#/components/schemas/ent.APIKey"
auth_tokens:
description: AuthTokens holds the value of the auth_tokens edge.
type: array
@@ -2627,6 +2723,54 @@ components:
- TypeNumber
- TypeBoolean
- TypeTime
+ repo.APIKeyCreate:
+ type: object
+ required:
+ - name
+ properties:
+ expiresAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ maxLength: 255
+ minLength: 1
+ repo.APIKeyCreatedOut:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ token:
+ type: string
+ userId:
+ type: string
+ repo.APIKeyOut:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ nullable: true
+ name:
+ type: string
+ userId:
+ type: string
repo.BarcodeProduct:
type: object
properties:
diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.json
index 03988e58..c6b0d506 100644
--- a/docs/public/api/swagger-2.0.json
+++ b/docs/public/api/swagger-2.0.json
@@ -2757,6 +2757,93 @@
}
}
},
+ "/v1/users/self/api-keys": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "List API Keys",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.APIKeyOut"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Create API Key",
+ "parameters": [
+ {
+ "description": "API Key Data",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreate"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.APIKeyCreatedOut"
+ }
+ }
+ }
+ }
+ },
+ "/v1/users/self/api-keys/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "Delete API Key",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "API Key ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/users/self/settings": {
"get": {
"security": [
@@ -2899,6 +2986,60 @@
}
}
},
+ "ent.APIKey": {
+ "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 APIKeyQuery when eager-loading is set.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.APIKeyEdges"
+ }
+ ]
+ },
+ "expires_at": {
+ "description": "ExpiresAt holds the value of the \"expires_at\" field.",
+ "type": "string"
+ },
+ "id": {
+ "description": "ID of the ent.",
+ "type": "string"
+ },
+ "last_used_at": {
+ "description": "LastUsedAt holds the value of the \"last_used_at\" field.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Name holds the value of the \"name\" field.",
+ "type": "string"
+ },
+ "updated_at": {
+ "description": "UpdatedAt holds the value of the \"updated_at\" field.",
+ "type": "string"
+ },
+ "user_id": {
+ "description": "UserID holds the value of the \"user_id\" field.",
+ "type": "string"
+ }
+ }
+ },
+ "ent.APIKeyEdges": {
+ "type": "object",
+ "properties": {
+ "user": {
+ "description": "User holds the value of the user edge.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/ent.User"
+ }
+ ]
+ }
+ }
+ },
"ent.Attachment": {
"type": "object",
"properties": {
@@ -3979,6 +4120,13 @@
"ent.UserEdges": {
"type": "object",
"properties": {
+ "api_keys": {
+ "description": "APIKeys holds the value of the api_keys edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.APIKey"
+ }
+ },
"auth_tokens": {
"description": "AuthTokens holds the value of the auth_tokens edge.",
"type": "array",
@@ -4017,6 +4165,76 @@
"TypeTime"
]
},
+ "repo.APIKeyCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1
+ }
+ }
+ },
+ "repo.APIKeyCreatedOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
+ "repo.APIKeyOut": {
+ "type": "object",
+ "properties": {
+ "createdAt": {
+ "type": "string"
+ },
+ "expiresAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "id": {
+ "type": "string"
+ },
+ "lastUsedAt": {
+ "type": "string",
+ "x-nullable": true
+ },
+ "name": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"repo.BarcodeProduct": {
"type": "object",
"properties": {
diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yaml
index a94de2f1..decc84da 100644
--- a/docs/public/api/swagger-2.0.yaml
+++ b/docs/public/api/swagger-2.0.yaml
@@ -43,6 +43,43 @@ definitions:
symbol:
type: string
type: object
+ ent.APIKey:
+ properties:
+ created_at:
+ description: CreatedAt holds the value of the "created_at" field.
+ type: string
+ edges:
+ allOf:
+ - $ref: '#/definitions/ent.APIKeyEdges'
+ description: |-
+ Edges holds the relations/edges for other nodes in the graph.
+ The values are being populated by the APIKeyQuery 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
+ last_used_at:
+ description: LastUsedAt holds the value of the "last_used_at" field.
+ type: string
+ name:
+ description: Name holds the value of the "name" field.
+ type: string
+ updated_at:
+ description: UpdatedAt holds the value of the "updated_at" field.
+ type: string
+ user_id:
+ description: UserID holds the value of the "user_id" field.
+ type: string
+ type: object
+ ent.APIKeyEdges:
+ properties:
+ user:
+ allOf:
+ - $ref: '#/definitions/ent.User'
+ description: User holds the value of the user edge.
+ type: object
ent.Attachment:
properties:
created_at:
@@ -785,6 +822,11 @@ definitions:
type: object
ent.UserEdges:
properties:
+ api_keys:
+ description: APIKeys holds the value of the api_keys edge.
+ items:
+ $ref: '#/definitions/ent.APIKey'
+ type: array
auth_tokens:
description: AuthTokens holds the value of the auth_tokens edge.
items:
@@ -813,6 +855,54 @@ definitions:
- TypeNumber
- TypeBoolean
- TypeTime
+ repo.APIKeyCreate:
+ properties:
+ expiresAt:
+ type: string
+ x-nullable: true
+ name:
+ maxLength: 255
+ minLength: 1
+ type: string
+ required:
+ - name
+ type: object
+ repo.APIKeyCreatedOut:
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ x-nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ x-nullable: true
+ name:
+ type: string
+ token:
+ type: string
+ userId:
+ type: string
+ type: object
+ repo.APIKeyOut:
+ properties:
+ createdAt:
+ type: string
+ expiresAt:
+ type: string
+ x-nullable: true
+ id:
+ type: string
+ lastUsedAt:
+ type: string
+ x-nullable: true
+ name:
+ type: string
+ userId:
+ type: string
+ type: object
repo.BarcodeProduct:
properties:
barcode:
@@ -3730,6 +3820,58 @@ paths:
summary: Update Account
tags:
- User
+ /v1/users/self/api-keys:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.APIKeyOut'
+ type: array
+ security:
+ - Bearer: []
+ summary: List API Keys
+ tags:
+ - User
+ post:
+ parameters:
+ - description: API Key Data
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/repo.APIKeyCreate'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.APIKeyCreatedOut'
+ security:
+ - Bearer: []
+ summary: Create API Key
+ tags:
+ - User
+ /v1/users/self/api-keys/{id}:
+ delete:
+ parameters:
+ - description: API Key ID
+ in: path
+ name: id
+ required: true
+ type: string
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete API Key
+ tags:
+ - User
/v1/users/self/settings:
get:
produces:
diff --git a/frontend/components/Item/CreateModal.vue b/frontend/components/Item/CreateModal.vue
index 8779b878..c470956f 100644
--- a/frontend/components/Item/CreateModal.vue
+++ b/frontend/components/Item/CreateModal.vue
@@ -291,7 +291,12 @@
import BaseModal from "@/components/App/CreateModal.vue";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
- import type { EntityCreate, EntityTemplateOut, EntityTemplateSummary, EntityOut } from "~~/lib/api/types/data-contracts";
+ import type {
+ EntityCreate,
+ EntityTemplateOut,
+ EntityTemplateSummary,
+ EntityOut,
+ } from "~~/lib/api/types/data-contracts";
import { useTagStore } from "~/stores/tags";
import { useLocationStore } from "~~/stores/locations";
import MdiBarcode from "~icons/mdi/barcode";
@@ -390,7 +395,11 @@
if (et?.defaultTemplateId && et.defaultTemplate) {
const { data, error } = await api.templates.get(et.defaultTemplateId);
if (!error && data) {
- selectedTemplate.value = { id: data.id, name: data.name, description: data.description } as EntityTemplateSummary;
+ selectedTemplate.value = {
+ id: data.id,
+ name: data.name,
+ description: data.description,
+ } as EntityTemplateSummary;
templateData.value = data;
form.quantity = data.defaultQuantity;
if (data.defaultName) form.name = data.defaultName;
@@ -657,7 +666,7 @@
} else {
// Normal item creation without template
const out: EntityCreate = {
- parentId: form.parentId || form.location.id as string,
+ parentId: form.parentId || (form.location.id as string),
name: form.name,
quantity: form.quantity,
description: form.description,
diff --git a/frontend/components/Location/CreateModal.vue b/frontend/components/Location/CreateModal.vue
index 503ce595..fe8e30cf 100644
--- a/frontend/components/Location/CreateModal.vue
+++ b/frontend/components/Location/CreateModal.vue
@@ -67,11 +67,7 @@
<template v-if="showAdvanced">
<TagSelector v-model="form.tags" :tags="tags ?? []" />
- <FormTextArea
- v-model="form.notes"
- label="Notes"
- :max-length="1000"
- />
+ <FormTextArea v-model="form.notes" label="Notes" :max-length="1000" />
</template>
<div class="mt-4 flex flex-row-reverse">
@@ -142,8 +138,7 @@
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import BaseModal from "@/components/App/CreateModal.vue";
- import type { EntityTypeSummary } from "~~/lib/api/types/data-contracts";
- import type { EntitySummary } from "~~/lib/api/types/data-contracts";
+ import type { EntityTypeSummary, EntitySummary } from "~~/lib/api/types/data-contracts";
import { AttachmentTypes } from "~~/lib/api/types/non-generated";
import { useDialog, useDialogHotkey } from "~/components/ui/dialog-provider";
import { useTagStore } from "~/stores/tags";
diff --git a/frontend/components/Scanner/ARControls.vue b/frontend/components/Scanner/ARControls.vue
index ea665013..0d0c9da3 100644
--- a/frontend/components/Scanner/ARControls.vue
+++ b/frontend/components/Scanner/ARControls.vue
@@ -2,7 +2,13 @@
<div class="pointer-events-none absolute inset-0 z-20 flex flex-col justify-between">
<!-- Top bar -->
<div class="pointer-events-auto flex items-center gap-3 bg-background/60 p-3 backdrop-blur-sm">
- <Button variant="ghost" size="icon" :aria-label="t('scanner_ar.back')" :title="t('scanner_ar.back')" @click="$emit('back')">
+ <Button
+ variant="ghost"
+ size="icon"
+ :aria-label="t('scanner_ar.back')"
+ :title="t('scanner_ar.back')"
+ @click="$emit('back')"
+ >
<MdiArrowLeft class="size-5" />
</Button>
<span class="text-sm font-semibold text-foreground">{{ t("scanner_ar.title") }}</span>
diff --git a/frontend/components/ui/dialog-provider/utils.ts b/frontend/components/ui/dialog-provider/utils.ts
index 80bea75c..fed5e5b9 100644
--- a/frontend/components/ui/dialog-provider/utils.ts
+++ b/frontend/components/ui/dialog-provider/utils.ts
@@ -12,6 +12,8 @@ import type {
export enum DialogID {
AttachmentEdit = "attachment-edit",
ChangePassword = "changePassword",
+ CreateApiKey = "create-api-key",
+ CreateApiKeyResult = "create-api-key-result",
CreateItem = "create-item",
CreateLocation = "create-location",
CreateTag = "create-tag",
diff --git a/frontend/lib/api/classes/items.ts b/frontend/lib/api/classes/items.ts
index 65f40ee8..64fa3f30 100644
--- a/frontend/lib/api/classes/items.ts
+++ b/frontend/lib/api/classes/items.ts
@@ -69,7 +69,10 @@ export class AttachmentsAPI extends BaseAPI {
}
addExternalLink(id: string, sourceType: string, externalId: string, title: string, attachmentType?: string) {
- return this.http.post<{ source_type: string; external_id: string; title: string; attachment_type?: string }, EntityOut>({
+ return this.http.post<
+ { source_type: string; external_id: string; title: string; attachment_type?: string },
+ EntityOut
+ >({
url: route(`/entities/${id}/attachments/external`),
body: { source_type: sourceType, external_id: externalId, title, attachment_type: attachmentType },
});
diff --git a/frontend/lib/api/classes/users.ts b/frontend/lib/api/classes/users.ts
index a4cfba26..83216fd7 100644
--- a/frontend/lib/api/classes/users.ts
+++ b/frontend/lib/api/classes/users.ts
@@ -1,5 +1,5 @@
import { BaseAPI, route } from "../base";
-import type { ChangePassword, UserOut } from "../types/data-contracts";
+import type { APIKeyCreate, APIKeyCreatedOut, APIKeyOut, ChangePassword, UserOut } from "../types/data-contracts";
import type { Result } from "../types/non-generated";
export class UserApi extends BaseAPI {
@@ -37,4 +37,19 @@ export class UserApi extends BaseAPI {
body: settings,
});
}
+
+ public listApiKeys() {
+ return this.http.get<APIKeyOut[]>({ url: route("/users/self/api-keys") });
+ }
+
+ public createApiKey(body: APIKeyCreate) {
+ return this.http.post<APIKeyCreate, APIKeyCreatedOut>({
+ url: route("/users/self/api-keys"),
+ body,
+ });
+ }
+
+ public deleteApiKey(id: string) {
+ return this.http.delete<void>({ url: route(`/users/self/api-keys/${id}`) });
+ }
}
diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.ts
index 982c0c4e..937db2c4 100644
--- a/frontend/lib/api/types/data-contracts.ts
+++ b/frontend/lib/api/types/data-contracts.ts
@@ -67,6 +67,33 @@ export interface CurrenciesCurrency {
symbol: string;
}
+export interface EntAPIKey {
+ /** 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 APIKeyQuery when eager-loading is set.
+ */
+ edges: EntAPIKeyEdges;
+ /** ExpiresAt holds the value of the "expires_at" field. */
+ expires_at: string;
+ /** ID of the ent. */
+ id: string;
+ /** LastUsedAt holds the value of the "last_used_at" field. */
+ last_used_at: string;
+ /** Name holds the value of the "name" field. */
+ name: string;
+ /** UpdatedAt holds the value of the "updated_at" field. */
+ updated_at: string;
+ /** UserID holds the value of the "user_id" field. */
+ user_id: string;
+}
+
+export interface EntAPIKeyEdges {
+ /** User holds the value of the user edge. */
+ user: EntUser;
+}
+
export interface EntAttachment {
/** CreatedAt holds the value of the "created_at" field. */
created_at: string;
@@ -555,6 +582,8 @@ export interface EntUser {
}
export interface EntUserEdges {
+ /** APIKeys holds the value of the api_keys edge. */
+ api_keys: EntAPIKey[];
/** AuthTokens holds the value of the auth_tokens edge. */
auth_tokens: EntAuthTokens[];
/** Groups holds the value of the groups edge. */
@@ -563,6 +592,34 @@ export interface EntUserEdges {
notifiers: EntNotifier[];
}
+export interface APIKeyCreate {
+ expiresAt?: string | null;
+ /**
+ * @minLength 1
+ * @maxLength 255
+ */
+ name: string;
+}
+
+export interface APIKeyCreatedOut {
+ createdAt: Date | string;
+ expiresAt?: string | null;
+ id: string;
+ lastUsedAt?: string | null;
+ name: string;
+ token: string;
+ userId: string;
+}
+
+export interface APIKeyOut {
+ createdAt: Date | string;
+ expiresAt?: string | null;
+ id: string;
+ lastUsedAt?: string | null;
+ name: string;
+ userId: string;
+}
+
export interface BarcodeProduct {
barcode: string;
imageBase64: string;
diff --git a/frontend/locales/en.json b/frontend/locales/en.json
index a932dddd..9fafc96c 100644
--- a/frontend/locales/en.json
+++ b/frontend/locales/en.json
@@ -400,6 +400,7 @@
"archived": "Archived",
"build": "Build: { build }",
"cancel": "Cancel",
+ "close": "Close",
"confirm": "Confirm",
"create": "Create",
"create_and_add": "Create and Add Another",
@@ -725,6 +726,23 @@
},
"profile": {
"active": "Active",
+ "api_keys": "API Keys",
+ "api_keys_sub": "Static tokens for programmatic access. Each key has the same permissions as your account.",
+ "api_key_create": "Create API Key",
+ "api_key_name": "Name",
+ "api_key_name_placeholder": "e.g. Home Assistant",
+ "api_key_expires_at": "Expires",
+ "api_key_no_expiration": "No expiration",
+ "api_key_set_expiration": "Set an expiration date",
+ "api_key_last_used": "Last used",
+ "api_key_never_used": "Never",
+ "api_key_created": "Created",
+ "api_key_token_label": "Your new API key",
+ "api_key_token_warning": "Copy this token now. For your security, it will not be shown again.",
+ "api_key_copy": "Copy",
+ "api_key_copied": "Copied to clipboard",
+ "api_key_delete_confirm": "Are you sure you want to revoke this API key? Any clients using it will lose access immediately.",
+ "no_api_keys": "No API keys yet",
"change_password": "Change Password",
"currency_format": "Currency Format",
"current_password": "Current Password",
@@ -758,6 +776,10 @@
"theme_settings_sub": "Theme settings are stored in your browser's local storage. You can change the theme at any time. If you're\n having trouble setting your theme try refreshing your browser.",
"toast": {
"account_deleted": "Your account has been deleted.",
+ "api_key_created": "API key created.",
+ "api_key_deleted": "API key revoked.",
+ "failed_api_key_create": "Failed to create API key.",
+ "failed_api_key_delete": "Failed to revoke API key.",
"failed_change_password": "Failed to change password.",
"failed_create_notifier": "Failed to create notifier.",
"failed_delete_account": "Failed to delete your account.",
diff --git a/frontend/pages/collection/index/entity-types.vue b/frontend/pages/collection/index/entity-types.vue
index 796926f8..920fdf53 100644
--- a/frontend/pages/collection/index/entity-types.vue
+++ b/frontend/pages/collection/index/entity-types.vue
@@ -16,13 +16,7 @@
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
- import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- } from "@/components/ui/dialog";
+ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useDialog } from "@/components/ui/dialog-provider";
import { DialogID } from "~/components/ui/dialog-provider/utils";
import FormTextField from "~/components/Form/TextField.vue";
@@ -98,7 +92,11 @@
updateForm.icon = et.icon;
updateForm.isLocation = et.isLocation;
updateTemplate.value = et.defaultTemplate
- ? { id: et.defaultTemplate.id, name: et.defaultTemplate.name, description: et.defaultTemplate.description } as EntityTemplateSummary
+ ? ({
+ id: et.defaultTemplate.id,
+ name: et.defaultTemplate.name,
+ description: et.defaultTemplate.description,
+ } as EntityTemplateSummary)
: null;
openDialog(DialogID.UpdateEntityType);
}
@@ -154,13 +152,7 @@
<DialogTitle>Create Entity Type</DialogTitle>
</DialogHeader>
<form class="flex flex-col gap-3" @submit.prevent="create">
- <FormTextField
- v-model="createForm.name"
- :autofocus="true"
- label="Name"
- :max-length="255"
- :min-length="1"
- />
+ <FormTextField v-model="createForm.name" :autofocus="true" label="Name" :max-length="255" :min-length="1" />
<FormCheckbox v-model="createForm.isLocation" label="Is a container / location type" />
<TemplateSelector v-model="createTemplate" />
@@ -178,13 +170,7 @@
<DialogTitle>Update Entity Type</DialogTitle>
</DialogHeader>
<form class="flex flex-col gap-3" @submit.prevent="update">
- <FormTextField
- v-model="updateForm.name"
- :autofocus="true"
- label="Name"
- :max-length="255"
- :min-length="1"
- />
+ <FormTextField v-model="updateForm.name" :autofocus="true" label="Name" :max-length="255" :min-length="1" />
<FormCheckbox v-model="updateForm.isLocation" label="Is a container / location type" />
<TemplateSelector v-model="updateTemplate" />
@@ -196,7 +182,7 @@
</Dialog>
<!-- Page Content -->
- <div class="flex items-center justify-between mb-4">
+ <div class="mb-4 flex items-center justify-between">
<h3 class="text-lg font-medium">Entity Types</h3>
<Button size="sm" @click="openDialog(DialogID.CreateEntityType)">
<MdiPlus class="mr-1 size-4" />
@@ -207,7 +193,9 @@
<div v-if="entityTypes && entityTypes.length > 0" class="space-y-2">
<Card v-for="et in entityTypes" :key="et.id" class="p-4">
<div class="flex items-center gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-secondary text-secondary-foreground">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-secondary text-secondary-foreground"
+ >
<MdiMapMarkerOutline v-if="et.isLocation" class="size-5" />
<MdiPackageVariantClosed v-else class="size-5" />
</div>
diff --git a/frontend/pages/item/[id]/index/edit.vue b/frontend/pages/item/[id]/index/edit.vue
index 8255d9ff..abb11e1c 100644
--- a/frontend/pages/item/[id]/index/edit.vue
+++ b/frontend/pages/item/[id]/index/edit.vue
@@ -379,7 +379,7 @@
"link",
droppedURL,
title,
- attachmentType,
+ attachmentType
);
if (error) {
@@ -752,7 +752,12 @@
</div>
</BaseCard>
- <Card ref="attDropZone" class="overflow-visible shadow-xl" @dragover.prevent @drop.prevent="handleAttachmentCardDrop">
+ <Card
+ ref="attDropZone"
+ class="overflow-visible shadow-xl"
+ @dragover.prevent
+ @drop.prevent="handleAttachmentCardDrop"
+ >
<div class="px-4 py-5 sm:px-6">
<h3 class="text-lg font-medium leading-6">{{ $t("items.attachments") }}</h3>
<p class="text-xs">{{ $t("items.changes_persisted_immediately") }}</p>
@@ -818,7 +823,11 @@
<TooltipContent>{{ $t("items.edit.view_image") }}</TooltipContent>
</Tooltip>
<Tooltip
- v-if="attachment.mimeType === 'link/url' || (attachment.path ?? '').startsWith('http://') || (attachment.path ?? '').startsWith('https://')"
+ v-if="
+ attachment.mimeType === 'link/url' ||
+ (attachment.path ?? '').startsWith('http://') ||
+ (attachment.path ?? '').startsWith('https://')
+ "
>
<TooltipTrigger as-child>
<a :href="attachment.path" target="_blank" rel="noopener noreferrer">
diff --git a/frontend/pages/location/[id]/index.vue b/frontend/pages/location/[id]/index.vue
index 5243fd12..bb39c5ca 100644
--- a/frontend/pages/location/[id]/index.vue
+++ b/frontend/pages/location/[id]/index.vue
@@ -1,8 +1,4 @@
-<script setup lang="ts">
- definePageMeta({
- middleware: ["auth"],
- });
-</script>
+<script setup lang="ts"></script>
<template>
<BaseContainer>
@@ -12,4 +8,7 @@
<script lang="ts">
import BaseContainer from "@/components/Base/Container.vue";
+ definePageMeta({
+ middleware: ["auth"],
+ });
</script>
diff --git a/frontend/pages/location/[id]/index/index.vue b/frontend/pages/location/[id]/index/index.vue
index 1e88712d..cdec53ec 100644
--- a/frontend/pages/location/[id]/index/index.vue
+++ b/frontend/pages/location/[id]/index/index.vue
@@ -150,7 +150,12 @@
else acc.attachments.push(attachment);
return acc;
},
- { attachments: [] as ItemAttachment[], warranty: [] as ItemAttachment[], manuals: [] as ItemAttachment[], receipts: [] as ItemAttachment[] }
+ {
+ attachments: [] as ItemAttachment[],
+ warranty: [] as ItemAttachment[],
+ manuals: [] as ItemAttachment[],
+ receipts: [] as ItemAttachment[],
+ }
);
});
@@ -171,12 +176,12 @@
type: "markdown",
text: location.value.notes,
},
- ...((location.value.fields || []).map(field => {
+ ...(location.value.fields || []).map(field => {
return {
name: field.name,
text: field.textValue,
} as AnyDetail;
- })),
+ }),
];
if (!preferences.value.showEmpty) {
@@ -224,7 +229,7 @@
<button
v-for="(photo, i) in photos"
:key="i"
- class="group relative aspect-square overflow-hidden rounded-lg border bg-muted"
+ class="aspect-square group relative overflow-hidden rounded-lg border bg-muted"
@click="openImageDialog(photo, location.id)"
>
<img
diff --git a/frontend/pages/profile.vue b/frontend/pages/profile.vue
index b3c8155e..b0c3e31f 100644
--- a/frontend/pages/profile.vue
+++ b/frontend/pages/profile.vue
@@ -6,6 +6,8 @@
import MdiAccount from "~icons/mdi/account";
import MdiDelete from "~icons/mdi/delete";
import MdiFill from "~icons/mdi/fill";
+ import MdiKeyVariant from "~icons/mdi/key-variant";
+ import MdiContentCopy from "~icons/mdi/content-copy";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useDialog } from "@/components/ui/dialog-provider";
@@ -14,12 +16,16 @@
import ThemePicker from "~/components/App/ThemePicker.vue";
import ItemDuplicateSettings from "~/components/Item/DuplicateSettings.vue";
import FormPassword from "~/components/Form/Password.vue";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import FormCheckbox from "~/components/Form/Checkbox.vue";
import BaseContainer from "@/components/Base/Container.vue";
import BaseCard from "@/components/Base/Card.vue";
import BaseSectionHeader from "@/components/Base/SectionHeader.vue";
import DetailsSection from "@/components/global/DetailsSection/DetailsSection.vue";
+ import DateTime from "@/components/global/DateTime.vue";
import PasswordScore from "~/components/global/PasswordScore.vue";
import { PASSWORD_MIN_LENGTH, PASSWORD_RULES } from "~/lib/passwords";
+ import type { APIKeyOut } from "~~/lib/api/types/data-contracts";
const { t } = useI18n();
@@ -104,6 +110,103 @@
passwordChange.current = "";
passwordChange.loading = false;
}
+
+ // ---------------------------------------------------------------------------
+ // API keys
+
+ const apiKeys = ref<APIKeyOut[]>([]);
+ const apiKeysLoading = ref(false);
+
+ async function loadApiKeys() {
+ apiKeysLoading.value = true;
+ const { data, error } = await api.user.listApiKeys();
+ apiKeysLoading.value = false;
+ if (error) {
+ toast.error(t("errors.api_failure") + String(error));
+ return;
+ }
+ apiKeys.value = data ?? [];
+ }
+
+ onMounted(() => {
+ void loadApiKeys();
+ });
+
+ const apiKeyForm = reactive({
+ name: "",
+ setExpiration: false,
+ expiresAt: "",
+ submitting: false,
+ });
+
+ function openCreateApiKey() {
+ apiKeyForm.name = "";
+ apiKeyForm.setExpiration = false;
+ apiKeyForm.expiresAt = "";
+ apiKeyForm.submitting = false;
+ openDialog(DialogID.CreateApiKey);
+ }
+
+ const newApiKeyToken = ref<string | null>(null);
+
+ async function submitCreateApiKey() {
+ if (!apiKeyForm.name.trim()) return;
+ apiKeyForm.submitting = true;
+
+ let expiresAt: string | null = null;
+ if (apiKeyForm.setExpiration && apiKeyForm.expiresAt) {
+ // <input type="date"> gives YYYY-MM-DD; treat as end-of-day UTC so the
+ // key remains valid through the chosen calendar day.
+ expiresAt = new Date(apiKeyForm.expiresAt + "T23:59:59Z").toISOString();
+ }
+
+ const { data, error } = await api.user.createApiKey({
+ name: apiKeyForm.name.trim(),
+ expiresAt,
+ });
+
+ apiKeyForm.submitting = false;
+
+ if (error || !data) {
+ toast.error(t("profile.toast.failed_api_key_create"));
+ return;
+ }
+
+ closeDialog(DialogID.CreateApiKey);
+ newApiKeyToken.value = data.token;
+ openDialog(DialogID.CreateApiKeyResult);
+ toast.success(t("profile.toast.api_key_created"));
+ await loadApiKeys();
+ }
+
+ async function copyApiKey() {
+ if (!newApiKeyToken.value) return;
+ try {
+ await navigator.clipboard.writeText(newApiKeyToken.value);
+ toast.success(t("profile.api_key_copied"));
+ } catch {
+ // Clipboard API can be blocked by the browser; surface no error toast,
+ // the user can still copy manually from the visible field.
+ }
+ }
+
+ function dismissApiKeyResult() {
+ closeDialog(DialogID.CreateApiKeyResult);
+ newApiKeyToken.value = null;
+ }
+
+ async function revokeApiKey(key: APIKeyOut) {
+ const result = await confirm.open(t("profile.api_key_delete_confirm"));
+ if (result.isCanceled) return;
+
+ const { error } = await api.user.deleteApiKey(key.id);
+ if (error) {
+ toast.error(t("profile.toast.failed_api_key_delete"));
+ return;
+ }
+ toast.success(t("profile.toast.api_key_deleted"));
+ await loadApiKeys();
+ }
</script>
<template>
@@ -120,6 +223,69 @@
</DialogContent>
</Dialog>
+ <Dialog :dialog-id="DialogID.CreateApiKey">
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{{ $t("profile.api_key_create") }}</DialogTitle>
+ </DialogHeader>
+
+ <form @submit.prevent="submitCreateApiKey">
+ <FormTextField
+ v-model="apiKeyForm.name"
+ :label="$t('profile.api_key_name')"
+ :placeholder="$t('profile.api_key_name_placeholder')"
+ :required="true"
+ class="mb-2"
+ />
+ <div class="mb-2 max-w-[260px]">
+ <FormCheckbox v-model="apiKeyForm.setExpiration" :label="$t('profile.api_key_set_expiration')" />
+ </div>
+ <div v-if="apiKeyForm.setExpiration" class="mb-2">
+ <label class="mb-1 block text-sm font-medium">{{ $t("profile.api_key_expires_at") }}</label>
+ <input
+ v-model="apiKeyForm.expiresAt"
+ type="date"
+ class="w-full rounded-md border bg-background px-3 py-2 text-sm"
+ :required="apiKeyForm.setExpiration"
+ />
+ </div>
+
+ <DialogFooter>
+ <Button :disabled="apiKeyForm.submitting || !apiKeyForm.name.trim()" type="submit">
+ <MdiLoading v-if="apiKeyForm.submitting" class="animate-spin" />
+ {{ $t("global.create") }}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog :dialog-id="DialogID.CreateApiKeyResult">
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{{ $t("profile.api_key_token_label") }}</DialogTitle>
+ </DialogHeader>
+
+ <p class="text-sm text-muted-foreground">{{ $t("profile.api_key_token_warning") }}</p>
+
+ <div class="flex items-center gap-2">
+ <input
+ :value="newApiKeyToken ?? ''"
+ readonly
+ class="w-full rounded-md border bg-muted px-3 py-2 font-mono text-sm"
+ @focus="($event.target as HTMLInputElement).select()"
+ />
+ <Button variant="secondary" size="icon" :aria-label="$t('profile.api_key_copy')" @click="copyApiKey">
+ <MdiContentCopy />
+ </Button>
+ </div>
+
+ <DialogFooter>
+ <Button @click="dismissApiKeyResult">{{ $t("global.close") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
<Dialog :dialog-id="DialogID.ChangePassword">
<DialogContent>
<DialogHeader>
@@ -185,6 +351,58 @@
<LanguageSelector />
</BaseCard>
+ <BaseCard>
+ <template #title>
+ <BaseSectionHeader>
+ <MdiKeyVariant class="-mt-1 mr-2" />
+ <span>{{ $t("profile.api_keys") }}</span>
+ <template #description>{{ $t("profile.api_keys_sub") }}</template>
+ </BaseSectionHeader>
+ </template>
+
+ <div class="px-4 pb-4">
+ <div class="mx-1 divide-y rounded-md border">
+ <p v-if="!apiKeysLoading && apiKeys.length === 0" class="p-2 text-center text-sm">
+ {{ $t("profile.no_api_keys") }}
+ </p>
+ <article v-for="k in apiKeys" :key="k.id" class="p-2">
+ <div class="flex flex-wrap items-center gap-2">
+ <p class="mr-auto text-lg">{{ k.name }}</p>
+ <Button variant="destructive" size="icon" :aria-label="$t('global.delete')" @click="revokeApiKey(k)">
+ <MdiDelete />
+ </Button>
+ </div>
+ <div class="flex flex-wrap justify-between gap-x-4 gap-y-1 py-1 text-sm text-muted-foreground">
+ <p>
+ {{ $t("profile.api_key_created") }}:
+ <DateTime format="relative" datetime-type="time" :date="k.createdAt" />
+ </p>
+ <p>
+ {{ $t("profile.api_key_last_used") }}:
+ <template v-if="k.lastUsedAt">
+ <DateTime format="relative" datetime-type="time" :date="k.lastUsedAt" />
+ </template>
+ <template v-else>{{ $t("profile.api_key_never_used") }}</template>
+ </p>
+ <p>
+ {{ $t("profile.api_key_expires_at") }}:
+ <template v-if="k.expiresAt">
+ <DateTime format="human" datetime-type="date" :date="k.expiresAt" />
+ </template>
+ <template v-else>{{ $t("profile.api_key_no_expiration") }}</template>
+ </p>
+ </div>
+ </article>
+ </div>
+
+ <div class="mt-4">
+ <Button variant="secondary" size="sm" @click="openCreateApiKey">
+ {{ $t("profile.api_key_create") }}
+ </Button>
+ </div>
+ </div>
+ </BaseCard>
+
<!-- TODO: Remove this notice once users are familiar with the collection-based settings. -->
<BaseCard>
<template #title>