auth
2014-07-18
Child:7b9e0fc20256
auth/util.go
Start rewriting the repo. This code originally was a carbon copy of https://github.com/RangelReale/osin, but I am methodically stripping out the extensible nature of it for a simpler interface, while simultaneously bringing the style into line with the Ducky style.
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/util.go Fri Jul 18 07:13:22 2014 -0400 1.3 @@ -0,0 +1,63 @@ 1.4 +package oauth2 1.5 + 1.6 +import ( 1.7 + "encoding/base64" 1.8 + "errors" 1.9 + "net/http" 1.10 + "strings" 1.11 +) 1.12 + 1.13 +var ( 1.14 + BasicAuthNotSetError = errors.New("Authorization header not set.") 1.15 + InvalidBasicAuthTypeError = errors.New("Invalid basic auth type.") 1.16 + InvalidBasicAuthMessage = errors.New("Invalid basic auth format.") 1.17 +) 1.18 + 1.19 +// Parse basic authentication header 1.20 +type BasicAuth struct { 1.21 + Username string 1.22 + Password string 1.23 +} 1.24 + 1.25 +// Return authorization header data 1.26 +func CheckBasicAuth(r *http.Request) (BasicAuth, error) { 1.27 + if r.Header.Get("Authorization") == "" { 1.28 + return BasicAuth{}, BasicAuthNotSetError 1.29 + } 1.30 + 1.31 + s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) 1.32 + if len(s) != 2 || s[0] != "Basic" { 1.33 + return BasicAuth{}, InvalidBasicAuthTypeError 1.34 + } 1.35 + 1.36 + b, err := base64.StdEncoding.DecodeString(s[1]) 1.37 + if err != nil { 1.38 + return BasicAuth{}, err 1.39 + } 1.40 + pair := strings.SplitN(string(b), ":", 2) 1.41 + if len(pair) != 2 { 1.42 + return BasicAuth{}, InvalidBasicAuthMessage 1.43 + } 1.44 + 1.45 + return BasicAuth{Username: pair[0], Password: pair[1]}, nil 1.46 +} 1.47 + 1.48 +// getClientAuth checks client basic authentication in params if allowed, 1.49 +// otherwise gets it from the header. 1.50 +func getClientAuth(r *http.Request, allowQueryParams bool) (BasicAuth, error) { 1.51 + 1.52 + if allowQueryParams { 1.53 + // Allow for auth without password 1.54 + if _, hasSecret := r.Form["client_secret"]; hasSecret { 1.55 + auth := BasicAuth{ 1.56 + Username: r.Form.Get("client_id"), 1.57 + Password: r.Form.Get("client_secret"), 1.58 + } 1.59 + if auth.Username != "" { 1.60 + return auth, nil 1.61 + } 1.62 + } 1.63 + } 1.64 + 1.65 + return CheckBasicAuth(r) 1.66 +}