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 default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 w.WriteHeader(http.StatusNotFound)
13 w.Write([]byte("404 Not Found"))
16 default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17 w.WriteHeader(http.StatusMethodNotAllowed)
18 w.Write([]byte("405 Method Not Allowed"))
23 // RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in
24 // your URL template will be available in the returned Header as a slice of strings, one for each instance of
25 // the {parameter}. In the case of a parameter name being used more than once in the same URL template, the
26 // values will be in the slice in the order they appeared in the template.
28 // Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple
29 // values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting.
30 // When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map,
31 // the parameter name needs to have http.CanonicalHeaderKey applied manually.
32 func RequestVars(r *http.Request) http.Header {
34 for h, v := range r.Header {
35 stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-"))
43 // Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to
44 // Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned
45 // to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler
46 // set for the HTTP method that the request used. Should either of these properties be unset, a default
47 // http.Handler will be used.
49 // The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding
50 // Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously
51 // routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended
52 // to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use
53 // case is unsupported.
56 Handle404 http.Handler
57 Handle405 http.Handler
60 func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) {
61 h := default404Handler
62 if router.Handle404 != nil {
65 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
69 func (router *Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) {
70 h := default405Handler
71 if router.Handle405 != nil {
74 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
78 func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 router.serve404(w, r, start)
84 pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/")
86 defer router.t.RUnlock()
87 branches := make([]*branch, len(pieces))
88 path, ok := router.t.match(pieces)
90 router.serve404(w, r, start)
94 for i, pos := range path {
98 v := vars(branches, pieces)
99 for key, vals := range v {
100 r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals
102 ms := make([]string, len(b.methods))
104 for m := range b.methods {
108 r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms
109 h := b.methods[r.Method]
111 router.serve405(w, r, start)
114 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10))
118 // Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces
119 // to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id`
120 // that should be filled with whatever the request has in that space.
122 // Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations
123 // on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters".
124 func (router *Router) Endpoint(e string) *Endpoint {
125 e = strings.Trim(e, "/")
126 e = strings.ToLower(e)
127 pieces := strings.Split(e, "/")
132 defer router.t.Unlock()
133 if router.t.branch == nil {
134 router.t.branch = &branch{
136 children: []*branch{},
139 methods: map[string]http.Handler{},
142 closest := findClosestLeaf(pieces, router.t.branch)
144 for _, pos := range closest {
147 if len(closest) == len(pieces) {
148 return (*Endpoint)(b)
150 offset := len(closest)
151 for i := offset; i < len(pieces); i++ {
154 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
156 piece = piece[1 : len(piece)-1]
158 b = b.addChild(piece, isParam)
160 return (*Endpoint)(b)
163 func vars(path []*branch, pieces []string) map[string][]string {
164 v := map[string][]string{}
165 for pos, p := range path {
171 v[p.key] = []string{pieces[pos]}
174 v[p.key] = append(v[p.key], pieces[pos])
179 func findClosestLeaf(pieces []string, b *branch) []int {
184 for i := 0; i < num; i++ {
187 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
189 piece = piece[1 : len(piece)-1]
191 offset = pickNextRoute(b, offset, piece, isParam)
194 // exhausted our options, bail
197 // no match, maybe save this and backup
198 if len(path) > len(longest) {
199 longest = append([]int{}, path...) // copy them over so they don't get modified
201 path, offset = backup(path)
206 path = append(path, offset)
207 b = b.children[offset]
211 if len(longest) < len(path) {
212 longest = append([]int{}, path...)
217 func pickNextRoute(b *branch, offset int, input string, variable bool) int {
218 count := len(b.children)
219 for i := offset; i < count; i++ {
220 if b.children[i].key == input && b.isParam == variable {
227 // Endpoint defines a single URL template that requests can be matched against. It uses
228 // URL parameters to accept variables in the URL structure and make them available to
229 // the Handlers associated with the Endpoint.
232 // Handler associates the passed http.Handler with the Endpoint. This http.Handler will be
233 // used for all requests, regardless of the HTTP method they are using, unless overridden by
234 // the Methods method. Endpoints without a http.Handler associated with them will not be
235 // considered matches for requests, unless the request was made using an HTTP method that the
236 // Endpoint has an http.Handler mapped to.
237 func (e *Endpoint) Handler(h http.Handler) {
238 (*branch)(e).setHandler("", h)
241 // Methods simple returns a Methods object that will enable the mapping of the passed HTTP
242 // request methods to a Methods object. On its own, this function does not modify anything. It
243 // should, instead, be used as a friendly shorthand to get to the Methods.Handler method.
244 func (e *Endpoint) Methods(m ...string) Methods {
251 // Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to
252 // specific http.Handlers. Its sole purpose is to enable the Methods.Handler method.
253 type Methods struct {
258 // Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler
259 // associated with the Endpoint to only handle specific HTTP method(s).
260 func (m Methods) Handler(h http.Handler) {
262 for _, method := range m.m {
263 b.setHandler(method, h)