-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
edit.go
79 lines (65 loc) · 1.89 KB
/
edit.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
package user
import (
"net/http"
"encoding/json"
"github.com/gorilla/mux"
"github.com/azukaar/cosmos-server/src/utils"
)
type EditRequestJSON struct {
Email string `validate:"email"`
}
func UserEdit(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
nickname := vars["nickname"]
if utils.AdminOrItselfOnly(w, req, nickname) != nil {
return
}
if(req.Method == "PATCH") {
var request EditRequestJSON
err1 := json.NewDecoder(req.Body).Decode(&request)
if err1 != nil {
utils.Error("UserEdit: Invalid User Request", err1)
utils.HTTPError(w, "User Edit Error", http.StatusInternalServerError, "UL001")
return
}
// Validate request
err2 := utils.Validate.Struct(request)
if err2 != nil {
utils.Error("UserEdit: Invalid User Request", err2)
utils.HTTPError(w, "User request invalid: " + err2.Error(), http.StatusInternalServerError, "UL002")
return
}
c, closeDb, errCo := utils.GetEmbeddedCollection(utils.GetRootAppId(), "users")
defer closeDb()
if errCo != nil {
utils.Error("Database Connect", errCo)
utils.HTTPError(w, "Database", http.StatusInternalServerError, "DB001")
return
}
utils.Debug("UserEdit: Edit user " + nickname)
toSet := map[string]interface{}{}
if request.Email != "" {
if utils.AdminOnly(w, req) != nil {
return
}
toSet["Email"] = request.Email
}
_, err := c.UpdateOne(nil, map[string]interface{}{
"Nickname": nickname,
}, map[string]interface{}{
"$set": toSet,
})
if err != nil {
utils.Error("UserEdit: Error while getting user", err)
utils.HTTPError(w, "User Edit Error", http.StatusInternalServerError, "UE001")
return
}
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "OK",
})
} else {
utils.Error("UserEdit: Method not allowed" + req.Method, nil)
utils.HTTPError(w, "Method not allowed", http.StatusMethodNotAllowed, "HTTP001")
return
}
}