forked from cyverse-de/user-info
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preferences.go
251 lines (210 loc) · 6.53 KB
/
preferences.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
// UserPreferencesRecord represents a user's preferences stored in the database
type UserPreferencesRecord struct {
ID string
Preferences string
UserID string
}
// convert makes sure that the JSON has the correct format. "wrap" tells convert
// whether to wrap the object in a map with "preferences" as the key.
func convertPrefs(record *UserPreferencesRecord, wrap bool) (map[string]interface{}, error) {
var values map[string]interface{}
if record.Preferences != "" {
if err := json.Unmarshal([]byte(record.Preferences), &values); err != nil {
return nil, err
}
}
// We don't want the return value wrapped in a preferences object, so unwrap it
// if it is wrapped.
if !wrap {
if _, ok := values["preferences"]; ok {
return values["preferences"].(map[string]interface{}), nil
}
return values, nil
}
// We do want the return value wrapped in a preferences object, so wrap it if it
// isn't already.
if _, ok := values["preferences"]; !ok {
newmap := make(map[string]interface{})
newmap["preferences"] = values
return newmap, nil
}
return values, nil
}
// UserPreferencesApp is an implementation of the App interface created to manage
// user preferences.
type UserPreferencesApp struct {
prefs pDB
router *mux.Router
}
// NewPrefsApp returns a new *UserPreferencesApp
func NewPrefsApp(db pDB, router *mux.Router) *UserPreferencesApp {
prefsApp := &UserPreferencesApp{
prefs: db,
router: router,
}
prefsApp.router.HandleFunc("/preferences/", prefsApp.Greeting).Methods("GET")
prefsApp.router.HandleFunc("/preferences/{username}", prefsApp.GetRequest).Methods("GET")
prefsApp.router.HandleFunc("/preferences/{username}", prefsApp.PutRequest).Methods("PUT")
prefsApp.router.HandleFunc("/preferences/{username}", prefsApp.PostRequest).Methods("POST")
prefsApp.router.HandleFunc("/preferences/{username}", prefsApp.DeleteRequest).Methods("DELETE")
return prefsApp
}
// Greeting prints out a greeting to the writer from user-prefs.
func (u *UserPreferencesApp) Greeting(writer http.ResponseWriter, r *http.Request) {
fmt.Fprintf(writer, "Hello from user-preferences.\n")
}
func (u *UserPreferencesApp) getUserPreferencesForRequest(username string, wrap bool) ([]byte, error) {
var retval UserPreferencesRecord
prefs, err := u.prefs.getPreferences(username)
if err != nil {
return nil, fmt.Errorf("Error getting preferences for username %s: %s", username, err)
}
if len(prefs) >= 1 {
retval = prefs[0]
}
response, err := convertPrefs(&retval, wrap)
if err != nil {
return nil, fmt.Errorf("Error generating response for username %s: %s", username, err)
}
var jsoned []byte
if len(response) > 0 {
jsoned, err = json.Marshal(response)
if err != nil {
return nil, fmt.Errorf("Error generating preferences JSON for user %s: %s", username, err)
}
} else {
jsoned = []byte("{}")
}
return jsoned, nil
}
// GetRequest handles writing out a user's preferences as a response.
func (u *UserPreferencesApp) GetRequest(writer http.ResponseWriter, r *http.Request) {
var (
username string
userExists bool
err error
ok bool
v = mux.Vars(r)
)
if username, ok = v["username"]; !ok {
badRequest(writer, "Missing username in URL")
return
}
log.WithFields(log.Fields{
"service": "preferences",
}).Info("Getting user preferences for ", username)
if userExists, err = u.prefs.isUser(username); err != nil {
badRequest(writer, fmt.Sprintf("Error checking for username %s: %s", username, err))
return
}
if !userExists {
handleNonUser(writer, username)
return
}
jsoned, err := u.getUserPreferencesForRequest(username, false)
if err != nil {
errored(writer, err.Error())
}
writer.Write(jsoned)
}
// PutRequest handles creating new user preferences.
func (u *UserPreferencesApp) PutRequest(writer http.ResponseWriter, r *http.Request) {
u.PostRequest(writer, r)
}
// PostRequest handles modifying an existing user's preferences.
func (u *UserPreferencesApp) PostRequest(writer http.ResponseWriter, r *http.Request) {
var (
username string
userExists bool
hasPrefs bool
err error
ok bool
v = mux.Vars(r)
)
if username, ok = v["username"]; !ok {
badRequest(writer, "Missing username in URL")
return
}
if userExists, err = u.prefs.isUser(username); err != nil {
badRequest(writer, fmt.Sprintf("Error checking for username %s: %s", username, err))
return
}
if !userExists {
handleNonUser(writer, username)
return
}
if hasPrefs, err = u.prefs.hasPreferences(username); err != nil {
errored(writer, fmt.Sprintf("Error checking preferences for user %s: %s", username, err))
return
}
var checked map[string]interface{}
bodyBuffer, err := ioutil.ReadAll(r.Body)
if err != nil {
errored(writer, fmt.Sprintf("Error reading body: %s", err))
return
}
if err = json.Unmarshal(bodyBuffer, &checked); err != nil {
errored(writer, fmt.Sprintf("Error parsing request body: %s", err))
return
}
bodyString := string(bodyBuffer)
if !hasPrefs {
if err = u.prefs.insertPreferences(username, bodyString); err != nil {
errored(writer, fmt.Sprintf("Error inserting preferences for user %s: %s", username, err))
return
}
} else {
if err = u.prefs.updatePreferences(username, bodyString); err != nil {
errored(writer, fmt.Sprintf("Error updating preferences for user %s: %s", username, err))
return
}
}
jsoned, err := u.getUserPreferencesForRequest(username, true)
if err != nil {
errored(writer, err.Error())
return
}
writer.Write(jsoned)
}
// DeleteRequest handles deleting a user's preferences.
func (u *UserPreferencesApp) DeleteRequest(writer http.ResponseWriter, r *http.Request) {
var (
username string
userExists bool
hasPrefs bool
err error
ok bool
v = mux.Vars(r)
)
if username, ok = v["username"]; !ok {
badRequest(writer, "Missing username in URL")
return
}
if userExists, err = u.prefs.isUser(username); err != nil {
badRequest(writer, fmt.Sprintf("Error checking for username %s: %s", username, err))
return
}
if !userExists {
handleNonUser(writer, username)
return
}
if hasPrefs, err = u.prefs.hasPreferences(username); err != nil {
errored(writer, fmt.Sprintf("Error checking preferences for user %s: %s", username, err))
return
}
if !hasPrefs {
return
}
if err = u.prefs.deletePreferences(username); err != nil {
errored(writer, fmt.Sprintf("Error deleting preferences for user %s: %s", username, err))
}
}