nezha/cmd/dashboard/controller/member_api.go

98 lines
2.1 KiB
Go
Raw Normal View History

2019-12-08 03:59:58 -05:00
package controller
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
2019-12-08 10:18:29 -05:00
"github.com/naiba/com"
2019-12-08 03:59:58 -05:00
"github.com/p14yground/nezha/model"
"github.com/p14yground/nezha/pkg/mygin"
"github.com/p14yground/nezha/service/dao"
)
type memberAPI struct {
r gin.IRouter
}
func (ma *memberAPI) serve() {
mr := ma.r.Group("")
mr.Use(mygin.Authorize(mygin.AuthorizeOption{
Member: true,
IsPage: false,
Msg: "访问此接口需要登录",
Btn: "点此登录",
Redirect: "/login",
}))
mr.POST("/logout", ma.logout)
2019-12-20 10:58:09 -05:00
mr.POST("/server", ma.addOrEditServer)
2019-12-08 10:18:29 -05:00
}
type serverForm struct {
2019-12-20 10:58:09 -05:00
ID uint64
2019-12-08 10:18:29 -05:00
Name string `binding:"required"`
}
2019-12-20 10:58:09 -05:00
func (ma *memberAPI) addOrEditServer(c *gin.Context) {
admin := c.MustGet(model.CtxKeyAuthorizedUser).(*model.User)
2019-12-08 10:18:29 -05:00
var sf serverForm
2019-12-09 03:02:49 -05:00
var s model.Server
2019-12-08 10:18:29 -05:00
err := c.ShouldBindJSON(&sf)
if err == nil {
2019-12-11 01:41:12 -05:00
dao.ServerLock.Lock()
defer dao.ServerLock.Unlock()
2019-12-08 10:18:29 -05:00
s.Name = sf.Name
2019-12-20 10:58:09 -05:00
}
if sf.ID == 0 {
s.Secret = com.MD5(fmt.Sprintf("%s%s%d", time.Now(), sf.Name, admin.ID))
2019-12-08 10:18:29 -05:00
s.Secret = s.Secret[:10]
err = dao.DB.Create(&s).Error
2019-12-20 10:58:09 -05:00
} else {
err = dao.DB.Save(&s).Error
2019-12-08 10:18:29 -05:00
}
if err != nil {
c.JSON(http.StatusOK, model.Response{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("请求错误:%s", err),
})
return
}
2019-12-09 05:14:31 -05:00
dao.ServerList[fmt.Sprintf("%d", s.ID)] = &s
2019-12-08 10:18:29 -05:00
c.JSON(http.StatusOK, model.Response{
Code: http.StatusOK,
})
2019-12-08 03:59:58 -05:00
}
type logoutForm struct {
ID uint64
}
func (ma *memberAPI) logout(c *gin.Context) {
2019-12-20 10:58:09 -05:00
admin := c.MustGet(model.CtxKeyAuthorizedUser).(*model.User)
2019-12-08 03:59:58 -05:00
var lf logoutForm
if err := c.ShouldBindJSON(&lf); err != nil {
c.JSON(http.StatusOK, model.Response{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("请求错误:%s", err),
})
return
}
2019-12-20 10:58:09 -05:00
if lf.ID != admin.ID {
2019-12-08 03:59:58 -05:00
c.JSON(http.StatusOK, model.Response{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("请求错误:%s", "用户ID不匹配"),
})
return
}
2019-12-20 10:58:09 -05:00
dao.DB.Model(admin).UpdateColumns(model.User{
Token: "",
TokenExpired: time.Now(),
})
2019-12-08 03:59:58 -05:00
c.JSON(http.StatusOK, model.Response{
Code: http.StatusOK,
})
}