You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
109 lines
2.1 KiB
109 lines
2.1 KiB
package handlers
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.vdhsn.com/adam/bodytrack/internal/services"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/jwtauth/v5"
|
|
)
|
|
|
|
type Stats struct {
|
|
Conn services.DB
|
|
}
|
|
|
|
func (s Stats) Subscribe(c chi.Router) error {
|
|
c.Group(func(r chi.Router) {
|
|
r.Use(services.NewJWTVerifier())
|
|
r.Use(jwtauth.Authenticator)
|
|
|
|
r.Put("/stats", s.putLog)
|
|
r.Get("/stats", s.getLog)
|
|
})
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s Stats) getLog(res http.ResponseWriter, req *http.Request) {
|
|
fail := APIResp{Payload: "Unauthorized", Status: http.StatusUnauthorized}
|
|
userId, err := services.GetUserIDFromClaims(req)
|
|
if err != nil {
|
|
fail.Payload = err.Error()
|
|
fail.Write(res)
|
|
return
|
|
}
|
|
|
|
queryStrs := req.URL.Query()
|
|
startStr := queryStrs.Get("start")
|
|
endStr := queryStrs.Get("end")
|
|
typeStr := queryStrs.Get("type")
|
|
|
|
start := time.Now().UTC().Add(-time.Hour * 24 * 30)
|
|
|
|
if startStr != "" {
|
|
start, _ = time.Parse(time.RFC3339, startStr)
|
|
}
|
|
|
|
end := time.Now().UTC()
|
|
if endStr != "" {
|
|
end, _ = time.Parse(time.RFC3339, endStr)
|
|
}
|
|
|
|
wlog, err := s.Conn.GetLog(userId, start, end, services.ParseLogTypes(typeStr))
|
|
if err != nil {
|
|
log.Println(err)
|
|
fail.Write(res)
|
|
return
|
|
}
|
|
|
|
APIResp{
|
|
Success: true,
|
|
Payload: struct {
|
|
Log []services.StatLog `json:"log"`
|
|
Count int `json:"count"`
|
|
Start time.Time `json:"start"`
|
|
End time.Time `json:"end"`
|
|
}{
|
|
Log: wlog,
|
|
Count: len(wlog),
|
|
Start: start,
|
|
End: end,
|
|
},
|
|
}.Write(res)
|
|
|
|
}
|
|
|
|
func (s Stats) putLog(res http.ResponseWriter, req *http.Request) {
|
|
fail := APIResp{Payload: "Unauthorized", Status: http.StatusUnauthorized}
|
|
userId, err := services.GetUserIDFromClaims(req)
|
|
if err != nil {
|
|
fail.Payload = err.Error()
|
|
fail.Write(res)
|
|
return
|
|
}
|
|
|
|
type logWeightInput struct {
|
|
services.StatLog
|
|
}
|
|
|
|
var in logWeightInput
|
|
|
|
if err := ParseCall(&in, res, req); err != nil {
|
|
fail.Payload = "Could not read arguments"
|
|
fail.Status = http.StatusUnprocessableEntity
|
|
fail.Write(res)
|
|
return
|
|
}
|
|
|
|
if err := s.Conn.AddLog(userId, in.StatLog); err != nil {
|
|
log.Println(err)
|
|
fail.Write(res)
|
|
return
|
|
}
|
|
|
|
APIResp{Success: true}.Write(res)
|
|
|
|
}
|