mattermost-plugin-cleanup-c.../server/api.go
Felipe M. 2ecbd2442d
Some checks failed
ci / test (push) Failing after 1m5s
ci / lint (push) Failing after 1m6s
ci / build (push) Failing after 1m6s
release / release (push) Failing after 50s
Add Mattermost plugin for system-admin channel cleanup.
Provide a channel header menu action and /cleanup-channel slash command so system administrators can remove all messages from a channel, with admin checks enforced on both the web app and server. Configure CI and release workflows for the Forgejo runner and signed plugin bundles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:46:39 +02:00

74 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/gorilla/mux"
"github.com/mattermost/mattermost/server/public/plugin"
)
type cleanupRequest struct {
ChannelID string `json:"channel_id"`
}
type cleanupResponse struct {
Deleted int `json:"deleted"`
}
func (p *Plugin) initRouter() *mux.Router {
router := mux.NewRouter()
router.Use(p.requireLoggedInUser)
apiRouter := router.PathPrefix("/api/v1").Subrouter()
apiRouter.HandleFunc("/cleanup", p.handleCleanup).Methods(http.MethodPost)
return router
}
func (p *Plugin) ServeHTTP(_ *plugin.Context, w http.ResponseWriter, r *http.Request) {
p.router.ServeHTTP(w, r)
}
func (p *Plugin) requireLoggedInUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Mattermost-User-ID") == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func (p *Plugin) handleCleanup(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
var req cleanupRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if req.ChannelID == "" {
http.Error(w, "channel_id is required", http.StatusBadRequest)
return
}
deleted, err := p.cleanupChannel(userID, req.ChannelID)
if err != nil {
if errors.Is(err, errPermissionDenied) {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
p.client.Log.Error("Failed to cleanup channel", "channel_id", req.ChannelID, "error", err)
http.Error(w, "Failed to cleanup channel", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(cleanupResponse{Deleted: deleted}); err != nil {
p.client.Log.Error("Failed to encode cleanup response", "error", err)
}
}