2019-12-08 03:59:58 -05:00
|
|
|
package mygin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2019-12-20 10:58:09 -05:00
|
|
|
"strings"
|
2019-12-08 03:59:58 -05:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
2020-11-10 21:07:45 -05:00
|
|
|
"github.com/naiba/nezha/model"
|
|
|
|
"github.com/naiba/nezha/service/dao"
|
2019-12-08 03:59:58 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type AuthorizeOption struct {
|
|
|
|
Guest bool
|
|
|
|
Member bool
|
|
|
|
IsPage bool
|
|
|
|
Msg string
|
|
|
|
Redirect string
|
|
|
|
Btn string
|
|
|
|
}
|
|
|
|
|
|
|
|
func Authorize(opt AuthorizeOption) func(*gin.Context) {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
token, err := c.Cookie(dao.Conf.Site.CookieName)
|
2019-12-20 10:58:09 -05:00
|
|
|
token = strings.TrimSpace(token)
|
2019-12-08 03:59:58 -05:00
|
|
|
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,
|
2019-12-20 10:58:09 -05:00
|
|
|
}
|
|
|
|
if token != "" {
|
|
|
|
|
2019-12-08 03:59:58 -05:00
|
|
|
}
|
|
|
|
var isLogin bool
|
2019-12-20 10:58:09 -05:00
|
|
|
var u model.User
|
|
|
|
err = dao.DB.Where("token = ?", token).First(&u).Error
|
2019-12-08 03:59:58 -05:00
|
|
|
if err == nil {
|
2019-12-20 10:58:09 -05:00
|
|
|
isLogin = u.TokenExpired.After(time.Now())
|
|
|
|
}
|
|
|
|
if isLogin {
|
|
|
|
c.Set(model.CtxKeyAuthorizedUser, &u)
|
2019-12-08 03:59:58 -05:00
|
|
|
}
|
|
|
|
// 已登录且只能游客访问
|
|
|
|
if isLogin && opt.Guest {
|
|
|
|
ShowErrorPage(c, commonErr, opt.IsPage)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// 未登录且需要登录
|
|
|
|
if !isLogin && opt.Member {
|
|
|
|
ShowErrorPage(c, commonErr, opt.IsPage)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|