MCPcopy Create free account
hub / github.com/GoMudEngine/GoMud / apiV1PatchUser

Function apiV1PatchUser

internal/web/api_v1_users.go:56–117  ·  view source on GitHub ↗

PATCH /admin/api/v1/users/{userid}

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

54
55// PATCH /admin/api/v1/users/{userid}
56func apiV1PatchUser(w http.ResponseWriter, r *http.Request) {
57 userId := resolveUserId(w, r.PathValue("userid"))
58 if userId == 0 {
59 return
60 }
61
62 u := loadUserRecord(w, userId)
63 if u == nil {
64 return
65 }
66
67 // Capture the plaintext password from the request before decoding into the
68 // UserRecord, because UserRecord.Password stores a bcrypt hash and we need
69 // to call SetPassword to hash a new plaintext value.
70 var raw struct {
71 Password string `json:"Password"`
72 }
73 body, err := io.ReadAll(r.Body)
74 if err != nil {
75 writeAPIError(w, http.StatusBadRequest, "failed to read request body: "+err.Error())
76 return
77 }
78 _ = json.Unmarshal(body, &raw)
79
80 updated := *u
81 if err := json.Unmarshal(body, &updated); err != nil {
82 writeAPIError(w, http.StatusBadRequest, "malformed request body: "+err.Error())
83 return
84 }
85
86 // Preserve the canonical ID; callers cannot change it via PATCH.
87 updated.UserId = userId
88
89 // If a plaintext password was supplied, hash it properly.
90 if raw.Password != "" && !isBcryptHash(raw.Password) {
91 if err := updated.SetPassword(raw.Password); err != nil {
92 writeAPIError(w, http.StatusBadRequest, "invalid password: "+err.Error())
93 return
94 }
95 }
96
97 if updated.Character.Gold < 0 {
98 updated.Character.Gold = 0
99 }
100 if updated.Character.Bank < 0 {
101 updated.Character.Bank = 0
102 }
103
104 updated.Character.Validate()
105
106 if err := users.SaveUser(updated); err != nil {
107 writeAPIError(w, http.StatusInternalServerError, err.Error())
108 return
109 }
110
111 users.UpdateOnlineUser(updated)
112
113 writeJSON(w, http.StatusOK, APIResponse[*users.UserRecord]{

Callers

nothing calls this directly

Calls 9

SaveUserFunction · 0.92
UpdateOnlineUserFunction · 0.92
resolveUserIdFunction · 0.85
loadUserRecordFunction · 0.85
writeAPIErrorFunction · 0.85
isBcryptHashFunction · 0.85
writeJSONFunction · 0.85
SetPasswordMethod · 0.80
ValidateMethod · 0.65

Tested by

no test coverage detected