Skip to content
Snippets Groups Projects
bannedfile.go 1.4 KiB
Newer Older
Dean's avatar
Dean committed
package routes

import (
	"database/sql"
	"encoding/hex"
	"net/http"
	"strings"

	"owo.codes/whats-this/api/lib/apierrors"
	"owo.codes/whats-this/api/lib/db"
	"owo.codes/whats-this/api/lib/middleware"

	"github.com/go-chi/render"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
)

// bannedFileResponse is the response format for Object.
type bannedFileResponse struct {
	Success bool       `json:"success"`
	Data    db.FileBan `json:"data"`
}

// BannedFile returns metadata about a banned file to an administrator.
func BannedFile(w http.ResponseWriter, r *http.Request) {
	// Only authorized admin users can use this route
	user := middleware.GetAuthorizedUser(r)
	if user.ID == "" || user.IsBlocked || !user.IsAdmin {
		panic(apierrors.Unauthorized)
	}

	// Get the SHA256 hash
	sha256String := r.URL.Path
	if strings.HasPrefix(sha256String, "/bannedfiles/") {
		sha256String = sha256String[13:]
	}
	sha256, err := hex.DecodeString(sha256String)
	if err != nil {
		panic(apierrors.BadFileID)
	}

	// Get the file ban
	bannedFile, err := db.GetBannedFile(sha256)
	switch {
	case errors.Cause(err) == sql.ErrNoRows:
		panic(apierrors.FileIsNotBanned)
	case err != nil:
		log.Error().Err(err).Msg("failed to get FileBan")
		panic(apierrors.InternalServerError)
	}

	// Return response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	render.JSON(w, r, bannedFileResponse{true, bannedFile})
}