99 lines
2.1 KiB
Go
99 lines
2.1 KiB
Go
package admin
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.maze.io/maze/styx/dataset"
|
|
)
|
|
|
|
func (a *Admin) apiLists(w http.ResponseWriter, r *http.Request) {
|
|
lists, err := a.Storage.Lists()
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
a.jsonResponse(w, r, lists)
|
|
}
|
|
|
|
func (a *Admin) apiList(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
list, err := a.Storage.ListByID(id)
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
a.jsonResponse(w, r, list)
|
|
}
|
|
|
|
func (a *Admin) apiListCreate(w http.ResponseWriter, r *http.Request) {
|
|
var request struct {
|
|
dataset.List
|
|
Groups []int64 `json:"groups"`
|
|
ID int64 `json:"id"` // mask, not used
|
|
CreatedAt time.Time `json:"created_at"` // mask, not used
|
|
UpdatedAt time.Time `json:"updated_at"` // mask, not used
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
|
|
if err := a.verifyList(&request.List); err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
|
|
request.List.Groups = request.List.Groups[:0]
|
|
for _, id := range request.Groups {
|
|
group, err := a.Storage.GroupByID(id)
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
request.List.Groups = append(request.List.Groups, group)
|
|
}
|
|
|
|
if err := a.Storage.SaveList(&request.List); err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
|
|
a.jsonResponse(w, r, request.List)
|
|
}
|
|
|
|
func (a *Admin) apiListDelete(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
list, err := a.Storage.ListByID(id)
|
|
if err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
if err = a.Storage.DeleteList(list); err != nil {
|
|
a.handleAPIError(w, r, err)
|
|
return
|
|
}
|
|
a.jsonResponse(w, r, nil)
|
|
}
|
|
|
|
func (a *Admin) verifyList(list *dataset.List) error {
|
|
switch list.Type {
|
|
case dataset.ListTypeDomain, dataset.ListTypeNetwork:
|
|
default:
|
|
return apiError{Err: fmt.Errorf("unknown list type %q", list.Type)}
|
|
}
|
|
|
|
return nil
|
|
}
|