2022-03-21 22:27:35 +00:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/julienschmidt/httprouter"
|
2022-03-22 22:59:09 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2022-03-21 22:27:35 +00:00
|
|
|
"github.com/unrolled/render"
|
2022-03-22 22:59:09 +00:00
|
|
|
|
|
|
|
"go.mills.io/saltyim"
|
2022-03-21 22:27:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// API ...
|
|
|
|
type API struct {
|
|
|
|
router *Router
|
|
|
|
config *Config
|
|
|
|
db Store
|
|
|
|
|
|
|
|
r *render.Render
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewAPI ...
|
|
|
|
func NewAPI(router *Router, config *Config, db Store) *API {
|
|
|
|
api := &API{router, config, db, render.New()}
|
|
|
|
|
|
|
|
api.initRoutes()
|
|
|
|
|
|
|
|
return api
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *API) initRoutes() {
|
|
|
|
router := a.router.Group("/api/v1")
|
|
|
|
|
|
|
|
router.GET("/ping", a.PingEndpoint())
|
2022-03-22 22:59:09 +00:00
|
|
|
router.POST("/register", a.RegisterEndpoint())
|
2022-03-21 22:27:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PingEndpoint ...
|
|
|
|
func (a *API) PingEndpoint() httprouter.Handle {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
_, _ = w.Write([]byte(`{}`))
|
|
|
|
}
|
|
|
|
}
|
2022-03-22 22:59:09 +00:00
|
|
|
|
|
|
|
// RegisterEndpoint ...
|
|
|
|
func (a *API) RegisterEndpoint() httprouter.Handle {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
|
|
|
req, signer, err := saltyim.NewRegisterRequest(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("error parsing register request")
|
|
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if signer != req.Key {
|
|
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-26 14:43:05 +00:00
|
|
|
if err := CreateConfig(a.config, req.Addr.Hash(), req.Key); err != nil {
|
2022-03-24 04:11:51 +00:00
|
|
|
log.WithError(err).Errorf("error creating config for %s", req.Addr.String())
|
2022-03-22 22:59:09 +00:00
|
|
|
http.Error(w, "Error", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Error(w, "Account Created", http.StatusCreated)
|
|
|
|
}
|
|
|
|
}
|