ducky/devices

Paddy 2016-01-02 Parent:b2fdf827758e Child:ed1b5ba69551

19:51ad0db105c8 Go to Latest

ducky/devices/apiv1/handlers.go

Update trout to fix routing bug. Update to tip on trout to fix the routing bug that was causing us such issues. See the commit message of trout at 3df515f0cec5 for more details.

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 }