package svc import ( "applet/app/db" "applet/app/md" "applet/app/utils" "errors" "github.com/gin-gonic/gin" "strings" ) // 因为在mw_auth已经做完所有校验, 因此在此不再做任何校验 // GetUser is get user model func GetUser(c *gin.Context) *md.User { user, _ := c.Get("user") if user == nil { return nil } return user.(*md.User) } func GetUid(c *gin.Context) string { user, _ := c.Get("user") u := user.(*md.User) return utils.IntToStr(u.Info.Uid) } func CheckUser(c *gin.Context) (*md.User, error) { token := c.GetHeader("Authorization") if token == "" { return nil, errors.New("token not exist") } // 按空格分割 parts := strings.SplitN(token, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { return nil, errors.New("token format error") } // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它 mc, err := utils.ParseToken(parts[1]) if err != nil { return nil, err } // 获取user u, err := db.UserFindByID(db.DBs[c.GetString("mid")], mc.UID) if err != nil { return nil, err } if u == nil { return nil, errors.New("token can not find user") } // 获取user profile up, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], mc.UID) if err != nil { return nil, err } // 获取user 等级 ul, err := db.UserLevelByID(db.DBs[c.GetString("mid")], u.Level) if err != nil { return nil, err } user := &md.User{ Info: u, Profile: up, Level: ul, } return user, nil }