github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/auth/auth.go (about) 1 package auth 2 3 import ( 4 "fmt" 5 "github.com/OrigamiWang/msd/micro/util/jwt" 6 logutil "github.com/OrigamiWang/msd/micro/util/log" 7 "time" 8 ) 9 10 // Authorize 授权 11 func Authorize(uid int, uname string) string { 12 jwtPayload := &jwt.JwtPayload{ 13 Uid: uid, 14 Uname: uname, 15 Exp: time.Now().Add(time.Hour * 24 * 365), // one year to expire 16 } 17 j := jwt.EncodeJwt(jwtPayload) 18 return j 19 } 20 21 // Authenticate 鉴权 22 func Authenticate(j string) (uid int, uname string, err error) { 23 jwtPayload, err := jwt.DecodeJwt(j) 24 if err != nil { 25 logutil.Error("decode jwt failed, error: %v", err) 26 return -1, "", fmt.Errorf("decode jwt failed, error: %v", err) 27 } 28 // time has expired 29 if jwtPayload.Exp.Before(time.Now()) { 30 logutil.Warn("jwt token has expired") 31 return -1, "", fmt.Errorf("jwt token has expired") 32 } 33 return jwtPayload.Uid, jwtPayload.Uname, nil 34 }