netbird/management/server/http/handler/peers.go
Mikhail Bragin 3c47a3c408
peer management HTTP API (#81)
* feature: create account for a newly registered user

* feature: finalize user auth flow

* feature: create protected API with JWT

* chore: cleanup http server

* feature: add UI assets

* chore: update react UI

* refactor: move account not exists -> create to AccountManager

* chore: update UI

* chore: return only peers on peers endpoint

* chore: add UI path to the config

* chore: remove ui from management

* chore: remove unused Docker comamnds

* docs: update management config sample

* fix: store creation

* feature: introduce peer response to the HTTP api

* fix: lint errors

* feature: add setup-keys HTTP endpoint

* fix: return empty json arrays in HTTP API

* feature: add new peer response fields
2021-08-12 12:49:10 +02:00

68 lines
1.6 KiB
Go

package handler
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/wiretrustee/wiretrustee/management/server"
"net/http"
"time"
)
// Peers is a handler that returns peers of the account
type Peers struct {
accountManager *server.AccountManager
}
// PeerResponse is a response sent to the client
type PeerResponse struct {
Name string
IP string
Connected bool
LastSeen time.Time
Os string
}
func NewPeers(accountManager *server.AccountManager) *Peers {
return &Peers{
accountManager: accountManager,
}
}
func (h *Peers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
accountId := extractAccountIdFromRequestContext(r)
//new user -> create a new account
account, err := h.accountManager.GetOrCreateAccount(accountId)
if err != nil {
log.Errorf("failed getting user account %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
respBody := []*PeerResponse{}
for _, peer := range account.Peers {
respBody = append(respBody, &PeerResponse{
Name: peer.Key,
IP: peer.IP.String(),
LastSeen: time.Now(),
Connected: false,
Os: "Ubuntu 21.04 (Hirsute Hippo)",
})
}
err = json.NewEncoder(w).Encode(respBody)
if err != nil {
log.Errorf("failed encoding account peers %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
case http.MethodOptions:
default:
http.Error(w, "", http.StatusNotFound)
}
}