main.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. grpcc "github.com/go-micro/plugins/v4/client/grpc"
  6. "github.com/go-micro/plugins/v4/registry/consul"
  7. grpcs "github.com/go-micro/plugins/v4/server/grpc"
  8. "github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry"
  9. "github.com/google/uuid"
  10. "github.com/redis/go-redis/v9"
  11. "github.com/sirupsen/logrus"
  12. "go-micro.dev/v4"
  13. "go-micro.dev/v4/auth"
  14. "go-micro.dev/v4/registry"
  15. "go-micro.dev/v4/server"
  16. "go.opentelemetry.io/otel"
  17. "go.opentelemetry.io/otel/propagation"
  18. "gorm.io/driver/mysql"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/schema"
  21. "sghgogs.com/sghblog/authorization-service/config"
  22. req "sghgogs.com/sghblog/authorization-service/domain/model/request"
  23. "sghgogs.com/sghblog/authorization-service/domain/repository"
  24. "sghgogs.com/sghblog/authorization-service/domain/service"
  25. "sghgogs.com/sghblog/authorization-service/handler"
  26. authorization_service "sghgogs.com/sghblog/authorization-service/proto"
  27. "sghgogs.com/sghblog/authorization-service/utils/authutil"
  28. "sghgogs.com/sghblog/authorization-service/utils/middleware"
  29. "sghgogs.com/sghblog/authorization-service/utils/tracing"
  30. "strings"
  31. "time"
  32. )
  33. var (
  34. name = "authorizationservice"
  35. version = "1.0.0"
  36. )
  37. func main() {
  38. // Load conigurations
  39. if err := config.Load(); err != nil {
  40. logrus.Fatal(err)
  41. }
  42. // 1. 连接数据库
  43. var db *gorm.DB
  44. if cfg := config.DataBase(); cfg.Enable {
  45. address := fmt.Sprintf("%v:%v@(%v:%v)/%v?charset=utf8mb4,utf8&parseTime=True&loc=Local", cfg.Mysql.User, cfg.Mysql.Password, cfg.Mysql.Host, cfg.Mysql.Port, cfg.Mysql.DataBase)
  46. db, _ = gorm.Open(mysql.Open(address), &gorm.Config{
  47. // Logger: logger.Default.LogMode(logger.Info),
  48. NamingStrategy: schema.NamingStrategy{
  49. SingularTable: true,
  50. }})
  51. } else {
  52. // 没有配置数据库
  53. logrus.Info("There is no database configured")
  54. }
  55. if cfg := config.RedisAddress(); cfg.Enable {
  56. // UpdateRulesItems
  57. roles := make([]req.AdminRole, 0)
  58. db.Model(&req.AdminRole{}).Where("status = ?", authorization_service.StatusEnum_ENABLED).Preload("Permissions", "status = ?", authorization_service.StatusEnum_ENABLED).Find(&roles)
  59. authutil.NewJWTAuth(redis.NewClient(&redis.Options{
  60. Addr: cfg.URL, // Redis 服务器地址
  61. Password: cfg.Password, // Redis 密码,如果有的话
  62. DB: 0, // 默认数据库
  63. }), name, cfg.Enable, UpdateRulesItems(roles))
  64. // cfg.Password
  65. }
  66. // 2. Create service
  67. srv := micro.NewService(
  68. micro.Server(grpcs.NewServer()),
  69. micro.Client(grpcc.NewClient()),
  70. )
  71. authService := authutil.JWTAuthService.Auth
  72. opts := []micro.Option{
  73. micro.Name(name),
  74. micro.Version(version),
  75. micro.Address(config.Address()),
  76. micro.Auth(
  77. authService,
  78. ),
  79. }
  80. // 3.添加注册中心
  81. if cfg := config.Registry(); cfg.Enable {
  82. logrus.Info("添加注册中心")
  83. consul := consul.NewRegistry(func(options *registry.Options) {
  84. options.Addrs = []string{
  85. cfg.Consul.URL,
  86. }
  87. })
  88. opts = append(opts, micro.Registry(consul))
  89. }
  90. // 4.添加链路追踪
  91. if cfg := config.Tracing(); cfg.Enable {
  92. fmt.Println("加入进来了")
  93. tp, err := tracing.NewTracerProvider(name, version, srv.Server().Options().Id, cfg.Jaeger.URL)
  94. if err != nil {
  95. logrus.Fatal(err)
  96. }
  97. defer func() {
  98. ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
  99. defer cancel()
  100. if err := tp.Shutdown(ctx); err != nil {
  101. logrus.Fatal(err)
  102. }
  103. }()
  104. otel.SetTracerProvider(tp)
  105. otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
  106. traceOpts := []opentelemetry.Option{
  107. opentelemetry.WithHandleFilter(func(ctx context.Context, r server.Request) bool {
  108. if e := r.Endpoint(); strings.HasPrefix(e, "Health.") {
  109. return true
  110. }
  111. return false
  112. }),
  113. }
  114. opts = append(opts, micro.WrapHandler(opentelemetry.NewHandlerWrapper(traceOpts...)))
  115. }
  116. opts = append(opts, micro.WrapHandler(middleware.NewAuthWrapper(srv)))
  117. srv.Init(opts...)
  118. // authutil.JWTAuthService.Client
  119. // 5. 初始化数据库
  120. newRepository := repository.NewRepository(db)
  121. newRepository.InitTable()
  122. // 6.初始化 service
  123. newService := service.NewService(newRepository)
  124. // 注册 Register handler
  125. // 公共
  126. authorization_service.RegisterCommonServiceHandler(srv.Server(), &handler.AdminCommon{
  127. Service: newService,
  128. })
  129. // 角色相关
  130. authorization_service.RegisterAdminRoleServiceHandler(srv.Server(), &handler.AdminRole{
  131. Service: newService,
  132. })
  133. authorization_service.RegisterAdminUserServiceHandler(srv.Server(), &handler.AdminUser{Service: newService})
  134. authorization_service.RegisterAdminPermissionServiceHandler(srv.Server(), &handler.AdminPermission{
  135. Service: newService,
  136. })
  137. // 权限认证使用
  138. authorization_service.RegisterAuthenticationServiceHandler(srv.Server(), &handler.Authentication{})
  139. // Run service
  140. logrus.Info("Run service")
  141. if err := srv.Run(); err != nil {
  142. logrus.Fatal(err)
  143. }
  144. }
  145. func UpdateRulesItems(roles []req.AdminRole) []*auth.Rule {
  146. rules := make([]*auth.Rule, 0)
  147. for _, role := range roles {
  148. for _, permission := range role.Permissions {
  149. rules = append(rules, &auth.Rule{
  150. Resource: &auth.Resource{
  151. Name: "authorizationservice",
  152. Type: "user",
  153. Endpoint: permission.Endpoint,
  154. },
  155. ID: uuid.New().String(),
  156. Scope: role.Name,
  157. Priority: 1,
  158. })
  159. fmt.Println(&auth.Rule{
  160. Resource: &auth.Resource{
  161. Name: "authorizationservice",
  162. Type: "user",
  163. Endpoint: permission.Endpoint,
  164. },
  165. ID: uuid.New().String(),
  166. Scope: role.Name,
  167. Priority: 1,
  168. })
  169. }
  170. }
  171. return rules
  172. }