oauth2/server.go

53 lines
1.4 KiB
Go
Raw Normal View History

2024-10-01 17:38:43 +00:00
package oauth2
import (
"fmt"
"net/http"
"somehole.com/common/log"
"somehole.com/common/oauth2/server"
)
type Server struct {
*http.ServeMux
2024-10-02 17:45:42 +00:00
basePath string
Logger log.Logger
2024-10-01 17:38:43 +00:00
}
2024-10-02 17:45:42 +00:00
func NewServer(mux *http.ServeMux, basePath string, logger log.Logger) *Server {
2024-10-01 17:38:43 +00:00
if mux == nil {
mux = http.NewServeMux()
}
return &Server{
ServeMux: mux,
2024-10-02 17:45:42 +00:00
basePath: basePath,
2024-10-01 17:38:43 +00:00
Logger: logger,
}
}
2024-10-02 17:45:42 +00:00
func (s *Server) Handle(pattern string, handler http.Handler) {
s.ServeMux.Handle(s.basePath+pattern, handler)
}
2024-10-01 17:38:43 +00:00
func (s *Server) RegisterCallbackServer(srv server.CallbackServer) {
2024-10-01 22:57:46 +00:00
s.Handle(server.CallbackEndpoint, server.NewServer(server.CallbackRequest{}, []string{http.MethodPost}, s.Logger, func(req server.Request) (res server.Response, errRes server.ErrorResponse) {
2024-10-01 17:38:43 +00:00
callbackRequest, ok := req.(*server.CallbackRequest)
if !ok {
panic(fmt.Errorf("expected CallbackRequest, got %T", req))
}
res, errRes = srv.Callback(callbackRequest)
return
}))
}
func (s *Server) RegisterTokenServer(srv server.TokenServer) {
2024-10-01 22:57:46 +00:00
s.Handle(server.TokenEndpoint, server.NewServer(server.TokenRequest{}, []string{http.MethodPost}, s.Logger, func(req server.Request) (res server.Response, errRes server.ErrorResponse) {
2024-10-01 17:38:43 +00:00
tokenRequest, ok := req.(*server.TokenRequest)
if !ok {
panic(fmt.Errorf("expected TokenRequest, got %T", req))
}
res, errRes = srv.Token(tokenRequest)
return
}))
}