74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package http
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"go-socket/packages/globals"
|
|
"go-socket/packages/minio"
|
|
"io"
|
|
"net/http"
|
|
|
|
"go-socket/packages/convertions"
|
|
)
|
|
|
|
func HandleFileUpload(response http.ResponseWriter, request *http.Request) {
|
|
if !postValidCheckWithResponseOnFail(&response, request, true) {
|
|
return
|
|
}
|
|
ctx := request.Context()
|
|
|
|
user, err := getUserByToken(ctx, request.Header.Get("token"))
|
|
if err != nil {
|
|
http.Error(response, "invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
connectionId, err := convertions.ConvertStringUuid(request.FormValue("connectionid"))
|
|
if err != nil {
|
|
http.Error(response, "invalid connectionid", http.StatusBadRequest)
|
|
return
|
|
}
|
|
_, ok := user.Connections[connectionId]
|
|
if !ok {
|
|
http.Error(response, "no such connection", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
request.Body = http.MaxBytesReader(response, request.Body, int64(globals.MaxPostWithFileBytes))
|
|
multipartReader, err := request.MultipartReader()
|
|
if err != nil {
|
|
http.Error(response, "expected multipart form", 400)
|
|
return
|
|
}
|
|
|
|
for {
|
|
part, err := multipartReader.NextPart()
|
|
if err == io.EOF {
|
|
http.Error(response, "bad request", 400)
|
|
return
|
|
}
|
|
|
|
if part.FileName() == "" {
|
|
part.Close()
|
|
continue
|
|
}
|
|
|
|
if len(part.FileName()) != sha256.Size {
|
|
part.Close()
|
|
http.Error(response, "filename must be sha256 of whole file", 400)
|
|
return
|
|
}
|
|
|
|
err = minio.Upload(ctx, part.FileName(), part, -1, part.Header.Get("Content-Type"), user.Id)
|
|
if err != nil {
|
|
http.Error(response, "upload failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
part.Close()
|
|
|
|
if err != nil {
|
|
http.Error(response, "upload failed", 500)
|
|
return
|
|
}
|
|
}
|
|
}
|