8000 [pull] main from miniflux:main by pull[bot] · Pull Request #258 · suhaoGe/miniflux · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ require (
github.com/coreos/go-oidc/v3 v3.17.0
github.com/go-webauthn/webauthn v0.16.1
github.com/gorilla/mux v1.8.1
github.com/lib/pq v1.11.2
github.com/lib/pq v1.12.0
github.com/prometheus/client_golang v1.23.2
github.com/tdewolff/minify/v2 v2.24.10
golang.org/x/crypto v0.49.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lib/pq v1.11.2 h1:x6gxUeu39V0BHZiugWe8LXZYZ+Utk7hSJGThs8sdzfs=
github.com/lib/pq v1.11.2/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lib/pq v1.12.0 h1:mC1zeiNamwKBecjHarAr26c/+d8V5w/u4J0I/yASbJo=
github.com/lib/pq v1.12.0/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
137 changes: 59 additions & 78 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,92 +5,73 @@ package api // import "miniflux.app/v2/internal/api"

import (
"net/http"
"runtime"

"miniflux.app/v2/internal/http/response"
"miniflux.app/v2/internal/storage"
"miniflux.app/v2/internal/version"
"miniflux.app/v2/internal/worker"

"github.com/gorilla/mux"
)

type handler struct {
store *storage.Storage
pool *worker.Pool
router *mux.Router
store *storage.Storage
pool *worker.Pool
}

// Serve declares API routes for the application.
func Serve(router *mux.Router, store *storage.Storage, pool *worker.Pool) {
handler := &handler{store, pool, router}

sr := router.PathPrefix("/v1").Subrouter()
// NewHandler returns an http.Handler that handles API v1 calls.
// The returned handler expects the base path to be stripped from the request URL.
func NewHandler(store *storage.Storage, pool *worker.Pool) http.Handler {
handler := &handler{store: store, pool: pool}
middleware := newMiddleware(store)
sr.Use(middleware.handleCORS)
sr.Use(middleware.apiKeyAuth)
sr.Use(middleware.basicAuth)
sr.Methods(http.MethodOptions)
sr.HandleFunc("/users", handler.createUser).Methods(http.MethodPost)
sr.HandleFunc("/users", handler.users).Methods(http.MethodGet)
sr.HandleFunc("/users/{userID:[0-9]+}", handler.userByID).Methods(http.MethodGet)
sr.HandleFunc("/users/{userID:[0-9]+}", handler.updateUser).Methods(http.MethodPut)
sr.HandleFunc("/users/{userID:[0-9]+}", handler.removeUser).Methods(http.MethodDelete)
sr.HandleFunc("/users/{userID:[0-9]+}/mark-all-as-read", handler.markUserAsRead).Methods(http.MethodPut)
sr.HandleFunc("/users/{username}", handler.userByUsername).Methods(http.MethodGet)
sr.HandleFunc("/me", handler.currentUser).Methods(http.MethodGet)
sr.HandleFunc("/categories", handler.createCategory).Methods(http.MethodPost)
sr.HandleFunc("/categories", handler.getCategories).Methods(http.MethodGet)
sr.HandleFunc("/categories/{categoryID}", handler.updateCategory).Methods(http.MethodPut)
sr.HandleFunc("/categories/{categoryID}", handler.removeCategory).Methods(http.MethodDelete)
sr.HandleFunc("/categories/{categoryID}/mark-all-as-read", handler.markCategoryAsRead).Methods(http.MethodPut)
sr.HandleFunc("/categories/{categoryID}/feeds", handler.getCategoryFeeds).Methods(http.MethodGet)
sr.HandleFunc("/categories/{categoryID}/refresh", handler.refreshCategory).Methods(http.MethodPut)
sr.HandleFunc("/categories/{categoryID}/entries", handler.getCategoryEntries).Methods(http.MethodGet)
sr.HandleFunc("/categories/{categoryID}/entries/{entryID}", handler.getCategoryEntry).Methods(http.MethodGet)
sr.HandleFunc("/discover", handler.discoverSubscriptions).Methods(http.MethodPost)
sr.HandleFunc("/feeds", handler.createFeed).Methods(http.MethodPost)
sr.HandleFunc("/feeds", handler.getFeeds).Methods(http.MethodGet)
sr.HandleFunc("/feeds/counters", handler.fetchCounters).Methods(http.MethodGet)
sr.HandleFunc("/feeds/refresh", handler.refreshAllFeeds).Methods(http.MethodPut)
sr.HandleFunc("/feeds/{feedID}/refresh", handler.refreshFeed).Methods(http.MethodPut)
sr.HandleFunc("/feeds/{feedID}", handler.getFeed).Methods(http.MethodGet)
sr.HandleFunc("/feeds/{feedID}", handler.updateFeed).Methods(http.MethodPut)
sr.HandleFunc("/feeds/{feedID}", handler.removeFeed).Methods(http.MethodDelete)
sr.HandleFunc("/feeds/{feedID}/icon", handler.getIconByFeedID).Methods(http.MethodGet)
sr.HandleFunc("/feeds/{feedID}/mark-all-as-read", handler.markFeedAsRead).Methods(http.MethodPut)
sr.HandleFunc("/export", handler.exportFeeds).Methods(http.MethodGet)
sr.HandleFunc("/import", handler.importFeeds).Methods(http.MethodPost)
sr.HandleFunc("/feeds/{feedID}/entries", handler.getFeedEntries).Methods(http.MethodGet)
sr.HandleFunc("/feeds/{feedID}/entries/import", handler.importFeedEntry).Methods(http.MethodPost)
sr.HandleFunc("/feeds/{feedID}/entries/{entryID}", handler.getFeedEntry).Methods(http.MethodGet)
sr.HandleFunc("/entries", handler.getEntries).Methods(http.MethodGet)
sr.HandleFunc("/entries", handler.setEntryStatus).Methods(http.MethodPut)
sr.HandleFunc("/entries/{entryID}", handler.getEntry).Methods(http.MethodGet)
sr.HandleFunc("/entries/{entryID}", handler.updateEntry).Methods(http.MethodPut)
sr.HandleFunc("/entries/{entryID}/bookmark", handler.toggleStarred).Methods(http.MethodPut)
sr.HandleFunc("/entries/{entryID}/star", handler.toggleStarred).Methods(http.MethodPut)
sr.HandleFunc("/entries/{entryID}/save", handler.saveEntry).Methods(http.MethodPost)
sr.HandleFunc("/entries/{entryID}/fetch-content", handler.fetchContent).Methods(http.MethodGet)
sr.HandleFunc("/flush-history", handler.flushHistory).Methods(http.MethodPut, http.MethodDelete)
sr.HandleFunc("/icons/{iconID}", handler.getIconByIconID).Methods(http.MethodGet)
sr.HandleFunc("/enclosures/{enclosureID}", handler.getEnclosureByID).Methods(http.MethodGet)
sr.HandleFunc("/enclosures/{enclosureID}", handler.updateEnclosureByID).Methods(http.MethodPut)
sr.HandleFunc("/integrations/status", handler.getIntegrationsStatus).Methods(http.MethodGet)
sr.HandleFunc("/version", handler.versionHandler).Methods(http.MethodGet)
sr.HandleFunc("/api-keys", handler.createAPIKey).Methods(http.MethodPost)
sr.HandleFunc("/api-keys", handler.getAPIKeys).Methods(http.MethodGet)
sr.HandleFunc("/api-keys/{apiKeyID}", handler.deleteAPIKey).Methods(http.MethodDelete)
}

func (h *handler) versionHandler(w http.ResponseWriter, r *http.Request) {
response.JSON(w, r, &versionResponse{
Version: version.Version,
Commit: version.Commit,
BuildDate: version.BuildDate,
GoVersion: runtime.Version(),
Compiler: runtime.Compiler,
Arch: runtime.GOARCH,
OS: runtime.GOOS,
})
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/users", handler.createUserHandler)
mux.HandleFunc("GET /v1/users", handler.usersHandler)
mux.HandleFunc("GET /v1/users/{identifier}", handler.dispatchUserLookupHandler)
mux.HandleFunc("PUT /v1/users/{userID}", handler.updateUserHandler)
mux.HandleFunc("DELETE /v1/users/{userID}", handler.removeUserHandler)
mux.HandleFunc("PUT /v1/users/{userID}/mark-all-as-read", handler.markUserAsReadHandler)
mux.HandleFunc("GET /v1/me", handler.currentUserHandler)
mux.HandleFunc("POST /v1/categories", handler.createCategoryHandler)
mux.HandleFunc("GET /v1/categories", handler.getCategoriesHandler)
mux.HandleFunc("PUT /v1/categories/{categoryID}", handler.updateCategoryHandler)
mux.HandleFunc("DELETE /v1/categories/{categoryID}", handler.removeCategoryHandler)
mux.HandleFunc("PUT /v1/categories/{categoryID}/mark-all-as-read", handler.markCategoryAsReadHandler)
mux.HandleFunc("GET /v1/categories/{categoryID}/feeds", handler.getCategoryFeedsHandler)
mux.HandleFunc("PUT /v1/categories/{categoryID}/refresh", handler.refreshCategoryHandler)
mux.HandleFunc("GET /v1/categories/{categoryID}/entries", handler.getCategoryEntriesHandler)
mux.HandleFunc("GET /v1/categories/{categoryID}/entries/{entryID}", handler.getCategoryEntryHandler)
mux.HandleFunc("POST /v1/discover", handler.discoverSubscriptionsHandler)
mux.HandleFunc("POST /v1/feeds", handler.createFeedHandler)
mux.HandleFunc("GET /v1/feeds", handler.getFeedsHandler)
mux.HandleFunc("GET /v1/feeds/counters", handler.fetchCountersHandler)
mux.HandleFunc("PUT /v1/feeds/refresh", handler.refreshAllFeedsHandler)
mux.HandleFunc("PUT /v1/feeds/{feedID}/refresh", handler.refreshFeedHandler)
mux.HandleFunc("GET /v1/feeds/{feedID}", handler.getFeedHandler)
mux.HandleFunc("PUT /v1/feeds/{feedID}", handler.updateFeedHandler)
mux.HandleFunc("DELETE /v1/feeds/{feedID}", handler.removeFeedHandler)
mux.HandleFunc("GET /v1/feeds/{feedID}/icon", handler.getIconByFeedIDHandler)
mux.HandleFunc("PUT /v1/feeds/{feedID}/mark-all-as-read", handler.markFeedAsReadHandler)
mux.HandleFunc("GET /v1/export", handler.exportFeedsHandler)
mux.HandleFunc("POST /v1/import", handler.importFeedsHandler)
mux.HandleFunc("GET /v1/feeds/{feedID}/entries", handler.getFeedEntriesHandler)
mux.HandleFunc("POST /v1/feeds/{feedID}/entries/import", handler.importFeedEntryHandler)
mux.HandleFunc("GET /v1/feeds/{feedID}/entries/{entryID}", handler.getFeedEntryHandler)
mux.HandleFunc("GET /v1/entries", handler.getEntriesHandler)
mux.HandleFunc("PUT /v1/entries", handler.setEntryStatusHandler)
mux.HandleFunc("GET /v1/entries/{entryID}", handler.getEntryHandler)
mux.HandleFunc("PUT /v1/entries/{entryID}", handler.updateEntryHandler)
mux.HandleFunc("PUT /v1/entries/{entryID}/bookmark", handler.toggleStarredHandler)
mux.HandleFunc("PUT /v1/entries/{entryID}/star", handler.toggleStarredHandler)
mux.HandleFunc("POST /v1/entries/{entryID}/save", handler.saveEntryHandler)
mux.HandleFunc("GET /v1/entries/{entryID}/fetch-content", handler.fetchContentHandler)
mux.HandleFunc("PUT /v1/flush-history", handler.flushHistoryHandler)
mux.HandleFunc("DELETE /v1/flush-history", handler.flushHistoryHandler)
mux.HandleFunc("GET /v1/icons/{iconID}", handler.getIconByIconIDHandler)
mux.HandleFunc("GET /v1/enclosures/{enclosureID}", handler.getEnclosureByIDHandler)
mux.HandleFunc("PUT /v1/enclosures/{enclosureID}", handler.updateEnclosureByIDHandler)
mux.HandleFunc("GET /v1/integrations/status", handler.getIntegrationsStatusHandler)
mux.HandleFunc("GET /v1/version", handler.versionHandler)
mux.HandleFunc("POST /v1/api-keys", handler.createAPIKeyHandler)
mux.HandleFunc("GET /v1/api-keys", handler.getAPIKeysHandler)
mux.HandleFunc("DELETE /v1/api-keys/{apiKeyID}", handler.deleteAPIKeyHandler)

return middleware.withCORSHeaders(middleware.validateAPIKeyAuth(middleware.validateBasicAuth(mux)))
}
12 changes: 8 additions & 4 deletions internal/api/api_key.go → internal/api/api_key_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"miniflux.app/v2/internal/validator"
)

func (h *handler) createAPIKey(w http.ResponseWriter, r *http.Request) {
func (h *handler) createAPIKeyHandler(w http.ResponseWriter, r *http.Request) {
userID := request.UserID(r)

var apiKeyCreationRequest model.APIKeyCreationRequest
Expand All @@ -38,7 +38,7 @@ func (h *handler) createAPIKey(w http.ResponseWriter, r *http.Request) {
response.JSONCreated(w, r, apiKey)
}

func (h *handler) getAPIKeys(w http.ResponseWriter, r *http.Request) {
func (h *handler) getAPIKeysHandler(w http.ResponseWriter, r *http.Request) {
userID := request.UserID(r)
apiKeys, err := h.store.APIKeys(userID)
if err != nil {
Expand All @@ -48,9 +48,13 @@ func (h *handler) getAPIKeys(w http.ResponseWriter, r *http.Request) {
response.JSON(w, r, apiKeys)
}

func (h *handler) deleteAPIKey(w http.ResponseWriter, r *http.Request) {
func (h *handler) deleteAPIKeyHandler(w http.ResponseWriter, r *http.Request) {
userID := request.UserID(r)
apiKeyID := request.RouteInt64Param(r, "apiKeyID")
if apiKeyID == 0 {
response.JSONBadRequest(w, r, errors.New("invalid API key ID"))
return
}

if err := h.store.DeleteAPIKey(userID, apiKeyID); err != nil {
if errors.Is(err, storage.ErrAPIKeyNotFound) {
Expand All @@ -60,5 +64,5 @@ func (h *handler) deleteAPIKey(w http.ResponseWriter, r *http.Request) {
response.JSONServerError(w, r, err)
return
}
response.JSONNoContent(w, r)
response.NoContent(w, r)
}
118 changes: 118 additions & 0 deletions internal/api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package api // import "miniflux.app/v2/internal/api"

import (
"encoding/json"
"net/http"
"net/http/httptest"
"runtime"
"testing"

"miniflux.app/v2/internal/version"
)

func TestNewHandlerHandlesOptionsRequests(t *testing.T) {
handler := NewHandler(nil, nil)

r := httptest.NewRequest(http.MethodOptions, "/v1/users", nil)
w := httptest.NewRecorder()

handler.ServeHTTP(w, r)

if got := w.Code; got != http.StatusNoContent {
t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusNoContent)
}

if got := w.Header().Get("Access-Control-Allow-Origin"); got != "*" {
t.Fatalf(`Unexpected Access-Control-Allow-Origin header, got %q`, got)
}

if got := w.Header().Get("Access-Control-Allow-Methods"); got != "GET, POST, PUT, DELETE, OPTIONS" {
t.Fatalf(`Unexpected Access-Control-Allow-Methods header, got %q`, got)
}

if got := w.Header().Get("Access-Control-Allow-Headers"); got != "X-Auth-Token, Authorization, Content-Type, Accept" {
t.Fatalf(`Unexpected Access-Control-Allow-Headers header, got %q`, got)
}

if got := w.Header().Get("Access-Control-Max-Age"); got != "3600" {
t.Fatalf(`Unexpected Access-Control-Max-Age header, got %q`, got)
}
}

func TestVersionHandler(t *testing.T) {
h := &handler{}
r := httptest.NewRequest(http.MethodGet, "/v1/version", nil)
w := httptest.NewRecorder()

h.versionHandler(w, r)

if got := w.Code; got != http.StatusOK {
t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusOK)
}

if got := w.Header().Get("Content-Type"); got != "application/json" {
t.Fatalf(`Unexpected Content-Type header, got %q`, got)
}

var responseBody versionResponse
if err := json.NewDecoder(w.Body).Decode(&responseBody); err != nil {
t.Fatalf("Unexpected JSON decoding error: %v", err)
}

if responseBody.Version != version.Version {
t.Fatalf(`Unexpected version, got %q instead of %q`, responseBody.Version, version.Version)
}

if responseBody.Commit != version.Commit {
t.Fatalf(`Unexpected commit, got %q instead of %q`, responseBody.Commit, version.Commit)
}

if responseBody.BuildDate != version.BuildDate {
t.Fatalf(`Unexpected build date, got %q instead of %q`, responseBody.BuildDate, version.BuildDate)
}

if responseBody.GoVersion != runtime.Version() {
t.Fatalf(`Unexpected Go version, got %q instead of %q`, responseBody.GoVersion, runtime.Version())
}

if responseBody.Compiler != runtime.Compiler {
t.Fatalf(`Unexpected compiler, got %q instead of %q`, responseBody.Compiler, runtime.Compiler)
}

if responseBody.Arch != runtime.GOARCH {
t.Fatalf(`Unexpected architecture, got %q instead of %q`, responseBody.Arch, runtime.GOARCH)
}

if responseBody.OS != runtime.GOOS {
t.Fatalf(`Unexpected OS, got %q instead of %q`, responseBody.OS, runtime.GOOS)
}
}

func TestNewHandlerSupportsBasePathStripping(t *testing.T) {
scenarios := []struct {
name string
prefix string
path string
}{
{name: "empty base path", prefix: "", path: "/v1/users"},
{name: "non empty base path", prefix: "/base", path: "/base/v1/users"},
}

for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
handler := http.StripPrefix(scenario.prefix, NewHandler(nil, nil))

r := httptest.NewRequest(http.MethodOptions, scenario.path, nil)
w := httptest.NewRecorder()

handler.ServeHTTP(w, r)

if got := w.Code; got != http.StatusNoContent {
t.Fatalf(`Unexpected status code, got %d instead of %d`, got, http.StatusNoContent)
}
})
}
}
Loading
Loading
2BEC
0