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