neko/internal/api/members/handler.go

67 lines
1.3 KiB
Go
Raw Normal View History

2020-11-22 11:42:34 +13:00
package members
2020-10-31 06:16:21 +13:00
import (
2020-11-22 11:39:24 +13:00
"context"
"net/http"
2020-10-31 06:16:21 +13:00
"github.com/go-chi/chi"
2021-02-15 02:40:17 +13:00
"demodesk/neko/internal/http/auth"
2020-10-31 06:16:21 +13:00
"demodesk/neko/internal/types"
2020-11-22 11:39:24 +13:00
"demodesk/neko/internal/utils"
)
type key int
const (
2021-01-09 10:41:37 +13:00
keyMemberCtx key = iota
2020-10-31 06:16:21 +13:00
)
2020-11-22 11:42:34 +13:00
type MembersHandler struct {
2020-11-02 04:54:06 +13:00
sessions types.SessionManager
2020-10-31 06:16:21 +13:00
}
func New(
sessions types.SessionManager,
2020-11-22 11:42:34 +13:00
) *MembersHandler {
2020-10-31 06:16:21 +13:00
// Init
2020-11-22 11:42:34 +13:00
return &MembersHandler{
2020-11-02 04:54:06 +13:00
sessions: sessions,
2020-10-31 06:16:21 +13:00
}
}
2020-11-22 11:42:34 +13:00
func (h *MembersHandler) Route(r chi.Router) {
2020-11-22 11:57:54 +13:00
r.Get("/", h.membersList)
2020-11-22 11:39:24 +13:00
2020-11-22 11:57:54 +13:00
r.With(auth.AdminsOnly).Group(func(r chi.Router) {
2020-11-22 11:42:34 +13:00
r.Post("/", h.membersCreate)
2020-11-22 11:57:54 +13:00
r.With(h.ExtractMember).Route("/{memberId}", func(r chi.Router) {
r.Get("/", h.membersRead)
r.Post("/", h.membersUpdate)
r.Delete("/", h.membersDelete)
})
2020-11-22 11:39:24 +13:00
})
}
func SetMember(r *http.Request, session types.Session) *http.Request {
ctx := context.WithValue(r.Context(), keyMemberCtx, session)
return r.WithContext(ctx)
}
func GetMember(r *http.Request) types.Session {
return r.Context().Value(keyMemberCtx).(types.Session)
}
2020-11-22 11:42:34 +13:00
func (h *MembersHandler) ExtractMember(next http.Handler) http.Handler {
2020-11-22 11:39:24 +13:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
memberId := chi.URLParam(r, "memberId")
session, ok := h.sessions.Get(memberId)
if !ok {
utils.HttpNotFound(w, "Member was not found.")
} else {
next.ServeHTTP(w, SetMember(r, session))
}
})
2020-10-31 06:16:21 +13:00
}