refactor: deduplicate sha1Hex/writeJSON/writeError into pkg/utils
- admin.go: replace local sha1Hex, sha256Hex, writeJSON, writeError with pkg/utils equivalents - auth.go: replace local writeJSON with utils.WriteJSON; rewrite writeError as thin wrapper - cas.go: remove local sha1Hex and unused writeJSON; use utils.SHA1Bytes - pkg/utils.go: add WriteJSON, WriteError; reorder imports
This commit is contained in:
@@ -6,14 +6,14 @@
|
||||
package cas
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/pkg/utils"
|
||||
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/internal/config"
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/internal/database"
|
||||
)
|
||||
@@ -148,7 +148,7 @@ func isValidHash(hash string) bool {
|
||||
// StoreFile writes data to the CAS directory structure.
|
||||
// Returns the SHA-1 hash of the stored data.
|
||||
func StoreFile(casDir string, data []byte) (string, error) {
|
||||
hash := sha1Hex(data)
|
||||
hash := utils.SHA1Bytes(data)
|
||||
destDir := filepath.Join(casDir, hash[:2])
|
||||
if err := os.MkdirAll(destDir, 0o755); err != nil {
|
||||
return "", err
|
||||
@@ -170,7 +170,7 @@ func FileExists(casDir, hash string) bool {
|
||||
// VerifyAndStore writes data to CAS only if the SHA-1 matches the expected hash.
|
||||
// This prevents corrupt or tampered uploads from being stored.
|
||||
func VerifyAndStore(casDir string, data []byte, expectedHash string) (string, error) {
|
||||
got := sha1Hex(data)
|
||||
got := utils.SHA1Bytes(data)
|
||||
if subtle.ConstantTimeCompare([]byte(got), []byte(expectedHash)) != 1 {
|
||||
return "", ErrHashMismatch
|
||||
}
|
||||
@@ -188,13 +188,3 @@ var ErrHashMismatch = errHashMismatch
|
||||
type hashMismatchError struct{}
|
||||
|
||||
func (e *hashMismatchError) Error() string { return "SHA-1 hash mismatch" }
|
||||
|
||||
func sha1Hex(data []byte) string {
|
||||
h := sha1.Sum(data)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user