InitGroup.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package jwtx
  2. import (
  3. "crypto/ecdsa"
  4. "time"
  5. "github.com/5-say/go-tool/crypto/ecdsatool"
  6. "github.com/5-say/go-tool/gin/jwtx/db/dao/model"
  7. "github.com/5-say/go-tool/gin/jwtx/tool"
  8. "github.com/5-say/go-tool/gorm/mysqlx"
  9. "github.com/5-say/go-tool/logx"
  10. "github.com/5-say/go-tool/utilx"
  11. "github.com/jinzhu/configor"
  12. "gorm.io/gorm"
  13. "gorm.io/gorm/logger"
  14. _ "embed"
  15. )
  16. // 初始化分组(支持多次调用)
  17. //
  18. // group string 分组名称
  19. // configPath string 分组配置文件路径
  20. // privateKeyPath string 分组私钥文件路径
  21. //
  22. // e.g.
  23. //
  24. // jwtx.InitGroup("admin", "jwtx/config/admin.yaml", "jwtx/config/admin.key")
  25. // jwtx.InitGroup("user", "jwtx/config/user.yaml", "jwtx/config/user.key")
  26. func InitGroup(group, configPath, privateKeyPath string) *SingletonT {
  27. // 配置文件不存在则创建
  28. createConfigFileIfNotExist(configPath)
  29. // 私钥文件不存在则创建
  30. createKeyFileIfNotExist(privateKeyPath)
  31. // 取得单例
  32. if Singleton == nil {
  33. Singleton = &SingletonT{}
  34. Singleton.DB = make(map[string]*gorm.DB)
  35. Singleton.Config = make(map[string]GroupConfig)
  36. Singleton.PrivateKey = make(map[string]*ecdsa.PrivateKey)
  37. }
  38. // 引用简化
  39. var s = Singleton
  40. // 初始化分组配置,每秒自动更新
  41. var config GroupConfig
  42. err := configor.New(&configor.Config{AutoReload: true}).Load(&config, configPath)
  43. if err != nil {
  44. panic(err)
  45. }
  46. s.Config[group] = config
  47. // 初始化分组数据库连接
  48. s.DB[group], err = mysqlx.New(config.MysqlDSN, logx.GormLogger(logger.Config{
  49. SlowThreshold: 200 * time.Millisecond,
  50. IgnoreRecordNotFoundError: false,
  51. ParameterizedQueries: false,
  52. LogLevel: logger.Warn,
  53. }))
  54. if err != nil {
  55. panic(err)
  56. }
  57. // 初始化数据库结构
  58. s.DB[group].AutoMigrate(&model.JwtxToken{})
  59. // 初始化分组私钥
  60. privateKey, err := tool.GetPrivateKey(privateKeyPath)
  61. if err != nil {
  62. panic(err)
  63. }
  64. s.PrivateKey[group] = privateKey
  65. return s
  66. }
  67. //go:embed example/demo.yaml
  68. var demoConfig string
  69. func createConfigFileIfNotExist(filePath string) {
  70. utilx.ForceCreateWriteIfNotExist(filePath, 0755, demoConfig)
  71. }
  72. func createKeyFileIfNotExist(filePath string) {
  73. key, _ := ecdsatool.GenerateKey(ecdsatool.P_384)
  74. privateKeyPEMBytes, _ := ecdsatool.PEM_EncodePrivateKey(key)
  75. content := "\n"
  76. content += "密钥格式: NIST P-384"
  77. content += "\n\n"
  78. content += string(privateKeyPEMBytes)
  79. content += "\n"
  80. content += "密钥格式: NIST P-384"
  81. content += "\n"
  82. utilx.ForceCreateWriteIfNotExist(filePath, 0755, content)
  83. }