2024-10-29 23:08:11 +00:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.1e99.eu/1e99/passed/storage"
|
|
|
|
)
|
|
|
|
|
|
|
|
func CreatePassword(store storage.Store, maxLength int, encoding *base64.Encoding) http.HandlerFunc {
|
|
|
|
return func(res http.ResponseWriter, req *http.Request) {
|
|
|
|
var reqBody struct {
|
2024-11-08 15:02:26 +00:00
|
|
|
// Go automatically decodes byte arrays using Base64
|
|
|
|
Password []byte `json:"password"`
|
2024-10-30 10:25:42 +00:00
|
|
|
ExpiresIn time.Duration `json:"expires-in"`
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
err := json.NewDecoder(req.Body).Decode(&reqBody)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(res, "Malformed JSON body", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-11-08 15:02:26 +00:00
|
|
|
if len(reqBody.Password) > maxLength {
|
2024-11-08 15:03:00 +00:00
|
|
|
http.Error(res, "Password too long", http.StatusRequestEntityTooLarge)
|
2024-10-29 23:08:11 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-10-30 10:25:42 +00:00
|
|
|
expiresIn := reqBody.ExpiresIn * time.Second
|
|
|
|
if expiresIn <= 0 {
|
|
|
|
http.Error(res, "Too short expires-in", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if expiresIn > 2*7*24*time.Hour {
|
|
|
|
http.Error(res, "Too long expires-in", http.StatusBadRequest)
|
2024-10-29 23:08:11 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-10-30 10:17:48 +00:00
|
|
|
id, err := store.Create(
|
2024-11-08 15:02:26 +00:00
|
|
|
reqBody.Password,
|
2024-10-29 23:08:11 +00:00
|
|
|
time.Now().Add(expiresIn),
|
|
|
|
)
|
|
|
|
switch {
|
|
|
|
case err == storage.ErrFull:
|
|
|
|
http.Error(res, "Insufficient storage", http.StatusInsufficientStorage)
|
|
|
|
return
|
|
|
|
case err != nil:
|
|
|
|
http.Error(res, "", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resBody := struct {
|
|
|
|
Id string `json:"id"`
|
|
|
|
}{
|
|
|
|
Id: id,
|
|
|
|
}
|
|
|
|
err = json.NewEncoder(res).Encode(&resBody)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(res, "", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|