Validate device creation.
Update our uuid package to the latest, which is now based on the GitHub
fork instead of the Google Code. Also, update our api package to its latest
version, which now needs the pqarrays package as a dependency.
We fleshed out the validateDeviceCreation. We now pass in the scopes we have
(for broad access control) and the user ID (for fine-grained access control).
This helper returns the first error it encounters, though it should probably
return a slice so we can return multiple errors all at once.
Before we even decode the request to create a Device, let's check if the user is
even logged in. If we can't ascertain that or they're not, there's no point in
even consuming the memory necessary to read the request, because we know we're
not going to use it anyways.
Finally actually validate the devices we're creating, and return an appropriate
error for each error we can get.
Also, the api.CheckScopes helper function now takes the scopes passed in as a
string slice, and we have an api.GetScopes helper function to retrieve the
scopes associated with the request. Let's not keep parsing that.
We need two new scopes to control access for device creation; ScopeImport lets
users import devices in and is pretty much admin access.
ScopeCreateOtherUserDevices allows a user to create Devices that are owned by
another user.
11 "bitbucket.org/ww/goautoneg"
13 "code.secondbit.org/uuid.hg"
15 "golang.org/x/net/context"
19 RequestErrAccessDenied = "access_denied"
20 RequestErrInsufficient = "insufficient"
21 RequestErrOverflow = "overflow"
22 RequestErrInvalidValue = "invalid_value"
23 RequestErrInvalidFormat = "invalid_format"
24 RequestErrMissing = "missing"
25 RequestErrNotFound = "not_found"
26 RequestErrConflict = "conflict"
27 RequestErrActOfGod = "act_of_god"
31 ActOfGodError = []RequestError{{Slug: RequestErrActOfGod}}
32 InvalidFormatError = []RequestError{{Slug: RequestErrInvalidFormat, Field: "/"}}
33 AccessDeniedError = []RequestError{{Slug: RequestErrAccessDenied}}
35 Encoders = []string{"application/json"}
37 ErrUserIDNotSet = errors.New("user ID not set")
40 type RequestError struct {
41 Slug string `json:"error,omitempty"`
42 Field string `json:"field,omitempty"`
43 Param string `json:"param,omitempty"`
44 Header string `json:"header,omitempty"`
47 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request)
49 func NegotiateMiddleware(h http.Handler) http.Handler {
50 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
51 if r.Header.Get("Accept") != "" {
52 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
53 if contentType == "" {
54 w.WriteHeader(http.StatusNotAcceptable)
55 w.Write([]byte("Unsupported content type requested: " + r.Header.Get("Accept")))
63 func Encode(w http.ResponseWriter, r *http.Request, status int, resp interface{}) {
64 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
65 w.Header().Set("content-type", contentType)
69 case "application/json":
70 enc := json.NewEncoder(w)
71 err = enc.Encode(resp)
73 enc := json.NewEncoder(w)
74 err = enc.Encode(resp)
81 func Decode(r *http.Request, target interface{}) error {
83 switch r.Header.Get("Content-Type") {
84 case "application/json":
85 dec := json.NewDecoder(r.Body)
86 return dec.Decode(target)
88 dec := json.NewDecoder(r.Body)
89 return dec.Decode(target)
93 func CORSMiddleware(h http.Handler) http.Handler {
94 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
95 w.Header().Set("Access-Control-Allow-Origin", "*")
96 w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
97 w.Header().Set("Access-Control-Allow-Credentials", "true")
98 if strings.ToLower(r.Method) == "options" {
99 methods := strings.Join(r.Header[http.CanonicalHeaderKey("Trout-Methods")], ", ")
100 w.Header().Set("Access-Control-Allow-Methods", methods)
101 w.Header().Set("Allow", methods)
102 w.WriteHeader(http.StatusOK)
109 func ContextWrapper(c context.Context, handler ContextHandler) http.Handler {
110 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
115 func CheckScopes(scopes []string, checking ...string) bool {
117 for _, scope := range checking {
118 found := sort.SearchStrings(scopes, scope)
119 if found == len(scopes) || scopes[found] != scope {
126 func GetScopes(r *http.Request) []string {
127 scopes := strings.Split(r.Header.Get("scopes"), " ")
128 for pos, scope := range scopes {
129 scopes[pos] = strings.TrimSpace(scope)
135 func AuthUser(r *http.Request) (uuid.ID, error) {
136 rawID := r.Header.Get("User-ID")
138 return nil, ErrUserIDNotSet
140 return uuid.Parse(rawID)