-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
api_devices_list.go
73 lines (61 loc) · 1.95 KB
/
api_devices_list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package constellation
import (
"net/http"
"encoding/json"
"github.com/azukaar/cosmos-server/src/utils"
)
func DeviceList(w http.ResponseWriter, req *http.Request) {
// Check for GET method
if req.Method != "GET" {
utils.HTTPError(w, "Method not allowed", http.StatusMethodNotAllowed, "HTTP002")
return
}
if utils.LoggedInOnly(w, req) != nil {
return
}
isAdmin := utils.IsAdmin(req)
// Connect to the collection
c, errCo := utils.GetCollection(utils.GetRootAppId(), "devices")
if errCo != nil {
utils.Error("Database Connect", errCo)
utils.HTTPError(w, "Database", http.StatusInternalServerError, "DB001")
return
}
var devices []utils.ConstellationDevice
// Check if user is an admin
if isAdmin {
// If admin, get all devices
cursor, err := c.Find(nil, map[string]interface{}{})
if err != nil {
utils.Error("DeviceList: Error fetching devices", err)
utils.HTTPError(w, "Error fetching devices", http.StatusInternalServerError, "DL001")
return
}
defer cursor.Close(nil)
if err = cursor.All(nil, &devices); err != nil {
utils.Error("DeviceList: Error decoding devices", err)
utils.HTTPError(w, "Error decoding devices", http.StatusInternalServerError, "DL002")
return
}
} else {
// If not admin, get user's devices based on their nickname
nickname := req.Header.Get("x-cosmos-user")
cursor, err := c.Find(nil, map[string]interface{}{"Nickname": nickname})
if err != nil {
utils.Error("DeviceList: Error fetching devices", err)
utils.HTTPError(w, "Error fetching devices", http.StatusInternalServerError, "DL003")
return
}
defer cursor.Close(nil)
if err = cursor.All(nil, &devices); err != nil {
utils.Error("DeviceList: Error decoding devices", err)
utils.HTTPError(w, "Error decoding devices", http.StatusInternalServerError, "DL004")
return
}
}
// Respond with the list of devices
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "OK",
"data": devices,
})
}