auth
auth/oauth2.go
Write Session tests. Add loginURI as a property to our Context, to keep track of where users should be redirected to log in. Implement the sessionStore in the memstore to let us test with Sessions. Catch when the HTTP Basic Auth header doesn't include two parts, rather than panicking. Return an ErrInvalidAuthFormat. Clean up the error handling for checkCookie to be cleaner. Log unexpected errors from request.Cookie. Stop checking for cookie expiration times--those aren't sent to the server, so we'll never get a valid session if we look for them. Add a helper to build a login redirect URI--a URI the user can be redirected to that has a URL-encoded URL to redirect the user back to after a successful login. Add a wrapper to wrap our Context into HTTP handlers. Create a RegisterOAuth2 helper that adds the OAuth2 endpoints to a Gorilla/mux router. Redirect users to the login page when they have no session set or an invalid session. Return a server error when we can't check our cookie for whatever reason. Log errors. Add sessions to our OAuth2 tests so the tests stop failing--the session check was interfering with them. Add a test for our getBasicAuth helper to ensure that we're parsing basic auth correctly. Add an ErrSessionAlreadyExists error to be returned when a session has an ID conflict. Test that our memstore implementation of the sessionStore works as intended..
1.1 --- a/oauth2.go Tue Nov 11 21:30:47 2014 -0500 1.2 +++ b/oauth2.go Tue Nov 18 03:28:14 2014 -0500 1.3 @@ -5,10 +5,12 @@ 1.4 "encoding/json" 1.5 "errors" 1.6 "html/template" 1.7 + "log" 1.8 "net/http" 1.9 "net/url" 1.10 "strings" 1.11 "time" 1.12 + "github.com/gorilla/mux" 1.13 1.14 "crypto/sha256" 1.15 "code.secondbit.org/pass" 1.16 @@ -55,21 +57,20 @@ 1.17 return "", "", ErrInvalidAuthFormat 1.18 } 1.19 info := strings.SplitN(string(decoded), ":", 2) 1.20 + if len(info) < 2 { 1.21 + return "", "", ErrInvalidAuthFormat 1.22 + } 1.23 return info[0], info[1], nil 1.24 } 1.25 1.26 func checkCookie(r *http.Request, context Context) (Session, error) { 1.27 cookie, err := r.Cookie(authCookieName) 1.28 - if err != nil { 1.29 - if err == http.ErrNoCookie { 1.30 - return Session{}, ErrNoSession 1.31 - } 1.32 + if err == http.ErrNoCookie { 1.33 + return Session{}, ErrNoSession 1.34 + } else if err != nil { 1.35 + log.Println(err) 1.36 return Session{}, err 1.37 } 1.38 - if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) || 1.39 - !cookie.Secure || !cookie.HttpOnly { 1.40 - return Session{}, ErrInvalidSession 1.41 - } 1.42 sess, err := context.GetSession(cookie.Value) 1.43 if err == ErrSessionNotFound { 1.44 return Session{}, ErrInvalidSession 1.45 @@ -82,6 +83,17 @@ 1.46 return sess, nil 1.47 } 1.48 1.49 +func buildLoginRedirect(r *http.Request, context Context) string { 1.50 + if context.loginURI == nil { 1.51 + return "" 1.52 + } 1.53 + uri := *context.loginURI 1.54 + q := uri.Query() 1.55 + q.Set("from", url.QueryEscape(r.URL.String())) 1.56 + uri.RawQuery = q.Encode() 1.57 + return uri.String() 1.58 +} 1.59 + 1.60 func authenticate(user, passphrase string, context Context) (Profile, error) { 1.61 profile, err := context.GetProfileByLogin(user) 1.62 if err != nil { 1.63 @@ -102,17 +114,42 @@ 1.64 return profile, nil 1.65 } 1.66 1.67 +func wrap(context Context, f func(w http.ResponseWriter, r *http.Request, context Context)) http.Handler { 1.68 + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1.69 + f(w, r, context) 1.70 + }) 1.71 +} 1.72 + 1.73 +// RegisterOAuth2 adds handlers to the passed router to handle the OAuth2 endpoints. 1.74 +func RegisterOAuth2(r *mux.Router, context Context) { 1.75 + r.Handle("/authorize", wrap(context, GetGrantHandler)) 1.76 + r.Handle("/token", wrap(context, GetTokenHandler)) 1.77 +} 1.78 + 1.79 // GetGrantHandler presents and processes the page for asking a user to grant access 1.80 // to their data. See RFC 6749, Section 4.1. 1.81 func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) { 1.82 session, err := checkCookie(r, context) 1.83 if err != nil { 1.84 if err == ErrNoSession || err == ErrInvalidSession { 1.85 - // TODO(paddy): redirect to login screen 1.86 - //return 1.87 + redir := buildLoginRedirect(r, context) 1.88 + if redir == "" { 1.89 + log.Println("No login URL configured.") 1.90 + w.WriteHeader(http.StatusInternalServerError) 1.91 + context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.92 + "internal_error": template.HTML("Missing login URL."), 1.93 + }) 1.94 + return 1.95 + } 1.96 + http.Redirect(w, r, redir, http.StatusFound) 1.97 + return 1.98 } 1.99 - // TODO(paddy): return a server error 1.100 - //return 1.101 + log.Println(err.Error()) 1.102 + w.WriteHeader(http.StatusInternalServerError) 1.103 + context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.104 + "internal_error": template.HTML(err.Error()), 1.105 + }) 1.106 + return 1.107 } 1.108 if r.URL.Query().Get("client_id") == "" { 1.109 w.WriteHeader(http.StatusBadRequest) 1.110 @@ -146,6 +183,7 @@ 1.111 "error": template.HTML("The specified Client couldn’t be found."), 1.112 }) 1.113 } else { 1.114 + log.Println(err.Error()) 1.115 w.WriteHeader(http.StatusInternalServerError) 1.116 context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.117 "internal_error": template.HTML(err.Error()), 1.118 @@ -157,6 +195,7 @@ 1.119 // the client has registered 1.120 numEndpoints, err := context.CountEndpoints(clientID) 1.121 if err != nil { 1.122 + log.Println(err.Error()) 1.123 w.WriteHeader(http.StatusInternalServerError) 1.124 context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.125 "internal_error": template.HTML(err.Error()), 1.126 @@ -168,6 +207,7 @@ 1.127 // BUG(paddy): We really should normalize URIs before trying to compare them. 1.128 validURI, err = context.CheckEndpoint(clientID, redirectURI) 1.129 if err != nil { 1.130 + log.Println(err.Error()) 1.131 w.WriteHeader(http.StatusInternalServerError) 1.132 context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.133 "internal_error": template.HTML(err.Error()), 1.134 @@ -180,6 +220,7 @@ 1.135 validURI = true 1.136 endpoints, err := context.ListEndpoints(clientID, 1, 0) 1.137 if err != nil { 1.138 + log.Println(err.Error()) 1.139 w.WriteHeader(http.StatusInternalServerError) 1.140 context.Render(w, getGrantTemplateName, map[string]interface{}{ 1.141 "internal_error": template.HTML(err.Error()),