广告平台(总站长使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 1.4 KiB

4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package auth
  2. import (
  3. "errors"
  4. "github.com/dgrijalva/jwt-go"
  5. "time"
  6. )
  7. // GenToken 生成JWT
  8. func GenToken(admId int, username string) (string, error) {
  9. // 创建一个我们自己的声明
  10. c := JWTUser{
  11. AdmId: admId,
  12. Username: username,
  13. StandardClaims: jwt.StandardClaims{
  14. ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间
  15. Issuer: "super_advertisement", // 签发人
  16. },
  17. }
  18. // 使用指定的签名方法创建签名对象
  19. token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
  20. // 使用指定的secret签名并获得完整的编码后的字符串token
  21. return token.SignedString(Secret)
  22. }
  23. // ParseToken 解析JWT
  24. func ParseToken(tokenString string) (*JWTUser, string, error) {
  25. // 解析token
  26. token, err := jwt.ParseWithClaims(tokenString, &JWTUser{}, func(token *jwt.Token) (i interface{}, err error) {
  27. return Secret, nil
  28. })
  29. if err != nil {
  30. return nil, "", err
  31. }
  32. if claims, ok := token.Claims.(*JWTUser); ok && token.Valid { // 校验token正确性
  33. if claims.StandardClaims.ExpiresAt < time.Now().Unix() { // 校验token时效性
  34. return nil, "", errors.New("token is expired")
  35. }
  36. if !claims.VerifyExpiresAt(time.Now().Add(time.Minute*30).Unix(), false) { // TODO::判断Token快过期,就创建新的token(30分钟)
  37. newToken, _ := GenToken(claims.AdmId, claims.Username)
  38. return claims, newToken, nil
  39. }
  40. return claims, "", err
  41. }
  42. return nil, "", errors.New("invalid token")
  43. }