71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package snap
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.twelvetwelve.org/library/snap/auth"
|
|
)
|
|
|
|
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,
|
|
}
|
|
return r
|
|
}
|
|
|
|
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, ok := r.auth.DoAuth(w, req)
|
|
if !ok {
|
|
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
|
|
}
|
|
c := s.makeContext(rec, w, req)
|
|
r.contentHandler(c)
|
|
}
|
|
}
|
|
|
|
func NewRouteBuilder() *RouteBuilder {
|
|
return &RouteBuilder{}
|
|
}
|