users 權限
This commit is contained in:
@@ -50,6 +50,11 @@ func UsersPost(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("400 - " + err.Error()))
|
||||
return
|
||||
}
|
||||
// 如果是第一個用戶, 設置為管理員
|
||||
if user.ID == 1 {
|
||||
user.Admin = true
|
||||
configs.ORMDB().Save(&user)
|
||||
}
|
||||
// 返回信息
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write(utils.ToJSON(user))
|
||||
@@ -69,9 +74,22 @@ func UsersItemGet(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 更新用戶
|
||||
func UsersItemPatch(w http.ResponseWriter, r *http.Request) {
|
||||
form := utils.BodyRead(r)
|
||||
user := models.User{ID: utils.ParamInt(mux.Vars(r)["id"], 0)}
|
||||
models.AccountRead(w, r, func(account *models.Account) {
|
||||
var form map[string]interface{} = utils.BodyRead(r)
|
||||
var user models.User = models.User{ID: utils.ParamInt(mux.Vars(r)["id"], 0)}
|
||||
configs.ORMDB().First(&user)
|
||||
|
||||
// 只有自己的賬戶或是管理員才能更新用戶信息
|
||||
if account.ID != user.ID && !account.Admin {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte("403 - Forbidden"))
|
||||
return
|
||||
}
|
||||
// 用戶不能修改管理員權限, 管理員不能修改自己的管理員權限
|
||||
if account.ID == user.ID || !account.Admin {
|
||||
delete(form, "admin")
|
||||
}
|
||||
|
||||
if name, ok := form["name"].(string); ok {
|
||||
user.Name = name
|
||||
}
|
||||
@@ -89,12 +107,37 @@ func UsersItemPatch(w http.ResponseWriter, r *http.Request) {
|
||||
configs.ORMDB().Save(&user)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write(utils.ToJSON(user))
|
||||
})
|
||||
}
|
||||
|
||||
// 刪除用戶
|
||||
func UsersItemDelete(w http.ResponseWriter, r *http.Request) {
|
||||
user := models.User{ID: utils.ParamInt(mux.Vars(r)["id"], 0)}
|
||||
models.AccountRead(w, r, func(account *models.Account) {
|
||||
var user models.User = models.User{ID: utils.ParamInt(mux.Vars(r)["id"], 0)}
|
||||
|
||||
// 獲取目標用戶
|
||||
if err := configs.ORMDB().First(&user).Error; err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte("404 - " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 只有自己的賬戶或是管理員才能刪除用戶
|
||||
if account.ID != user.ID && !account.Admin {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte("403 - 只有自己的賬戶或是管理員才能刪除用戶"))
|
||||
return
|
||||
}
|
||||
|
||||
// 管理員不能刪除自己
|
||||
if account.ID == user.ID && account.Admin {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte("403 - 管理員不能刪除自己"))
|
||||
return
|
||||
}
|
||||
|
||||
configs.ORMDB().Delete(&user)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write(utils.ToJSON(user))
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user