neko/internal/api/router.go

66 lines
1.5 KiB
Go
Raw Normal View History

2020-10-30 10:23:30 +13:00
package api
import (
"context"
2020-11-01 00:27:55 +13:00
"net/http"
2020-10-30 10:23:30 +13:00
"github.com/go-chi/chi"
2020-11-01 00:27:55 +13:00
2020-10-31 06:16:21 +13:00
"demodesk/neko/internal/api/member"
"demodesk/neko/internal/api/room"
"demodesk/neko/internal/types"
"demodesk/neko/internal/utils"
2020-11-02 04:54:06 +13:00
"demodesk/neko/internal/config"
2020-10-30 10:23:30 +13:00
)
2020-11-02 04:54:06 +13:00
type ApiManagerCtx struct {
sessions types.SessionManager
desktop types.DesktopManager
capture types.CaptureManager
2020-10-30 10:23:30 +13:00
}
const (
keySessionCtx int = iota
)
2020-10-31 22:48:24 +13:00
2020-10-31 06:16:21 +13:00
func New(
sessions types.SessionManager,
2020-11-02 04:54:06 +13:00
desktop types.DesktopManager,
capture types.CaptureManager,
2020-10-31 22:48:24 +13:00
conf *config.Server,
2020-11-02 04:54:06 +13:00
) *ApiManagerCtx {
2020-10-31 06:16:21 +13:00
2020-11-02 04:54:06 +13:00
return &ApiManagerCtx{
2020-10-31 06:16:21 +13:00
sessions: sessions,
2020-11-02 04:54:06 +13:00
desktop: desktop,
capture: capture,
2020-10-31 06:16:21 +13:00
}
2020-10-30 10:23:30 +13:00
}
func (api *ApiManagerCtx) Mount(r *chi.Mux) {
r.Use(api.Authenticate)
2020-10-30 10:23:30 +13:00
memberHandler := member.New(api.sessions)
r.Mount("/member", memberHandler.Router())
roomHandler := room.New(api.sessions, api.desktop, api.capture)
r.Mount("/room", roomHandler.Router())
2020-10-31 22:48:24 +13:00
r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
session, _ := r.Context().Value(keySessionCtx).(types.Session)
utils.HttpBadRequest(w, "Hi `" + session.ID() + "`, you are authenticated.")
})
2020-10-31 22:48:24 +13:00
}
func (api *ApiManagerCtx) Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := api.sessions.Authenticate(r)
if err != nil {
utils.HttpNotAuthenticated(w, err)
} else {
ctx := context.WithValue(r.Context(), keySessionCtx, session)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
2020-10-30 10:23:30 +13:00
}