ducky/devices

Paddy 2016-01-02 Parent:a700ede02f91

20:ed1b5ba69551 Go to Latest

ducky/devices/vendor/code.secondbit.org/api.hg/api.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.

History
paddy@15 1 package api
paddy@15 2
paddy@15 3 import (
paddy@15 4 "encoding/json"
paddy@15 5 "errors"
paddy@15 6 "log"
paddy@15 7 "net/http"
paddy@16 8 "sort"
paddy@15 9 "strings"
paddy@15 10
paddy@15 11 "bitbucket.org/ww/goautoneg"
paddy@15 12
paddy@15 13 "code.secondbit.org/uuid.hg"
paddy@15 14
paddy@15 15 "golang.org/x/net/context"
paddy@15 16 )
paddy@15 17
paddy@15 18 const (
paddy@15 19 RequestErrAccessDenied = "access_denied"
paddy@15 20 RequestErrInsufficient = "insufficient"
paddy@15 21 RequestErrOverflow = "overflow"
paddy@15 22 RequestErrInvalidValue = "invalid_value"
paddy@15 23 RequestErrInvalidFormat = "invalid_format"
paddy@15 24 RequestErrMissing = "missing"
paddy@15 25 RequestErrNotFound = "not_found"
paddy@15 26 RequestErrConflict = "conflict"
paddy@15 27 RequestErrActOfGod = "act_of_god"
paddy@15 28 )
paddy@15 29
paddy@15 30 var (
paddy@15 31 ActOfGodError = []RequestError{{Slug: RequestErrActOfGod}}
paddy@15 32 InvalidFormatError = []RequestError{{Slug: RequestErrInvalidFormat, Field: "/"}}
paddy@16 33 AccessDeniedError = []RequestError{{Slug: RequestErrAccessDenied}}
paddy@15 34
paddy@15 35 Encoders = []string{"application/json"}
paddy@15 36
paddy@15 37 ErrUserIDNotSet = errors.New("user ID not set")
paddy@15 38 )
paddy@15 39
paddy@15 40 type RequestError struct {
paddy@15 41 Slug string `json:"error,omitempty"`
paddy@15 42 Field string `json:"field,omitempty"`
paddy@15 43 Param string `json:"param,omitempty"`
paddy@15 44 Header string `json:"header,omitempty"`
paddy@15 45 }
paddy@15 46
paddy@15 47 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request)
paddy@15 48
paddy@15 49 func NegotiateMiddleware(h http.Handler) http.Handler {
paddy@15 50 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paddy@15 51 if r.Header.Get("Accept") != "" {
paddy@15 52 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
paddy@15 53 if contentType == "" {
paddy@15 54 w.WriteHeader(http.StatusNotAcceptable)
paddy@15 55 w.Write([]byte("Unsupported content type requested: " + r.Header.Get("Accept")))
paddy@15 56 return
paddy@15 57 }
paddy@15 58 }
paddy@15 59 h.ServeHTTP(w, r)
paddy@15 60 })
paddy@15 61 }
paddy@15 62
paddy@15 63 func Encode(w http.ResponseWriter, r *http.Request, status int, resp interface{}) {
paddy@15 64 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
paddy@15 65 w.Header().Set("content-type", contentType)
paddy@15 66 w.WriteHeader(status)
paddy@15 67 var err error
paddy@15 68 switch contentType {
paddy@15 69 case "application/json":
paddy@15 70 enc := json.NewEncoder(w)
paddy@15 71 err = enc.Encode(resp)
paddy@15 72 default:
paddy@15 73 enc := json.NewEncoder(w)
paddy@15 74 err = enc.Encode(resp)
paddy@15 75 }
paddy@15 76 if err != nil {
paddy@15 77 log.Println(err)
paddy@15 78 }
paddy@15 79 }
paddy@15 80
paddy@15 81 func Decode(r *http.Request, target interface{}) error {
paddy@15 82 defer r.Body.Close()
paddy@15 83 switch r.Header.Get("Content-Type") {
paddy@15 84 case "application/json":
paddy@15 85 dec := json.NewDecoder(r.Body)
paddy@15 86 return dec.Decode(target)
paddy@15 87 default:
paddy@15 88 dec := json.NewDecoder(r.Body)
paddy@15 89 return dec.Decode(target)
paddy@15 90 }
paddy@15 91 }
paddy@15 92
paddy@15 93 func CORSMiddleware(h http.Handler) http.Handler {
paddy@15 94 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paddy@15 95 w.Header().Set("Access-Control-Allow-Origin", "*")
paddy@15 96 w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
paddy@15 97 w.Header().Set("Access-Control-Allow-Credentials", "true")
paddy@15 98 if strings.ToLower(r.Method) == "options" {
paddy@15 99 methods := strings.Join(r.Header[http.CanonicalHeaderKey("Trout-Methods")], ", ")
paddy@15 100 w.Header().Set("Access-Control-Allow-Methods", methods)
paddy@15 101 w.Header().Set("Allow", methods)
paddy@15 102 w.WriteHeader(http.StatusOK)
paddy@15 103 return
paddy@15 104 }
paddy@15 105 h.ServeHTTP(w, r)
paddy@15 106 })
paddy@15 107 }
paddy@15 108
paddy@15 109 func ContextWrapper(c context.Context, handler ContextHandler) http.Handler {
paddy@15 110 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paddy@15 111 handler(c, w, r)
paddy@15 112 })
paddy@15 113 }
paddy@15 114
paddy@16 115 func CheckScopes(scopes []string, checking ...string) bool {
paddy@16 116 sort.Strings(scopes)
paddy@16 117 for _, scope := range checking {
paddy@16 118 found := sort.SearchStrings(scopes, scope)
paddy@16 119 if found == len(scopes) || scopes[found] != scope {
paddy@15 120 return false
paddy@15 121 }
paddy@15 122 }
paddy@15 123 return true
paddy@15 124 }
paddy@15 125
paddy@16 126 func GetScopes(r *http.Request) []string {
paddy@16 127 scopes := strings.Split(r.Header.Get("scopes"), " ")
paddy@16 128 for pos, scope := range scopes {
paddy@16 129 scopes[pos] = strings.TrimSpace(scope)
paddy@16 130 }
paddy@16 131 sort.Strings(scopes)
paddy@16 132 return scopes
paddy@16 133 }
paddy@16 134
paddy@15 135 func AuthUser(r *http.Request) (uuid.ID, error) {
paddy@15 136 rawID := r.Header.Get("User-ID")
paddy@15 137 if rawID == "" {
paddy@15 138 return nil, ErrUserIDNotSet
paddy@15 139 }
paddy@15 140 return uuid.Parse(rawID)
paddy@15 141 }