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.
| paddy@0 | 1 package oauth2 |
| paddy@0 | 2 |
| paddy@0 | 3 import ( |
| paddy@0 | 4 "encoding/base64" |
| paddy@0 | 5 "errors" |
| paddy@0 | 6 "net/http" |
| paddy@0 | 7 "strings" |
| paddy@0 | 8 ) |
| paddy@0 | 9 |
| paddy@0 | 10 var ( |
| paddy@0 | 11 BasicAuthNotSetError = errors.New("Authorization header not set.") |
| paddy@0 | 12 InvalidBasicAuthTypeError = errors.New("Invalid basic auth type.") |
| paddy@0 | 13 InvalidBasicAuthMessage = errors.New("Invalid basic auth format.") |
| paddy@0 | 14 ) |
| paddy@0 | 15 |
| paddy@0 | 16 // Parse basic authentication header |
| paddy@0 | 17 type BasicAuth struct { |
| paddy@0 | 18 Username string |
| paddy@0 | 19 Password string |
| paddy@0 | 20 } |
| paddy@0 | 21 |
| paddy@0 | 22 // Return authorization header data |
| paddy@0 | 23 func CheckBasicAuth(r *http.Request) (BasicAuth, error) { |
| paddy@0 | 24 if r.Header.Get("Authorization") == "" { |
| paddy@0 | 25 return BasicAuth{}, BasicAuthNotSetError |
| paddy@0 | 26 } |
| paddy@0 | 27 |
| paddy@0 | 28 s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) |
| paddy@0 | 29 if len(s) != 2 || s[0] != "Basic" { |
| paddy@0 | 30 return BasicAuth{}, InvalidBasicAuthTypeError |
| paddy@0 | 31 } |
| paddy@0 | 32 |
| paddy@0 | 33 b, err := base64.StdEncoding.DecodeString(s[1]) |
| paddy@0 | 34 if err != nil { |
| paddy@0 | 35 return BasicAuth{}, err |
| paddy@0 | 36 } |
| paddy@0 | 37 pair := strings.SplitN(string(b), ":", 2) |
| paddy@0 | 38 if len(pair) != 2 { |
| paddy@0 | 39 return BasicAuth{}, InvalidBasicAuthMessage |
| paddy@0 | 40 } |
| paddy@0 | 41 |
| paddy@0 | 42 return BasicAuth{Username: pair[0], Password: pair[1]}, nil |
| paddy@0 | 43 } |
| paddy@0 | 44 |
| paddy@0 | 45 // getClientAuth checks client basic authentication in params if allowed, |
| paddy@0 | 46 // otherwise gets it from the header. |
| paddy@0 | 47 func getClientAuth(r *http.Request, allowQueryParams bool) (BasicAuth, error) { |
| paddy@0 | 48 |
| paddy@0 | 49 if allowQueryParams { |
| paddy@0 | 50 // Allow for auth without password |
| paddy@0 | 51 if _, hasSecret := r.Form["client_secret"]; hasSecret { |
| paddy@0 | 52 auth := BasicAuth{ |
| paddy@0 | 53 Username: r.Form.Get("client_id"), |
| paddy@0 | 54 Password: r.Form.Get("client_secret"), |
| paddy@0 | 55 } |
| paddy@0 | 56 if auth.Username != "" { |
| paddy@0 | 57 return auth, nil |
| paddy@0 | 58 } |
| paddy@0 | 59 } |
| paddy@0 | 60 } |
| paddy@0 | 61 |
| paddy@0 | 62 return CheckBasicAuth(r) |
| paddy@0 | 63 } |