github.heygears.com/openimsdk/tools@v0.0.49/tokenverify/jwt_token.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tokenverify
    16  
    17  import (
    18  	"time"
    19  
    20  	"github.com/golang-jwt/jwt/v4"
    21  	"github.com/openimsdk/tools/errs"
    22  )
    23  
    24  const HoursOneDay = 24
    25  const minutesBefore = 5
    26  
    27  type Claims struct {
    28  	UserID     string
    29  	PlatformID int // login platform
    30  	jwt.RegisteredClaims
    31  }
    32  
    33  func BuildClaims(uid string, platformID int, ttl int64) Claims {
    34  	now := time.Now()
    35  	before := now.Add(-time.Minute * time.Duration(minutesBefore))
    36  	return Claims{
    37  		UserID:     uid,
    38  		PlatformID: platformID,
    39  		RegisteredClaims: jwt.RegisteredClaims{
    40  			ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*HoursOneDay) * time.Hour)), // Expiration time
    41  			IssuedAt:  jwt.NewNumericDate(now),                                                 // Issuing time
    42  			NotBefore: jwt.NewNumericDate(before),                                              // Begin Effective time
    43  		},
    44  	}
    45  }
    46  
    47  func GetClaimFromToken(tokensString string, secretFunc jwt.Keyfunc) (*Claims, error) {
    48  	token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secretFunc)
    49  	if err == nil {
    50  		if claims, ok := token.Claims.(*Claims); ok && token.Valid {
    51  			return claims, nil
    52  		}
    53  		return nil, errs.ErrTokenUnknown
    54  	}
    55  
    56  	if ve, ok := err.(*jwt.ValidationError); ok {
    57  		return nil, mapValidationError(ve)
    58  	}
    59  
    60  	return nil, errs.ErrTokenUnknown
    61  }
    62  
    63  func mapValidationError(ve *jwt.ValidationError) error {
    64  	if ve.Errors&jwt.ValidationErrorMalformed != 0 {
    65  		return errs.ErrTokenMalformed
    66  	} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
    67  		return errs.ErrTokenExpired
    68  	} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
    69  		return errs.ErrTokenNotValidYet
    70  	}
    71  	return errs.ErrTokenUnknown
    72  }