neko/internal/api/members/handler.go

84 lines
1.8 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"
2021-08-30 03:09:13 +12:00
"errors"
2020-11-22 11:39:24 +13:00
"net/http"
2020-10-31 06:16:21 +13:00
"github.com/go-chi/chi"
"github.com/demodesk/neko/pkg/auth"
"github.com/demodesk/neko/pkg/types"
"github.com/demodesk/neko/pkg/utils"
2020-11-22 11:39:24 +13:00
)
type key int
2021-09-03 07:37:24 +12:00
const keyMemberCtx key = iota
2020-10-31 06:16:21 +13:00
2020-11-22 11:42:34 +13:00
type MembersHandler struct {
2021-03-15 02:44:32 +13:00
members types.MemberManager
2020-10-31 06:16:21 +13:00
}
func New(
2021-03-15 02:44:32 +13:00
members types.MemberManager,
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{
2021-03-15 02:44:32 +13:00
members: members,
2020-10-31 06:16:21 +13:00
}
}
2021-09-17 10:58:50 +12:00
func (h *MembersHandler) Route(r types.Router) {
2020-11-22 11:57:54 +13:00
r.Get("/", h.membersList)
2020-11-22 11:39:24 +13:00
2021-09-17 10:58:50 +12:00
r.With(auth.AdminsOnly).Group(func(r types.Router) {
2020-11-22 11:42:34 +13:00
r.Post("/", h.membersCreate)
2021-09-17 10:58:50 +12:00
r.With(h.ExtractMember).Route("/{memberId}", func(r types.Router) {
2020-11-22 11:57:54 +13:00
r.Get("/", h.membersRead)
2021-03-15 02:44:32 +13:00
r.Post("/", h.membersUpdateProfile)
r.Post("/password", h.membersUpdatePassword)
2020-11-22 11:57:54 +13:00
r.Delete("/", h.membersDelete)
})
2020-11-22 11:39:24 +13:00
})
}
2021-09-17 10:58:50 +12:00
func (h *MembersHandler) RouteBulk(r types.Router) {
r.With(auth.AdminsOnly).Group(func(r types.Router) {
2021-04-06 09:03:49 +12:00
r.Post("/update", h.membersBulkUpdate)
2023-11-20 03:19:47 +13:00
r.Post("/delete", h.membersBulkDelete)
2021-04-06 09:03:49 +12:00
})
}
2021-03-15 02:44:32 +13:00
type MemberData struct {
ID string
Profile types.MemberProfile
}
2021-09-17 10:58:50 +12:00
func SetMember(r *http.Request, session MemberData) context.Context {
return context.WithValue(r.Context(), keyMemberCtx, session)
2020-11-22 11:39:24 +13:00
}
2021-03-15 02:44:32 +13:00
func GetMember(r *http.Request) MemberData {
return r.Context().Value(keyMemberCtx).(MemberData)
2020-11-22 11:39:24 +13:00
}
2021-09-17 10:58:50 +12:00
func (h *MembersHandler) ExtractMember(w http.ResponseWriter, r *http.Request) (context.Context, error) {
memberId := chi.URLParam(r, "memberId")
2021-08-30 03:09:13 +12:00
2021-09-17 10:58:50 +12:00
profile, err := h.members.Select(memberId)
if err != nil {
if errors.Is(err, types.ErrMemberDoesNotExist) {
return nil, utils.HttpNotFound("member not found")
2020-11-22 11:39:24 +13:00
}
2021-08-30 03:09:13 +12:00
2021-09-17 10:58:50 +12:00
return nil, utils.HttpInternalServerError().WithInternalErr(err)
}
return SetMember(r, MemberData{
ID: memberId,
Profile: profile,
}), nil
2020-10-31 06:16:21 +13:00
}