123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- package middleware
- import (
- "eta_mini_ht_api/common/component/cache"
- logger "eta_mini_ht_api/common/component/log"
- "eta_mini_ht_api/common/exception"
- "eta_mini_ht_api/common/utils/jwt"
- "eta_mini_ht_api/common/utils/redis"
- stringUtils "eta_mini_ht_api/common/utils/string"
- "eta_mini_ht_api/controllers"
- "eta_mini_ht_api/service/user"
- "github.com/beego/beego/v2/server/web"
- "github.com/beego/beego/v2/server/web/context"
- "strings"
- )
- var (
- rdCache *cache.RedisCache
- )
- const (
- ILLEGALUSER = "用户信息异常"
- UNAUTHORIZED = "请重新登录"
- FORBIDDEN = "禁止访问"
- NOTFOUND = "未找到"
- authorization = "Authorization"
- baseUrl = "/htapi"
- Bearer = "Bearer"
- )
- func rd() *cache.RedisCache {
- if rdCache == nil {
- rdCache = cache.GetInstance()
- }
- return rdCache
- }
- var publicRoutes = []string{
- "/auth/*",
- }
- func AuthMiddleware() web.FilterFunc {
- return func(ctx *context.Context) {
- path := ctx.Input.URL()
- logger.Info("请求路径:%v", path)
- if !allowed(path) {
- rep := unAuthorized()
- auth := ctx.Input.Header(authorization)
- if auth == "" {
- logger.Error("token信息不存在")
- _ = ctx.JSONResp(rep)
- return
- }
- parts := strings.Split(auth, " ")
- if len(parts) != 2 || parts[0] != Bearer {
- logger.Error("token参数不符合格式")
- _ = ctx.JSONResp(rep)
- return
- }
- info, err := jwt.CheckToken(parts[1])
- if err != nil {
- logger.Error("token无效:%v", err)
- _ = ctx.JSONResp(rep)
- return
- }
- //校验redis中是否合法
- redisToken := rd().GetString(redis.GenerateTokenKey(info.Mobile))
- if redisToken != parts[1] {
- logger.Error("token无效:用户token已刷新")
- _ = ctx.JSONResp(unAuthorized())
- return
- }
- //组装用户信息
- var userInfo user.User
- userInfo, err = user.GetUserByMobile(info.Mobile)
- if err != nil {
- logger.Error("获取用户信息失败:%v", err)
- _ = ctx.JSONResp(illegalUser())
- return
- }
- ctx.Input.SetData("user", userInfo)
- return
- }
- return
- }
- }
- func unAuthorized() controllers.BaseResponse {
- return controllers.BaseResponse{
- Ret: 401,
- Msg: UNAUTHORIZED,
- ErrMsg: exception.GetMsg(exception.Unauthorized),
- }
- }
- func illegalUser() controllers.BaseResponse {
- return controllers.BaseResponse{
- Ret: 401,
- Msg: ILLEGALUSER,
- ErrMsg: exception.GetMsg(exception.Unauthorized),
- }
- }
- func allowed(path string) bool {
- for _, p := range publicRoutes {
- if stringUtils.IsBlank(p) {
- continue
- }
- src := baseUrl + p
- if strings.HasSuffix(p, "*") {
- target := src[:len(src)-1]
- if strings.HasPrefix(path, target) {
- return true
- }
- } else {
- if src == path {
- return true
- }
- }
- }
- return false
- }
|