api_key.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package api // import "miniflux.app/v2/internal/api"
  4. import (
  5. json_parser "encoding/json"
  6. "errors"
  7. "net/http"
  8. "miniflux.app/v2/internal/http/request"
  9. "miniflux.app/v2/internal/http/response/json"
  10. "miniflux.app/v2/internal/model"
  11. "miniflux.app/v2/internal/storage"
  12. "miniflux.app/v2/internal/validator"
  13. )
  14. func (h *handler) createAPIKey(w http.ResponseWriter, r *http.Request) {
  15. userID := request.UserID(r)
  16. var apiKeyCreationRequest model.APIKeyCreationRequest
  17. if err := json_parser.NewDecoder(r.Body).Decode(&apiKeyCreationRequest); err != nil {
  18. json.BadRequest(w, r, err)
  19. return
  20. }
  21. if validationErr := validator.ValidateAPIKeyCreation(h.store, userID, &apiKeyCreationRequest); validationErr != nil {
  22. json.BadRequest(w, r, validationErr.Error())
  23. return
  24. }
  25. apiKey, err := h.store.CreateAPIKey(userID, apiKeyCreationRequest.Description)
  26. if err != nil {
  27. json.ServerError(w, r, err)
  28. return
  29. }
  30. json.Created(w, r, apiKey)
  31. }
  32. func (h *handler) getAPIKeys(w http.ResponseWriter, r *http.Request) {
  33. userID := request.UserID(r)
  34. apiKeys, err := h.store.APIKeys(userID)
  35. if err != nil {
  36. json.ServerError(w, r, err)
  37. return
  38. }
  39. json.OK(w, r, apiKeys)
  40. }
  41. func (h *handler) deleteAPIKey(w http.ResponseWriter, r *http.Request) {
  42. userID := request.UserID(r)
  43. apiKeyID := request.RouteInt64Param(r, "apiKeyID")
  44. if err := h.store.DeleteAPIKey(userID, apiKeyID); err != nil {
  45. if errors.Is(err, storage.ErrAPIKeyNotFound) {
  46. json.NotFound(w, r)
  47. return
  48. }
  49. json.ServerError(w, r, err)
  50. return
  51. }
  52. json.NoContent(w, r)
  53. }