2020-10-30 10:23:30 +13:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/go-chi/chi"
|
2020-10-31 22:48:24 +13:00
|
|
|
"github.com/go-chi/jwtauth"
|
2020-10-30 10:23:30 +13:00
|
|
|
|
2020-10-31 06:16:21 +13:00
|
|
|
"demodesk/neko/internal/api/member"
|
|
|
|
"demodesk/neko/internal/api/room"
|
|
|
|
"demodesk/neko/internal/types"
|
2020-10-31 22:48:24 +13:00
|
|
|
"demodesk/neko/internal/types/config"
|
2020-10-30 10:23:30 +13:00
|
|
|
)
|
|
|
|
|
2020-10-31 06:16:21 +13:00
|
|
|
type API struct {
|
|
|
|
sessions types.SessionManager
|
|
|
|
remote types.RemoteManager
|
|
|
|
broadcast types.BroadcastManager
|
|
|
|
websocket types.WebSocketHandler
|
2020-10-30 10:23:30 +13:00
|
|
|
}
|
|
|
|
|
2020-10-31 22:48:24 +13:00
|
|
|
var AdminToken *jwtauth.JWTAuth
|
|
|
|
var UserToken *jwtauth.JWTAuth
|
|
|
|
|
2020-10-31 06:16:21 +13:00
|
|
|
func New(
|
|
|
|
sessions types.SessionManager,
|
|
|
|
remote types.RemoteManager,
|
|
|
|
broadcast types.BroadcastManager,
|
|
|
|
websocket types.WebSocketHandler,
|
2020-10-31 22:48:24 +13:00
|
|
|
conf *config.Server,
|
2020-10-31 06:16:21 +13:00
|
|
|
) *API {
|
2020-10-31 22:48:24 +13:00
|
|
|
AdminToken = jwtauth.New("HS256", []byte(conf.AdminToken), nil)
|
|
|
|
UserToken = jwtauth.New("HS256", []byte(conf.UserToken), nil)
|
2020-10-31 06:16:21 +13:00
|
|
|
|
|
|
|
return &API{
|
|
|
|
sessions: sessions,
|
|
|
|
remote: remote,
|
|
|
|
broadcast: broadcast,
|
|
|
|
websocket: websocket,
|
|
|
|
}
|
2020-10-30 10:23:30 +13:00
|
|
|
}
|
|
|
|
|
2020-10-31 22:48:24 +13:00
|
|
|
func (a *API) Mount(r *chi.Mux) {
|
2020-10-31 06:16:21 +13:00
|
|
|
memberHandler := member.New(a.sessions, a.websocket)
|
2020-10-31 22:48:24 +13:00
|
|
|
r.Mount("/member", memberHandler.Router(UsersOnly, AdminsOnly))
|
2020-10-30 10:23:30 +13:00
|
|
|
|
2020-10-31 06:16:21 +13:00
|
|
|
roomHandler := room.New(a.sessions, a.remote, a.broadcast, a.websocket)
|
2020-10-31 22:48:24 +13:00
|
|
|
r.Mount("/room", roomHandler.Router(UsersOnly, AdminsOnly))
|
|
|
|
}
|
|
|
|
|
|
|
|
func UsersOnly(r chi.Router, protectedRoutes func(r chi.Router)) {
|
|
|
|
r.Group(func(r chi.Router) {
|
|
|
|
// Verify JWT tokens
|
|
|
|
r.Use(jwtauth.Verifier(UserToken))
|
|
|
|
r.Use(jwtauth.Verifier(AdminToken))
|
|
|
|
|
|
|
|
// Handle valid / invalid tokens.
|
|
|
|
r.Use(jwtauth.Authenticator)
|
|
|
|
|
|
|
|
protectedRoutes(r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func AdminsOnly(r chi.Router, protectedRoutes func(r chi.Router)) {
|
|
|
|
r.Group(func(r chi.Router) {
|
|
|
|
// Verify JWT token
|
|
|
|
r.Use(jwtauth.Verifier(AdminToken))
|
|
|
|
|
|
|
|
// Handle valid / invalid tokens.
|
|
|
|
r.Use(jwtauth.Authenticator)
|
|
|
|
|
|
|
|
protectedRoutes(r)
|
|
|
|
})
|
2020-10-30 10:23:30 +13:00
|
|
|
}
|