Web 服务

This commit is contained in:
奶爸
2019-12-08 16:59:58 +08:00
parent 5a21ce6ca6
commit d8c4364653
33 changed files with 1112 additions and 21 deletions

55
pkg/mygin/auth.go Normal file
View File

@@ -0,0 +1,55 @@
package mygin
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/p14yground/nezha/model"
"github.com/p14yground/nezha/service/dao"
)
// AuthorizeOption ..
type AuthorizeOption struct {
Guest bool
Member bool
IsPage bool
Msg string
Redirect string
Btn string
}
// Authorize ..
func Authorize(opt AuthorizeOption) func(*gin.Context) {
return func(c *gin.Context) {
token, err := c.Cookie(dao.Conf.Site.CookieName)
var code uint64 = http.StatusForbidden
if opt.Guest {
code = http.StatusBadRequest
}
commonErr := ErrInfo{
Title: "访问受限",
Code: code,
Msg: opt.Msg,
Link: opt.Redirect,
Btn: opt.Btn,
}
var isLogin bool
if err == nil {
isLogin = token == dao.Admin.Token && dao.Admin.Token != "" &&
dao.Admin.TokenExpired.After(time.Now())
}
c.Set(model.CtxKeyIsUserLogin, isLogin)
// 已登录且只能游客访问
if isLogin && opt.Guest {
ShowErrorPage(c, commonErr, opt.IsPage)
return
}
// 未登录且需要登录
if !isLogin && opt.Member {
ShowErrorPage(c, commonErr, opt.IsPage)
return
}
}
}

37
pkg/mygin/error.go Normal file
View File

@@ -0,0 +1,37 @@
package mygin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/p14yground/nezha/model"
)
// ErrInfo ..
type ErrInfo struct {
Code uint64
Title string
Msg string
Link string
Btn string
}
// ShowErrorPage ..
func ShowErrorPage(c *gin.Context, i ErrInfo, isPage bool) {
if isPage {
c.HTML(http.StatusOK, "page/error", CommonEnvironment(c, gin.H{
"Code": i.Code,
"Title": i.Title,
"Msg": i.Msg,
"Link": i.Link,
"Btn": i.Btn,
}))
} else {
c.JSON(http.StatusOK, model.Response{
Code: i.Code,
Message: i.Msg,
})
}
c.Abort()
}

36
pkg/mygin/mygin.go Normal file
View File

@@ -0,0 +1,36 @@
package mygin
import (
"fmt"
"strings"
"github.com/gin-gonic/gin"
"github.com/p14yground/nezha/model"
"github.com/p14yground/nezha/service/dao"
)
// CommonEnvironment ..
func CommonEnvironment(c *gin.Context, data map[string]interface{}) gin.H {
data["MatchedPath"] = c.MustGet("MatchedPath")
// 站点标题
if t, has := data["Title"]; !has {
data["Title"] = dao.Conf.Site.Brand
} else {
data["Title"] = fmt.Sprintf("%s - %s", t, dao.Conf.Site.Brand)
}
isLogin, ok := c.Get(model.CtxKeyIsUserLogin)
if ok && isLogin.(bool) {
data["Admin"] = dao.Admin
}
return data
}
// RecordPath ..
func RecordPath(c *gin.Context) {
url := c.Request.URL.String()
for _, p := range c.Params {
url = strings.Replace(url, p.Value, ":"+p.Key, 1)
}
c.Set("MatchedPath", url)
}