You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

jwt.go 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright © 2023 OpenIM open source community. 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. package utils
  15. import (
  16. "time"
  17. "github.com/golang-jwt/jwt/v4"
  18. "github.com/OpenIMSDK/OpenKF/server/internal/config"
  19. )
  20. type JwtClaims struct {
  21. UUID string `json:"uuid"`
  22. CommunityId uint `json:"community_id"`
  23. jwt.RegisteredClaims
  24. }
  25. func GenerateJwtToken(uid string, community_id uint) (string, error) {
  26. secret := []byte(config.Config.JWT.Secret)
  27. issuer := config.Config.JWT.Issuer
  28. expireDays := config.Config.JWT.ExpireDays
  29. claims := &JwtClaims{
  30. uid,
  31. community_id,
  32. jwt.RegisteredClaims{
  33. Issuer: issuer,
  34. NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)),
  35. ExpiresAt: jwt.NewNumericDate(time.Now().AddDate(0, 0, expireDays)),
  36. },
  37. }
  38. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  39. return token.SignedString(secret)
  40. }
  41. func ParseJwtToken(tokenString string) (*JwtClaims, error) {
  42. secret := []byte(config.Config.JWT.Secret)
  43. token, err := jwt.ParseWithClaims(tokenString, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
  44. return secret, nil
  45. })
  46. if err != nil {
  47. return nil, err
  48. }
  49. if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
  50. return claims, nil
  51. } else {
  52. return nil, err
  53. }
  54. }