utils.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package common
  2. import (
  3. "context"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "encoding/hex"
  8. "fmt"
  9. "time"
  10. )
  11. import (
  12. "github.com/gin-gonic/gin"
  13. "github.com/golang-jwt/jwt/v5"
  14. "github.com/spf13/cast"
  15. grpcmd "google.golang.org/grpc/metadata"
  16. )
  17. var CstSh, _ = time.LoadLocation("Asia/Shanghai")
  18. const (
  19. LocateDateFormat = "2006-01-02"
  20. LocateTimeFormat = "2006-01-02 15:04:05"
  21. LocateMilliFormat = "2006-01-02 15:04:05.9999"
  22. )
  23. func Date() string {
  24. return time.Now().In(CstSh).Format(LocateDateFormat)
  25. }
  26. func Now() string {
  27. return time.Now().In(CstSh).Format(LocateTimeFormat)
  28. }
  29. func NowMilli() string {
  30. return time.Now().In(CstSh).Format(LocateMilliFormat)
  31. }
  32. func NewToken(userId uint, name string) (string, int64, error) {
  33. expire := time.Now().AddDate(0, 1, 0)
  34. hmacSampleSecret := []byte(BasicConfig.Jwt)
  35. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  36. "id": userId,
  37. "name": name,
  38. "exp": expire.Unix(),
  39. })
  40. str, err := token.SignedString(hmacSampleSecret)
  41. return str, expire.Unix(), err
  42. }
  43. func ParseToken(tokenString string) (uint, string, error) {
  44. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  45. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  46. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  47. }
  48. return []byte(BasicConfig.Jwt), nil
  49. })
  50. if err != nil {
  51. return 0, "", err
  52. }
  53. claims := token.Claims.(jwt.MapClaims)
  54. return cast.ToUint(claims["id"]), claims["name"].(string), nil
  55. }
  56. func GC2GM(c *gin.Context) context.Context {
  57. md := grpcmd.New(map[string]string{
  58. "uid": cast.ToString(c.GetInt("uid")),
  59. "username": c.GetString("username"),
  60. "language": c.GetString("language"),
  61. "source": c.GetString("source"),
  62. "product": c.GetString("product"),
  63. },
  64. )
  65. return grpcmd.NewOutgoingContext(context.Background(), md)
  66. }
  67. func GetQueryString(c *gin.Context, key string) *string {
  68. if t, ok := c.GetQuery(key); ok {
  69. return &t
  70. }
  71. return nil
  72. }
  73. func IsEnabled(c *gin.Context) *bool {
  74. if isEnabled, ok := c.GetQuery("is_enabled"); ok {
  75. if r, e := cast.ToBoolE(isEnabled); e == nil {
  76. return &r
  77. }
  78. }
  79. return nil
  80. }
  81. func MD5(v []byte) string {
  82. h := md5.New()
  83. h.Write(v)
  84. re := h.Sum(nil)
  85. return hex.EncodeToString(re)
  86. }
  87. var dbPwKey = []byte("X3O6wVF&6*&lSVk0*504V~q7>\"k]6S'*") // 32 bytes for AES-256
  88. var dbPwNonceHex = "1962a6f6f9999447632c8a34"
  89. func EncryptGCM(key []byte, nonce []byte, plaintext []byte) ([]byte, error) {
  90. block, err := aes.NewCipher(key)
  91. if err != nil {
  92. return nil, err
  93. }
  94. gcm, err := cipher.NewGCM(block)
  95. if err != nil {
  96. return nil, err
  97. }
  98. ciphertext := gcm.Seal(nil, nonce, plaintext, nonce)
  99. return ciphertext, nil
  100. }
  101. func DecryptGCM(key []byte, nonce []byte, ciphertext []byte) ([]byte, error) {
  102. block, err := aes.NewCipher(key)
  103. if err != nil {
  104. return nil, err
  105. }
  106. gcm, err := cipher.NewGCM(block)
  107. if err != nil {
  108. return nil, err
  109. }
  110. plaintext, err := gcm.Open(nil, nonce, ciphertext, nonce)
  111. if err != nil {
  112. return nil, err
  113. }
  114. return plaintext, nil
  115. }
  116. func DBPwdEncrypt(ciphertext []byte) ([]byte, error) {
  117. nonce, _ := hex.DecodeString(dbPwNonceHex)
  118. return EncryptGCM(dbPwKey, nonce, ciphertext)
  119. }
  120. func DBPwdDecrypt(ciphertext []byte) ([]byte, error) {
  121. nonce, _ := hex.DecodeString(dbPwNonceHex)
  122. return DecryptGCM(dbPwKey, nonce, ciphertext)
  123. }