github.com/lovung/GoCleanArchitecture@v0.0.0-20210302152432-50d91fd29f9f/pkg/jwtutil/claim.go (about) 1 package jwtutil 2 3 import ( 4 "context" 5 "errors" 6 "time" 7 8 "github.com/dgrijalva/jwt-go" 9 ) 10 11 // const key for middleware 12 const ( 13 JWTClaimsKey = "jwtClaims" 14 ) 15 16 // AuthClaims the claim for authentication 17 type AuthClaims struct { 18 jwt.StandardClaims 19 UserID uint64 `json:"user_id,omitempty"` 20 IssueTime time.Time `json:"-"` 21 } 22 23 // JWTClaims is the information inside Claims 24 type JWTClaims struct { 25 UserID uint64 26 } 27 28 // ExtractClaims extracts AuthClaims from context 29 func ExtractClaims(ctx context.Context) (JWTClaims, error) { 30 claims := ctx.Value(JWTClaimsKey) 31 if claims == nil { 32 // We will never have this error because AuthenticateAccess raises error before accessing here. 33 // It means jwtClaims always exists that AuthenticateAccess doesn't raise error. 34 return JWTClaims{}, errors.New("failed to extract jwtClaims") 35 } 36 37 return claims.(JWTClaims), nil 38 }