|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package svc
-
- import (
- "applet/app/customer/lib/auth"
- "applet/app/db"
- "applet/app/db/model"
- "errors"
- "github.com/gin-gonic/gin"
- "strings"
- "time"
- )
-
- func GetUser(c *gin.Context) *model.User {
- user, _ := c.Get("user")
- if user == nil {
- return &model.User{
- Id: 0,
- UserId: "",
- Nickname: "",
- Avatar: "",
- Phone: "",
- Memo: "",
- CreateAt: time.Now().Format("2006-01-02 15:04:05"),
- UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
- }
- }
- return user.(*model.User)
- }
-
- func CheckUser(c *gin.Context) (*model.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 := auth.ParseToken(parts[1])
- if err != nil {
- return nil, err
- }
-
- // 获取user
- userDb := db.UserDb{}
- userDb.Set()
- user, err := userDb.GetUser(mc.UserId)
- if err != nil {
- return nil, err
- }
- return user, nil
- }
|