44 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			44 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package token
 | |
| 
 | |
| import (
 | |
| 	"errors"
 | |
| 	"time"
 | |
| 
 | |
| 	tk "github.com/golang-jwt/jwt/v5"
 | |
| )
 | |
| 
 | |
| // Different types of error returned by the VerifyToken function
 | |
| var (
 | |
| 	ErrInvalidToken = errors.New("token is invalid")
 | |
| 	ErrExpiredToken = errors.New("token has expired")
 | |
| )
 | |
| 
 | |
| // Payload contains the payload data of the token
 | |
| type Payload struct {
 | |
| 	ID                  string `json:"id"`
 | |
| 	Username            string `json:"username"`
 | |
| 	tk.RegisteredClaims        // v5版本新加的方法
 | |
| }
 | |
| 
 | |
| // NewPayload creates a new token payload with a specific username and duration
 | |
| func NewPayload(id string, username string, duration time.Duration) (*Payload, error) {
 | |
| 	payload := &Payload{
 | |
| 		id,
 | |
| 		username,
 | |
| 		tk.RegisteredClaims{
 | |
| 			ExpiresAt: tk.NewNumericDate(time.Now().Add(duration)), // 过期时间24小时
 | |
| 			IssuedAt:  tk.NewNumericDate(time.Now()),               // 签发时间
 | |
| 			NotBefore: tk.NewNumericDate(time.Now()),               // 生效时间
 | |
| 		},
 | |
| 	}
 | |
| 	return payload, nil
 | |
| }
 | |
| 
 | |
| // Valid checks if the token payload is valid or not
 | |
| func (payload *Payload) Valid() error {
 | |
| 	if time.Now().After(payload.ExpiresAt.Time) {
 | |
| 		return ErrExpiredToken
 | |
| 	}
 | |
| 	return nil
 | |
| }
 |