前台查看密码 close #24 close #41

This commit is contained in:
naiba
2021-01-31 13:37:43 +08:00
parent 061a9992ff
commit c3dcc721dc
13 changed files with 159 additions and 15 deletions

View File

@@ -1,12 +1,15 @@
package controller
import (
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"golang.org/x/crypto/bcrypt"
"github.com/naiba/nezha/model"
"github.com/naiba/nezha/pkg/mygin"
@@ -20,11 +23,63 @@ type commonPage struct {
func (cp *commonPage) serve() {
cr := cp.r.Group("")
cr.Use(mygin.Authorize(mygin.AuthorizeOption{}))
cr.POST("/view-password", cp.issueViewPassword)
cr.Use(cp.checkViewPassword) // 前端查看密码鉴权
cr.GET("/", cp.home)
cr.GET("/service", cp.service)
cr.GET("/ws", cp.ws)
}
type viewPasswordForm struct {
Password string
}
func (p *commonPage) issueViewPassword(c *gin.Context) {
var vpf viewPasswordForm
err := c.ShouldBind(&vpf)
var hash []byte
if err == nil && vpf.Password != dao.Conf.Site.ViewPassword {
err = errors.New("查看密码错误")
}
if err == nil {
hash, err = bcrypt.GenerateFromPassword([]byte(vpf.Password), bcrypt.DefaultCost)
}
if err != nil {
mygin.ShowErrorPage(c, mygin.ErrInfo{
Title: "出现错误",
Msg: fmt.Sprintf("请求错误:%s", err),
}, true)
c.Abort()
return
}
c.SetCookie(dao.Conf.Site.CookieName+"-vp", string(hash), 60*60*24, "", "", false, false)
c.Redirect(http.StatusFound, c.Request.Referer())
}
func (p *commonPage) checkViewPassword(c *gin.Context) {
if dao.Conf.Site.ViewPassword == "" {
c.Next()
return
}
if _, authorized := c.Get(model.CtxKeyAuthorizedUser); authorized {
c.Next()
return
}
// 验证查看密码
viewPassword, _ := c.Cookie(dao.Conf.Site.CookieName + "-vp")
if err := bcrypt.CompareHashAndPassword([]byte(viewPassword), []byte(dao.Conf.Site.ViewPassword)); err != nil {
c.HTML(http.StatusOK, "theme-"+dao.Conf.Site.Theme+"/viewpassword", mygin.CommonEnvironment(c, gin.H{
"Title": "验证查看密码",
"CustomCode": dao.Conf.Site.CustomCode,
}))
c.Abort()
return
}
c.Next()
}
type ServiceItem struct {
Monitor model.Monitor
TotalUp uint64

View File

@@ -445,6 +445,7 @@ type settingForm struct {
Admin string
Theme string
CustomCode string
ViewPassword string
EnableIPChangeNotification string
}
@@ -461,6 +462,7 @@ func (ma *memberAPI) updateSetting(c *gin.Context) {
dao.Conf.Site.Brand = sf.Title
dao.Conf.Site.Theme = sf.Theme
dao.Conf.Site.CustomCode = sf.CustomCode
dao.Conf.Site.ViewPassword = sf.ViewPassword
dao.Conf.GitHub.Admin = sf.Admin
if err := dao.Conf.Save(); err != nil {
c.JSON(http.StatusOK, model.Response{

View File

@@ -40,6 +40,9 @@ func init() {
if dao.Conf.Debug {
dao.DB = dao.DB.Debug()
}
if dao.Conf.GRPCPort == 0 {
dao.Conf.GRPCPort = 5555
}
dao.Cache = cache.New(5*time.Minute, 10*time.Minute)
initSystem()
@@ -105,7 +108,7 @@ func loadCrons() {
func main() {
go controller.ServeWeb(dao.Conf.HTTPPort)
go rpc.ServeRPC(5555)
go rpc.ServeRPC(dao.Conf.GRPCPort)
go rpc.DispatchTask(time.Minute * 3)
dao.AlertSentinelStart()
}