snap/route.go

77 lines
1.7 KiB
Go
Raw Permalink Normal View History

2021-06-18 19:43:52 +00:00
package snap
import (
"fmt"
"net/http"
2023-05-23 14:09:57 +00:00
"git.twelvetwelve.org/library/snap/auth"
2021-06-18 19:43:52 +00:00
)
type RouteBuilder struct {
auth auth.Authenticator
contentHandler func(c *Context)
loginHandler func(c *Context) bool
}
func (r *RouteBuilder) WithLoginHandler(loginHandler func(c *Context) bool) *RouteBuilder {
return &RouteBuilder{
auth: r.auth,
loginHandler: loginHandler,
contentHandler: r.contentHandler,
}
}
func (r *RouteBuilder) WithAuth(auth auth.Authenticator) *RouteBuilder {
return &RouteBuilder{
auth: auth,
loginHandler: r.loginHandler,
contentHandler: r.contentHandler,
}
}
func (r *RouteBuilder) WithContent(contentHandler func(c *Context)) *RouteBuilder {
return &RouteBuilder{
auth: r.auth,
loginHandler: r.loginHandler,
contentHandler: contentHandler,
}
}
func (r *RouteBuilder) BuildRoute(s *Server) http.HandlerFunc {
if r.auth == nil {
return func(w http.ResponseWriter, req *http.Request) {
c := s.makeContext(nil, w, req)
r.contentHandler(c)
}
}
return func(w http.ResponseWriter, req *http.Request) {
rec, code := r.auth.DoAuth(w, req)
switch code {
case http.StatusOK:
c := s.makeContext(rec, w, req)
r.contentHandler(c)
return
case http.StatusUnauthorized:
2021-06-18 19:43:52 +00:00
if r.loginHandler != nil {
c := s.makeContext(rec, w, req)
if r.loginHandler(c) == false {
return
}
}
fmt.Printf("Sending to: %s\n", req.URL.Path)
req.Method = http.MethodGet
http.Redirect(w, req, req.URL.Path, http.StatusSeeOther)
return
default:
http.Error(w, http.StatusText(code), code)
2021-06-18 19:43:52 +00:00
}
}
}
func NewRouteBuilder() *RouteBuilder {
return &RouteBuilder{}
}