github.com/germla/auth@v0.0.0-20230505173936-bc9a4159cf17/controller.go (about) 1 package auth 2 3 import ( 4 "net/http" 5 "path" 6 "strings" 7 8 "github.com/germla/auth/claims" 9 ) 10 11 // NewServeMux generate http.Handler for auth 12 func (auth *Auth) NewServeMux() http.Handler { 13 return &serveMux{Auth: auth} 14 } 15 16 type serveMux struct { 17 *Auth 18 } 19 20 // ServeHTTP dispatches the handler registered in the matched route 21 func (serveMux *serveMux) ServeHTTP(w http.ResponseWriter, req *http.Request) { 22 var ( 23 claims *claims.Claims 24 reqPath = strings.TrimPrefix(req.URL.Path, serveMux.URLPrefix) 25 paths = strings.Split(reqPath, "/") 26 context = &Context{Auth: serveMux.Auth, Claims: claims, Request: req, Writer: w} 27 ) 28 29 if len(paths) >= 2 { 30 // render assets 31 if paths[0] == "assets" { 32 DefaultAssetHandler(context) 33 return 34 } 35 36 // eg: /phone/login 37 if provider := serveMux.Auth.GetProvider(paths[0]); provider != nil { 38 context.Provider = provider 39 40 // serve mux 41 switch paths[1] { 42 case "login": 43 provider.Login(context) 44 case "logout": 45 provider.Logout(context) 46 case "register": 47 provider.Register(context) 48 case "callback": 49 provider.Callback(context) 50 default: 51 provider.ServeHTTP(context) 52 } 53 return 54 } 55 } 56 57 http.NotFound(w, req) 58 } 59 60 // AuthURL generate URL for auth 61 func (auth *Auth) AuthURL(pth string) string { 62 return path.Join(auth.URLPrefix, pth) 63 }