picgo/handler/user.go
2024-08-09 20:30:35 +08:00

223 lines
7.0 KiB
Go

package handler
import (
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/csrf"
"math"
"net/http"
"picgo/corelib"
"picgo/data"
"picgo/model"
"strconv"
)
func UserPageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
var (
err error
user model.SysUser
res model.UserpageResponse
)
username := r.Context().Value("username").(string)
if user, err = data.SysUserGetCacheByUsername(username); err != nil {
http.Error(w, "IndexHandler SysUserGetCacheByUsername Error", http.StatusInternalServerError)
return
}
tmpData := map[string]interface{}{
csrf.TemplateTag: csrf.TemplateField(r),
}
tmpData["Title"] = "用户管理"
tmpData["Active"] = r.URL.Path
tmpData["IsSuper"] = user.IsSuper
if res, err = pagination(1, 10, ""); err != nil {
http.Error(w, fmt.Sprintf("%v", err), http.StatusInternalServerError)
return
}
tmpData["Data"] = res
w.Header().Add("X-CSRF-Token", csrf.Token(r))
corelib.TemplateHandler(w, tmpData, "layout.html", "view/layout.html", "view/user.html")
} else {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
}
func UserCreateApiHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
var (
err error
res model.UserCreateRequest
user model.SysUser
password string
salt string
)
if err = json.NewDecoder(r.Body).Decode(&res); err != nil {
corelib.Logger.Error("UserCreateApiHandler, 参数获取失败")
corelib.WriteJsonResponse(w, 400, "参数错误", nil)
return
}
if (res.Username == "") || (res.Password == "") {
corelib.Logger.Error("UserCreateApiHandler, 用户名或者密码为空")
corelib.WriteJsonResponse(w, 400, "请输入用户名密码", nil)
return
}
if isExists := data.SysUserExists(res.Username); isExists {
corelib.Logger.Error("UserCreateApiHandler, 用户: " + res.Username + "已经存在")
corelib.WriteJsonResponse(w, 10050, "用户已经存在", nil)
return
}
salt = corelib.GenerateSalt()
if password, err = corelib.HashPassword(res.Password, salt); err != nil {
corelib.Logger.Error("UserCreateApiHandler, 生成密码失败")
corelib.WriteJsonResponse(w, 10051, "生成密码失败", nil)
return
}
user.Username = res.Username
user.Password = password
user.Salt = salt
user.IsSuper = 0
if err = data.SysUserCreate(user); err != nil {
corelib.Logger.Error("UserCreateApiHandler, 数据保存用户数据失败")
corelib.WriteJsonResponse(w, 10052, "新建用户失败", nil)
return
}
w.Header().Set("Content-Type", "application/json")
corelib.WriteJsonResponse(w, 200, "用户创建成功", nil)
} else {
//http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
corelib.WriteJsonResponse(w, 405, "方法错误", nil)
return
}
}
// UserPageApiHandler 分页查询
func UserPageApiHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
var (
err error
page int
pageSize int
total int64
user []model.SysUser
)
query := r.URL.Query()
// 搜索条件
search := query.Get("search")
// 每页显示多少跳
if pageSize, err = strconv.Atoi(query.Get("pageSize")); err != nil {
corelib.Logger.Error("UserPageApiHandler, 获取count参数失败")
corelib.WriteJsonResponse(w, 400, "参数错误", nil)
return
}
// 第几页
if page, err = strconv.Atoi(query.Get("page")); err != nil {
corelib.Logger.Error("UserPageApiHandler, 获取page参数失败")
corelib.WriteJsonResponse(w, 400, "参数错误", nil)
return
}
if page < 1 {
page = 1
}
offset := (page - 1) * pageSize
if search != "" {
if err = corelib.DbMysql.Where("name like ?", "%"+search+"%").Find(&model.SysUser{}).Count(&total).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, search, 查询total失败")
corelib.WriteJsonResponse(w, 500, "数据查询失败", nil)
}
if err = corelib.DbMysql.Limit(pageSize).Offset(offset).Where("name like ?", "%"+search+"%").Find(&user).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, search, 查询分页数据失败")
corelib.WriteJsonResponse(w, 500, "数据查询失败", nil)
}
}
if err = corelib.DbMysql.Find(&model.SysUser{}).Count(&total).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, all, 查询total失败")
corelib.WriteJsonResponse(w, 500, "参数错误", nil)
}
if err = corelib.DbMysql.Limit(pageSize).Offset(offset).Find(&user).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, all, 查询分页数据失败")
corelib.WriteJsonResponse(w, 500, "参数错误", nil)
}
numPage := math.Ceil(float64(total) / float64(pageSize))
if page > int(numPage) {
page = int(numPage)
}
paginationData := corelib.GetPaginationData(int(numPage), page, 2, total)
res := model.UserpageResponse{}
res.PaginationData = paginationData
if total > 0 {
for _, v := range user {
res.Data = append(res.Data, model.UserResponse{
ID: v.ID,
Username: v.Username,
IsSuper: v.IsSuper,
Remark: v.Remark,
CreatedAt: v.CreatedAt,
UpdatedAt: v.UpdatedAt,
})
}
}
corelib.WriteJsonResponse(w, http.StatusOK, "", res)
} else {
corelib.WriteJsonResponse(w, 405, "方法错误", nil)
return
}
}
func pagination(page, pageSize int, search string) (model.UserpageResponse, error) {
var (
err error
user []model.SysUser
total int64
)
if page < 1 {
page = 1
}
offset := (page - 1) * pageSize
if search != "" {
if err = corelib.DbMysql.Where("name like ?", "%"+search+"%").Find(&model.SysUser{}).Count(&total).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, search, 查询total失败", err)
return model.UserpageResponse{}, errors.New("数据查询失败")
}
if err = corelib.DbMysql.Limit(pageSize).Offset(offset).Where("name like ?", "%"+search+"%").Find(&user).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, search, 查询分页数据失败", err)
return model.UserpageResponse{}, errors.New("数据查询失败")
}
} else {
if err = corelib.DbMysql.Find(&model.SysUser{}).Count(&total).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, all, 查询total失败", err)
return model.UserpageResponse{}, errors.New("数据查询失败")
}
if err = corelib.DbMysql.Limit(pageSize).Offset(offset).Find(&user).Error; err != nil {
corelib.Logger.Error("UserPageApiHandler, all, 查询分页数据失败", err)
return model.UserpageResponse{}, errors.New("数据查询失败")
}
}
numPage := math.Ceil(float64(total) / float64(pageSize))
if page > int(numPage) {
page = int(numPage)
}
paginationData := corelib.GetPaginationData(int(numPage), page, 2, total)
res := model.UserpageResponse{}
res.PaginationData = paginationData
if total > 0 {
for _, v := range user {
res.Data = append(res.Data, model.UserResponse{
ID: v.ID,
Username: v.Username,
IsSuper: v.IsSuper,
Remark: v.Remark,
CreatedAt: v.CreatedAt,
UpdatedAt: v.UpdatedAt,
})
}
}
return res, nil
}