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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. UserUUID string `json:"user_uuid"`
  22. CommunityUUID string `json:"community_uuid"`
  23. jwt.RegisteredClaims
  24. }
  25. func GenerateJwtToken(user_uuid string, community_uuid string) (string, uint, error) {
  26. secret := []byte(config.Config.JWT.Secret)
  27. issuer := config.Config.JWT.Issuer
  28. expireDays := config.Config.JWT.ExpireDays
  29. claims := &JwtClaims{
  30. user_uuid,
  31. community_uuid,
  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. token_string, err := token.SignedString(secret)
  40. expire_time_seconds := uint(time.Now().AddDate(0, 0, expireDays).Unix())
  41. return token_string, expire_time_seconds, err
  42. }
  43. func ParseJwtToken(tokenString string) (*JwtClaims, error) {
  44. secret := []byte(config.Config.JWT.Secret)
  45. token, err := jwt.ParseWithClaims(tokenString, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
  46. return secret, nil
  47. })
  48. if err != nil {
  49. return nil, err
  50. }
  51. if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
  52. return claims, nil
  53. } else {
  54. return nil, err
  55. }
  56. }