deletion endpoints
This commit is contained in:
+62
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -271,6 +272,67 @@ func contentHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if !validPasteId(id) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
var token string
|
||||
switch r.Method {
|
||||
case http.MethodDelete:
|
||||
bearer := r.Header.Get("Authorization")
|
||||
var scheme string
|
||||
var found bool
|
||||
scheme, token, found = strings.Cut(bearer, " ")
|
||||
if !found || scheme != "Bearer" {
|
||||
http.Error(w, "invalid token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
case http.MethodPost:
|
||||
token = r.PostFormValue("delete_token")
|
||||
}
|
||||
|
||||
path := getStoragePath(cfg.UploadDir, id)
|
||||
upload, err := getUploadById(db.WithContext(r.Context()), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
log.Println("get upload:", err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 {
|
||||
http.Error(w, "invalid token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// continue to delete from database IF the file doesnt exist on disk
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
|
||||
log.Println("remove upload file:", err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("remove upload file:", err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func detectMimeType(file io.ReadSeeker) (string, error) {
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewind file: %w", err)
|
||||
|
||||
Reference in New Issue
Block a user