ducky/devices
ducky/devices/vendor/code.secondbit.org/trout.hg/route.go
Add updating devices to apiv1. We needed a way to be able to update devices after they were created. This is supported in the devices package, we just needed to expose it using apiv1 endpoints. In doing so, it became apparent that allowing users to change the Owner of their Devices wasn't properly thought through, and pending a reason to use it, I'm just removing it. The biggest issue came when trying to return usable error messages; we couldn't distinguish between "you don't own the device you're trying to update" and "you're not allowed to change the owner of the device". I also couldn't figure out _who should be able to_ change the owner of the device, which is generally an indication that I'm building a feature before I have a use case for it. To support this change, the apiv1.DeviceChange type needed its Owner property removed. I also needed to add deviceFromAPI and devicesFromAPI helpers to return devices.Device types from apiv1.Device types. There's now a new validateDeviceUpdate helper that checks to ensure that a device update request is valid and the user has the appropriate permissions. The createRequest type now accepts a slice of Devices, not a slice of DeviceChanges, because we want to pass the Owner in. A new updateRequest type is created, which accepts a DeviceChange to apply. A new handleUpdateDevice handler is created, which is assigned to the endpoint for PATCH requests against a device ID. It checks that the user is logged in, the Device they're trying to update exists, and that it's a valid update. If all of that is true, the device is updated and the updated device is returned. Finally, we had to add two new scopes to support new functionality: ScopeUpdateOtherUserDevices allows a user to update other user's devices, and ScopeUpdateLastSeen allows a user to update the LastSeen property of a device. Pending some better error messages, this should be a full implementation of updating a device, which leaves only the deletion endpoint to deal with.
| paddy@15 | 1 package trout |
| paddy@15 | 2 |
| paddy@15 | 3 import ( |
| paddy@15 | 4 "net/http" |
| paddy@15 | 5 "strconv" |
| paddy@15 | 6 "strings" |
| paddy@15 | 7 "time" |
| paddy@15 | 8 ) |
| paddy@15 | 9 |
| paddy@15 | 10 var ( |
| paddy@15 | 11 default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| paddy@15 | 12 w.WriteHeader(http.StatusNotFound) |
| paddy@15 | 13 w.Write([]byte("404 Not Found")) |
| paddy@15 | 14 return |
| paddy@15 | 15 })) |
| paddy@15 | 16 default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| paddy@19 | 17 w.Header().Set("Allow", strings.Join(r.Header[http.CanonicalHeaderKey("Trout-Methods")], ", ")) |
| paddy@15 | 18 w.WriteHeader(http.StatusMethodNotAllowed) |
| paddy@15 | 19 w.Write([]byte("405 Method Not Allowed")) |
| paddy@15 | 20 return |
| paddy@15 | 21 })) |
| paddy@15 | 22 ) |
| paddy@15 | 23 |
| paddy@15 | 24 // RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in |
| paddy@15 | 25 // your URL template will be available in the returned Header as a slice of strings, one for each instance of |
| paddy@15 | 26 // the {parameter}. In the case of a parameter name being used more than once in the same URL template, the |
| paddy@15 | 27 // values will be in the slice in the order they appeared in the template. |
| paddy@15 | 28 // |
| paddy@15 | 29 // Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple |
| paddy@15 | 30 // values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting. |
| paddy@15 | 31 // When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map, |
| paddy@15 | 32 // the parameter name needs to have http.CanonicalHeaderKey applied manually. |
| paddy@15 | 33 func RequestVars(r *http.Request) http.Header { |
| paddy@15 | 34 res := http.Header{} |
| paddy@15 | 35 for h, v := range r.Header { |
| paddy@15 | 36 stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-")) |
| paddy@15 | 37 if stripped != h { |
| paddy@15 | 38 res[stripped] = v |
| paddy@15 | 39 } |
| paddy@15 | 40 } |
| paddy@15 | 41 return res |
| paddy@15 | 42 } |
| paddy@15 | 43 |
| paddy@15 | 44 // Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to |
| paddy@15 | 45 // Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned |
| paddy@15 | 46 // to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler |
| paddy@15 | 47 // set for the HTTP method that the request used. Should either of these properties be unset, a default |
| paddy@15 | 48 // http.Handler will be used. |
| paddy@15 | 49 // |
| paddy@15 | 50 // The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding |
| paddy@15 | 51 // Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously |
| paddy@15 | 52 // routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended |
| paddy@15 | 53 // to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use |
| paddy@15 | 54 // case is unsupported. |
| paddy@15 | 55 type Router struct { |
| paddy@15 | 56 t *trie |
| paddy@15 | 57 Handle404 http.Handler |
| paddy@15 | 58 Handle405 http.Handler |
| paddy@15 | 59 } |
| paddy@15 | 60 |
| paddy@15 | 61 func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) { |
| paddy@15 | 62 h := default404Handler |
| paddy@15 | 63 if router.Handle404 != nil { |
| paddy@15 | 64 h = router.Handle404 |
| paddy@15 | 65 } |
| paddy@15 | 66 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) |
| paddy@15 | 67 h.ServeHTTP(w, r) |
| paddy@15 | 68 } |
| paddy@15 | 69 |
| paddy@15 | 70 func (router *Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) { |
| paddy@15 | 71 h := default405Handler |
| paddy@15 | 72 if router.Handle405 != nil { |
| paddy@15 | 73 h = router.Handle405 |
| paddy@15 | 74 } |
| paddy@15 | 75 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) |
| paddy@15 | 76 h.ServeHTTP(w, r) |
| paddy@15 | 77 } |
| paddy@15 | 78 |
| paddy@15 | 79 func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| paddy@15 | 80 start := time.Now() |
| paddy@15 | 81 if router.t == nil { |
| paddy@15 | 82 router.serve404(w, r, start) |
| paddy@15 | 83 return |
| paddy@15 | 84 } |
| paddy@15 | 85 pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/") |
| paddy@15 | 86 router.t.RLock() |
| paddy@15 | 87 defer router.t.RUnlock() |
| paddy@15 | 88 branches := make([]*branch, len(pieces)) |
| paddy@15 | 89 path, ok := router.t.match(pieces) |
| paddy@15 | 90 if !ok { |
| paddy@15 | 91 router.serve404(w, r, start) |
| paddy@15 | 92 return |
| paddy@15 | 93 } |
| paddy@15 | 94 b := router.t.branch |
| paddy@15 | 95 for i, pos := range path { |
| paddy@15 | 96 b = b.children[pos] |
| paddy@15 | 97 branches[i] = b |
| paddy@15 | 98 } |
| paddy@15 | 99 v := vars(branches, pieces) |
| paddy@15 | 100 for key, vals := range v { |
| paddy@15 | 101 r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals |
| paddy@15 | 102 } |
| paddy@15 | 103 ms := make([]string, len(b.methods)) |
| paddy@15 | 104 i := 0 |
| paddy@15 | 105 for m := range b.methods { |
| paddy@15 | 106 ms[i] = m |
| paddy@15 | 107 i = i + 1 |
| paddy@15 | 108 } |
| paddy@15 | 109 r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms |
| paddy@15 | 110 h := b.methods[r.Method] |
| paddy@15 | 111 if h == nil { |
| paddy@15 | 112 router.serve405(w, r, start) |
| paddy@15 | 113 return |
| paddy@15 | 114 } |
| paddy@15 | 115 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10)) |
| paddy@15 | 116 h.ServeHTTP(w, r) |
| paddy@15 | 117 } |
| paddy@15 | 118 |
| paddy@15 | 119 // Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces |
| paddy@15 | 120 // to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id` |
| paddy@15 | 121 // that should be filled with whatever the request has in that space. |
| paddy@15 | 122 // |
| paddy@15 | 123 // Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations |
| paddy@15 | 124 // on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters". |
| paddy@15 | 125 func (router *Router) Endpoint(e string) *Endpoint { |
| paddy@15 | 126 e = strings.Trim(e, "/") |
| paddy@15 | 127 e = strings.ToLower(e) |
| paddy@15 | 128 pieces := strings.Split(e, "/") |
| paddy@15 | 129 if router.t == nil { |
| paddy@15 | 130 router.t = &trie{} |
| paddy@15 | 131 } |
| paddy@15 | 132 router.t.Lock() |
| paddy@15 | 133 defer router.t.Unlock() |
| paddy@15 | 134 if router.t.branch == nil { |
| paddy@15 | 135 router.t.branch = &branch{ |
| paddy@15 | 136 parent: nil, |
| paddy@15 | 137 children: []*branch{}, |
| paddy@15 | 138 key: "", |
| paddy@15 | 139 isParam: false, |
| paddy@15 | 140 methods: map[string]http.Handler{}, |
| paddy@15 | 141 } |
| paddy@15 | 142 } |
| paddy@15 | 143 closest := findClosestLeaf(pieces, router.t.branch) |
| paddy@15 | 144 b := router.t.branch |
| paddy@15 | 145 for _, pos := range closest { |
| paddy@15 | 146 b = b.children[pos] |
| paddy@15 | 147 } |
| paddy@15 | 148 if len(closest) == len(pieces) { |
| paddy@15 | 149 return (*Endpoint)(b) |
| paddy@15 | 150 } |
| paddy@15 | 151 offset := len(closest) |
| paddy@15 | 152 for i := offset; i < len(pieces); i++ { |
| paddy@15 | 153 piece := pieces[i] |
| paddy@15 | 154 var isParam bool |
| paddy@15 | 155 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" { |
| paddy@15 | 156 isParam = true |
| paddy@15 | 157 piece = piece[1 : len(piece)-1] |
| paddy@15 | 158 } |
| paddy@15 | 159 b = b.addChild(piece, isParam) |
| paddy@15 | 160 } |
| paddy@15 | 161 return (*Endpoint)(b) |
| paddy@15 | 162 } |
| paddy@15 | 163 |
| paddy@15 | 164 func vars(path []*branch, pieces []string) map[string][]string { |
| paddy@15 | 165 v := map[string][]string{} |
| paddy@15 | 166 for pos, p := range path { |
| paddy@15 | 167 if !p.isParam { |
| paddy@15 | 168 continue |
| paddy@15 | 169 } |
| paddy@15 | 170 _, ok := v[p.key] |
| paddy@15 | 171 if !ok { |
| paddy@15 | 172 v[p.key] = []string{pieces[pos]} |
| paddy@15 | 173 continue |
| paddy@15 | 174 } |
| paddy@15 | 175 v[p.key] = append(v[p.key], pieces[pos]) |
| paddy@15 | 176 } |
| paddy@15 | 177 return v |
| paddy@15 | 178 } |
| paddy@15 | 179 |
| paddy@15 | 180 func findClosestLeaf(pieces []string, b *branch) []int { |
| paddy@15 | 181 offset := 0 |
| paddy@15 | 182 path := []int{} |
| paddy@15 | 183 longest := []int{} |
| paddy@15 | 184 num := len(pieces) |
| paddy@15 | 185 for i := 0; i < num; i++ { |
| paddy@15 | 186 piece := pieces[i] |
| paddy@15 | 187 var isParam bool |
| paddy@15 | 188 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" { |
| paddy@15 | 189 isParam = true |
| paddy@15 | 190 piece = piece[1 : len(piece)-1] |
| paddy@15 | 191 } |
| paddy@15 | 192 offset = pickNextRoute(b, offset, piece, isParam) |
| paddy@15 | 193 if offset == -1 { |
| paddy@15 | 194 if len(path) == 0 { |
| paddy@15 | 195 // exhausted our options, bail |
| paddy@15 | 196 break |
| paddy@15 | 197 } |
| paddy@15 | 198 // no match, maybe save this and backup |
| paddy@15 | 199 if len(path) > len(longest) { |
| paddy@15 | 200 longest = append([]int{}, path...) // copy them over so they don't get modified |
| paddy@15 | 201 } |
| paddy@15 | 202 path, offset = backup(path) |
| paddy@15 | 203 offset = offset + 1 |
| paddy@15 | 204 b = b.parent |
| paddy@15 | 205 i = i - 2 |
| paddy@15 | 206 } else { |
| paddy@15 | 207 path = append(path, offset) |
| paddy@15 | 208 b = b.children[offset] |
| paddy@15 | 209 offset = 0 |
| paddy@15 | 210 } |
| paddy@15 | 211 } |
| paddy@15 | 212 if len(longest) < len(path) { |
| paddy@15 | 213 longest = append([]int{}, path...) |
| paddy@15 | 214 } |
| paddy@15 | 215 return longest |
| paddy@15 | 216 } |
| paddy@15 | 217 |
| paddy@15 | 218 func pickNextRoute(b *branch, offset int, input string, variable bool) int { |
| paddy@15 | 219 count := len(b.children) |
| paddy@15 | 220 for i := offset; i < count; i++ { |
| paddy@19 | 221 if b.children[i].key == input && b.children[i].isParam == variable { |
| paddy@15 | 222 return i |
| paddy@15 | 223 } |
| paddy@15 | 224 } |
| paddy@15 | 225 return -1 |
| paddy@15 | 226 } |
| paddy@15 | 227 |
| paddy@15 | 228 // Endpoint defines a single URL template that requests can be matched against. It uses |
| paddy@15 | 229 // URL parameters to accept variables in the URL structure and make them available to |
| paddy@15 | 230 // the Handlers associated with the Endpoint. |
| paddy@15 | 231 type Endpoint branch |
| paddy@15 | 232 |
| paddy@15 | 233 // Handler associates the passed http.Handler with the Endpoint. This http.Handler will be |
| paddy@15 | 234 // used for all requests, regardless of the HTTP method they are using, unless overridden by |
| paddy@15 | 235 // the Methods method. Endpoints without a http.Handler associated with them will not be |
| paddy@15 | 236 // considered matches for requests, unless the request was made using an HTTP method that the |
| paddy@15 | 237 // Endpoint has an http.Handler mapped to. |
| paddy@15 | 238 func (e *Endpoint) Handler(h http.Handler) { |
| paddy@15 | 239 (*branch)(e).setHandler("", h) |
| paddy@15 | 240 } |
| paddy@15 | 241 |
| paddy@15 | 242 // Methods simple returns a Methods object that will enable the mapping of the passed HTTP |
| paddy@15 | 243 // request methods to a Methods object. On its own, this function does not modify anything. It |
| paddy@15 | 244 // should, instead, be used as a friendly shorthand to get to the Methods.Handler method. |
| paddy@15 | 245 func (e *Endpoint) Methods(m ...string) Methods { |
| paddy@15 | 246 return Methods{ |
| paddy@15 | 247 e: e, |
| paddy@15 | 248 m: m, |
| paddy@15 | 249 } |
| paddy@15 | 250 } |
| paddy@15 | 251 |
| paddy@15 | 252 // Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to |
| paddy@15 | 253 // specific http.Handlers. Its sole purpose is to enable the Methods.Handler method. |
| paddy@15 | 254 type Methods struct { |
| paddy@15 | 255 e *Endpoint |
| paddy@15 | 256 m []string |
| paddy@15 | 257 } |
| paddy@15 | 258 |
| paddy@15 | 259 // Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler |
| paddy@15 | 260 // associated with the Endpoint to only handle specific HTTP method(s). |
| paddy@15 | 261 func (m Methods) Handler(h http.Handler) { |
| paddy@15 | 262 b := (*branch)(m.e) |
| paddy@15 | 263 for _, method := range m.m { |
| paddy@15 | 264 b.setHandler(method, h) |
| paddy@15 | 265 } |
| paddy@15 | 266 } |