lishwist/server/routing/users.go

83 lines
1.9 KiB
Go

package routing
import (
"encoding/json"
"lishwist/db"
"net/http"
)
func (ctx *Context) UsersJson(currentUser *db.User, w http.ResponseWriter, r *http.Request) {
if !currentUser.IsAdmin {
NotFoundJson(w, r)
return
}
users, err := db.GetAllUsers()
if err != nil {
writeGeneralErrorJson(w, http.StatusInternalServerError, "Failed to get users: "+err.Error())
return
}
_ = json.NewEncoder(w).Encode(users)
}
func (ctx *Context) User(currentUser *db.User, w http.ResponseWriter, r *http.Request) {
if !currentUser.IsAdmin {
NotFoundJson(w, r)
return
}
reference := r.PathValue("userReference")
user, err := db.GetUserByReference(reference)
if err != nil {
writeGeneralErrorJson(w, http.StatusInternalServerError, "Failed to get user: %s", err)
return
}
if user == nil {
writeGeneralErrorJson(w, http.StatusNotFound, "User not found")
return
}
_ = json.NewEncoder(w).Encode(user)
}
func (ctx *Context) UserPost(currentUser *db.User, w http.ResponseWriter, r *http.Request) {
if !currentUser.IsAdmin {
NotFoundJson(w, r)
return
}
if err := r.ParseForm(); err != nil {
writeGeneralErrorJson(w, http.StatusInternalServerError, "Failed to parse form: %s", err)
return
}
reference := r.PathValue("userReference")
if reference == currentUser.Reference {
writeGeneralErrorJson(w, http.StatusForbidden, "You cannot delete yourself.")
return
}
user, err := db.GetAnyUserByReference(reference)
if err != nil {
writeGeneralErrorJson(w, http.StatusInternalServerError, "Failed to get user: %s", err)
return
}
if user == nil {
writeGeneralErrorJson(w, http.StatusNotFound, "User not found")
return
}
intent := r.Form.Get("intent")
if intent != "" {
err = user.SetLive(intent != "delete")
if err != nil {
writeGeneralErrorJson(w, http.StatusInternalServerError, "Failed to delete user: "+err.Error())
return
}
}
_ = json.NewEncoder(w).Encode(user)
}