2020-10-31 06:16:21 +13:00
|
|
|
package member
|
|
|
|
|
|
|
|
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"
|
|
|
|
|
|
|
|
"demodesk/neko/internal/types"
|
2020-11-22 11:39:24 +13:00
|
|
|
"demodesk/neko/internal/utils"
|
|
|
|
"demodesk/neko/internal/http/auth"
|
|
|
|
)
|
|
|
|
|
|
|
|
type key int
|
|
|
|
|
|
|
|
const (
|
|
|
|
keyMemberCtx key = iota
|
2020-10-31 06:16:21 +13:00
|
|
|
)
|
|
|
|
|
|
|
|
type MemberHandler 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,
|
|
|
|
) *MemberHandler {
|
|
|
|
// Init
|
|
|
|
|
|
|
|
return &MemberHandler{
|
2020-11-02 04:54:06 +13:00
|
|
|
sessions: sessions,
|
2020-10-31 06:16:21 +13:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-15 06:16:25 +13:00
|
|
|
func (h *MemberHandler) Route(r chi.Router) {
|
|
|
|
|
2020-11-22 11:39:24 +13:00
|
|
|
r.With(auth.AdminsOnly).Group(func(r chi.Router) {
|
|
|
|
r.Get("/", h.memberList)
|
|
|
|
|
|
|
|
r.Post("/", h.memberCreate)
|
|
|
|
r.Get("/{memberId}/", h.memberRead)
|
|
|
|
r.Post("/{memberId}/", h.memberUpdate)
|
|
|
|
r.Delete("/{memberId}/", h.memberDelete)
|
|
|
|
})
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *MemberHandler) ExtractMember(next http.Handler) http.Handler {
|
|
|
|
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
|
|
|
}
|