ducky/devices

Paddy 2015-12-22 Parent:ad63b888f899 Child:ed1b5ba69551

18:b2fdf827758e Go to Latest

ducky/devices/apiv1/handlers.go

Add endpoint for retrieving devices. Add an endpoint for retrieving devices, either as a list or by ID. Stub endpoints for updating and deleting devices., along with TODOs marking them as things to still be completed. (Right now, accessing those endpoints is an insta-panic.) Simplify our handleCreateDevices by returning StatusUnauthorized if AuthUser fails, so we can reserve StatusForbidden for when auth succeeds but access is still denied. Also, delay the instantiation and allocation of a Response variable until we're actually going to use it. Create a handleGetDevices handler that authenticates the user, and if no ID is set, returns a list of all their Devices. If one or more IDs are set, only those Devices are returned. If ScopeViewPushToken is one of the scopes associated with the request, the push tokens for each Device will be included in the response. Otherwise, they will be omitted.

History
1 package apiv1
3 import (
4 "fmt"
5 "log"
6 "net/http"
8 "code.secondbit.org/api.hg"
9 "code.secondbit.org/ducky/devices.hg"
10 "code.secondbit.org/trout.hg"
11 "code.secondbit.org/uuid.hg"
13 "golang.org/x/net/context"
14 )
16 type createRequest struct {
17 Devices []DeviceChange `json:"devices"`
18 }
20 func handleCreateDevices(ctx context.Context, w http.ResponseWriter, r *http.Request) {
21 var req createRequest
23 userID, err := api.AuthUser(r)
24 if err != nil {
25 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: api.AccessDeniedError})
26 return
27 }
29 err = api.Decode(r, &req)
30 if err != nil {
31 api.Encode(w, r, http.StatusBadRequest, Response{Errors: api.InvalidFormatError})
32 return
33 }
35 devicesToCreate := createDevicesFromChanges(req.Devices)
36 passedScopes := api.GetScopes(r)
37 for pos, device := range devicesToCreate {
38 err := validateDeviceCreation(device, passedScopes, userID)
39 if err == nil {
40 continue
41 }
42 var requestErr api.RequestError
43 switch err {
44 case errUnauthorizedLastSeen:
45 requestErr.Slug = api.RequestErrAccessDenied
46 requestErr.Field = fmt.Sprintf("devices/%d/lastSeen", pos)
47 case errUnauthorizedCreated:
48 requestErr.Slug = api.RequestErrAccessDenied
49 requestErr.Field = fmt.Sprintf("devices/%d/created", pos)
50 case errUnauthorizedOwner:
51 requestErr.Slug = api.RequestErrAccessDenied
52 requestErr.Field = fmt.Sprintf("devices/%d/owner", pos)
53 case errInvalidDeviceType:
54 requestErr.Slug = api.RequestErrInvalidValue
55 requestErr.Field = fmt.Sprintf("devices/%d/type", pos)
56 case errDeviceNameTooShort:
57 if len(device.Name) == 0 {
58 requestErr.Slug = api.RequestErrMissing
59 } else {
60 requestErr.Slug = api.RequestErrInsufficient
61 }
62 requestErr.Field = fmt.Sprintf("devices/%d/name", pos)
63 case errDeviceNameTooLong:
64 requestErr.Slug = api.RequestErrOverflow
65 requestErr.Field = fmt.Sprintf("devices/%d/name", pos)
66 }
67 if requestErr.Slug != "" {
68 api.Encode(w, r, http.StatusBadRequest, Response{Errors: []api.RequestError{requestErr}})
69 return
70 }
71 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
72 }
73 createdDevices, err := devices.CreateMany(devicesToCreate, ctx)
74 if err != nil {
75 // BUG(paddy): we should filter out non-internal errors here and expose better error responses
76 log.Printf("Error creating devices: %+v\n", err)
77 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
78 return
79 }
80 var resp Response
81 for _, device := range createdDevices {
82 resp.Devices = append(resp.Devices, apiDeviceFromCore(device, api.CheckScopes(passedScopes, ScopeViewPushToken.ID)))
83 }
84 api.Encode(w, r, http.StatusCreated, resp)
85 }
87 func handleGetDevices(ctx context.Context, w http.ResponseWriter, r *http.Request) {
88 userID, err := api.AuthUser(r)
89 if err != nil {
90 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: api.AccessDeniedError})
91 return
92 }
94 passedScopes := api.GetScopes(r)
95 if !api.CheckScopes(passedScopes, ScopeViewDevices.ID) {
96 api.Encode(w, r, http.StatusForbidden, Response{Errors: api.AccessDeniedError})
97 return
98 }
100 var retrievedDevices []devices.Device
101 requestedIDStrs := r.URL.Query()["id"]
102 requestedIDStrs = append(requestedIDStrs, trout.RequestVars(r)[http.CanonicalHeaderKey("id")]...)
104 if len(requestedIDStrs) < 1 {
105 retrievedDevices, err = devices.ListByOwner(userID, ctx)
106 if err != nil {
107 log.Printf("Error listing devices: %+v\n", err)
108 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
109 return
110 }
111 } else {
112 requestedIDs := make([]uuid.ID, 0, len(requestedIDStrs))
113 var reqErrs []api.RequestError
114 for pos, idStr := range requestedIDStrs {
115 id, err := uuid.Parse(idStr)
116 if err != nil {
117 reqErrs = append(reqErrs, api.RequestError{Slug: api.RequestErrInvalidFormat, Param: fmt.Sprintf("id[%d]", pos)})
118 continue
119 }
120 requestedIDs = append(requestedIDs, id)
121 }
122 if len(reqErrs) > 0 {
123 api.Encode(w, r, http.StatusBadRequest, Response{Errors: reqErrs})
124 return
125 }
126 getDevices, err := devices.GetMany(requestedIDs, ctx)
127 if err != nil {
128 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
129 return
130 }
131 for _, device := range getDevices {
132 if device.Owner.Equal(userID) {
133 retrievedDevices = append(retrievedDevices, device)
134 }
135 }
136 }
138 var resp Response
139 for _, device := range retrievedDevices {
140 resp.Devices = append(resp.Devices, apiDeviceFromCore(device, api.CheckScopes(passedScopes, ScopeViewPushToken.ID)))
141 }
142 api.Encode(w, r, http.StatusOK, resp)
143 }