diff options
author | hmhealey <harrisonmhealey@gmail.com> | 2015-10-01 15:22:04 -0400 |
---|---|---|
committer | hmhealey <harrisonmhealey@gmail.com> | 2015-10-13 09:42:23 -0400 |
commit | a087403e9f25373d5bdea5e10fafb0c5d496a703 (patch) | |
tree | 0bf290c50fea2398da8beee262ff5ed6ec3c38bc /api/preference.go | |
parent | da66599fa39ddbff96b0844fabac161e130a2bc4 (diff) | |
download | chat-a087403e9f25373d5bdea5e10fafb0c5d496a703.tar.gz chat-a087403e9f25373d5bdea5e10fafb0c5d496a703.tar.bz2 chat-a087403e9f25373d5bdea5e10fafb0c5d496a703.zip |
Added api to get and set preferences
Diffstat (limited to 'api/preference.go')
-rw-r--r-- | api/preference.go | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/api/preference.go b/api/preference.go new file mode 100644 index 000000000..9fadfd2e4 --- /dev/null +++ b/api/preference.go @@ -0,0 +1,63 @@ +// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved. +// See License.txt for license information. + +package api + +import ( + l4g "code.google.com/p/log4go" + "encoding/json" + "github.com/gorilla/mux" + "github.com/mattermost/platform/model" + "net/http" +) + +func InitPreference(r *mux.Router) { + l4g.Debug("Initializing preference api routes") + + sr := r.PathPrefix("/preferences").Subrouter() + sr.Handle("/set", ApiAppHandler(setPreferences)).Methods("POST") + sr.Handle("/{category:[A-Za-z0-9_]+}/{name:[A-Za-z0-9_]+}", ApiAppHandler(getPreferencesByName)).Methods("GET") +} + +func setPreferences(c *Context, w http.ResponseWriter, r *http.Request) { + var preferences []model.Preference + + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&preferences); err != nil { + c.Err = model.NewAppError("setPreferences", "Unable to decode preferences from request", err.Error()) + c.Err.StatusCode = http.StatusBadRequest + return + } + + // just attempt to save/update them one by one and abort if one fails + // in the future, this could probably be done in a transaction, but that's unnecessary now + for _, preference := range preferences { + if c.Session.UserId != preference.UserId { + c.Err = model.NewAppError("setPreferences", "Unable to set preferences for other user", "session.user_id="+c.Session.UserId+", preference.user_id="+preference.UserId) + c.Err.StatusCode = http.StatusUnauthorized + return + } + + if result := <-Srv.Store.Preference().Save(&preference); result.Err != nil { + if result = <-Srv.Store.Preference().Update(&preference); result.Err != nil { + c.Err = result.Err + return + } + } + } + + w.Write([]byte("true")) +} + +func getPreferencesByName(c *Context, w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + category := params["category"] + name := params["name"] + + if result := <-Srv.Store.Preference().GetByName(c.Session.UserId, category, name); result.Err != nil { + c.Err = result.Err + return + } else { + w.Write([]byte(model.PreferenceListToJson(result.Data.([]*model.Preference)))) + } +} |