Files
imap-copier/internal/httpapi/accounts.go
T

69 lines
1.9 KiB
Go

package httpapi
import (
"encoding/json"
"net/http"
"strconv"
"github.com/vasyansk/imap-copier/internal/crypto"
"github.com/vasyansk/imap-copier/internal/store"
)
type AccountView struct {
ID int64 `json:"id"`
SrcLogin string `json:"src_login"`
DstLogin string `json:"dst_login"`
TestSrcStatus string `json:"test_src_status"`
TestDstStatus string `json:"test_dst_status"`
Status string `json:"status"`
Copied int64 `json:"copied"`
Skipped int64 `json:"skipped"`
Errors int64 `json:"errors"`
}
func accountDTO(a store.Account) AccountView {
return AccountView{
ID: a.ID, SrcLogin: a.SrcLogin, DstLogin: a.DstLogin,
TestSrcStatus: a.TestSrcStatus, TestDstStatus: a.TestDstStatus,
Status: a.Status, Copied: a.Copied, Skipped: a.Skipped, Errors: a.Errors,
}
}
func pathID(r *http.Request, name string) (int64, error) {
return strconv.ParseInt(r.PathValue(name), 10, 64)
}
func (s *Server) handleCreateAccount(w http.ResponseWriter, r *http.Request) {
taskID, err := pathID(r, "id")
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
var body struct {
SrcLogin, SrcPass, DstLogin, DstPass string
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
srcEnc, err := crypto.Encrypt(s.cfg.EncKey, []byte(body.SrcPass))
if err != nil {
http.Error(w, "encrypt", http.StatusInternalServerError)
return
}
dstEnc, err := crypto.Encrypt(s.cfg.EncKey, []byte(body.DstPass))
if err != nil {
http.Error(w, "encrypt", http.StatusInternalServerError)
return
}
id, err := s.store.CreateAccount(r.Context(), store.Account{
TaskID: taskID, SrcLogin: body.SrcLogin, SrcPassEnc: srcEnc,
DstLogin: body.DstLogin, DstPassEnc: dstEnc,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusCreated, map[string]int64{"id": id})
}