62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
)
|
|
|
|
func downloadFile(w http.ResponseWriter, req *http.Request) {
|
|
fileId := req.FormValue("id")
|
|
if fileId == "" {
|
|
http.Error(w, "Id is missing", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
localFile := localFiles[fileId]
|
|
if localFile == nil {
|
|
http.Error(w, "No file found for Id", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
if localFile.passwordHash != nil {
|
|
_, password, ok := req.BasicAuth()
|
|
showPopup, err := strconv.ParseBool(req.FormValue("show-popup"))
|
|
if err != nil {
|
|
showPopup = true
|
|
}
|
|
|
|
if !ok || password == "" {
|
|
password = req.FormValue("password")
|
|
|
|
if password == "" {
|
|
if showPopup {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted area", charset="UTF-8"`)
|
|
}
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
}
|
|
|
|
_, hash, err := hashPasswordWihSalt(password, localFile.passwordSalt)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if !slices.Equal(hash, localFile.passwordHash) {
|
|
if showPopup {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted area", charset="UTF-8"`)
|
|
}
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
}
|
|
|
|
filename := filepath.Base(localFile.path)
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
|
|
http.ServeFile(w, req, localFile.path)
|
|
}
|