local-server/cmd/dkl-local-server/ws-store.go

81 lines
1.4 KiB
Go
Raw Normal View History

2023-02-13 12:03:42 +00:00
package main
import (
2023-09-10 14:47:54 +00:00
"strconv"
"strings"
2023-02-13 12:03:42 +00:00
restful "github.com/emicklei/go-restful"
2023-09-10 14:47:54 +00:00
"novit.tech/direktil/local-server/secretstore"
2023-02-13 12:03:42 +00:00
)
func wsStoreAddKey(req *restful.Request, resp *restful.Response) {
2023-09-10 14:47:54 +00:00
np := NamedPassphrase{}
2023-02-13 12:03:42 +00:00
2023-09-10 14:47:54 +00:00
err := req.ReadEntity(&np)
2023-02-13 12:03:42 +00:00
if err != nil {
wsBadRequest(resp, err.Error())
return
}
2023-09-10 14:47:54 +00:00
np.Name = strings.TrimSpace(np.Name)
if len(np.Name) == 0 {
wsBadRequest(resp, "no name given")
return
}
if len(np.Passphrase) == 0 {
2023-02-13 12:03:42 +00:00
wsBadRequest(resp, "no passphrase given")
return
}
2023-09-10 14:47:54 +00:00
for _, k := range secStore.Keys {
if k.Name == np.Name {
wsBadRequest(resp, "there's already a passphrase named "+strconv.Quote(np.Name))
return
}
}
2024-01-07 10:18:50 +00:00
secStore.AddKey(np.Name, np.Passphrase)
defer updateState()
2023-09-10 14:47:54 +00:00
err = secStore.SaveTo(secKeysStorePath())
if err != nil {
wsError(resp, err)
return
}
}
func wsStoreDelKey(req *restful.Request, resp *restful.Response) {
name := ""
err := req.ReadEntity(&name)
if err != nil {
wsBadRequest(resp, err.Error())
return
}
newKeys := make([]secretstore.KeyEntry, 0, len(secStore.Keys))
for _, k := range secStore.Keys {
if k.Name == name {
continue
}
newKeys = append(newKeys, k)
}
if len(newKeys) == 0 {
wsBadRequest(resp, "can't remove the last key from the store")
return
}
secStore.Keys = newKeys
defer updateState()
2023-02-13 12:03:42 +00:00
err = secStore.SaveTo(secKeysStorePath())
if err != nil {
wsError(resp, err)
return
}
}