123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179 |
- package main
- import (
- "context"
- "fmt"
- grpcc "github.com/go-micro/plugins/v4/client/grpc"
- "github.com/go-micro/plugins/v4/registry/consul"
- grpcs "github.com/go-micro/plugins/v4/server/grpc"
- "github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry"
- "github.com/google/uuid"
- "github.com/redis/go-redis/v9"
- "github.com/sirupsen/logrus"
- "go-micro.dev/v4"
- "go-micro.dev/v4/auth"
- "go-micro.dev/v4/registry"
- "go-micro.dev/v4/server"
- "go.opentelemetry.io/otel"
- "go.opentelemetry.io/otel/propagation"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/schema"
- "sghgogs.com/sghblog/authorization-service/config"
- req "sghgogs.com/sghblog/authorization-service/domain/model/request"
- "sghgogs.com/sghblog/authorization-service/domain/repository"
- "sghgogs.com/sghblog/authorization-service/domain/service"
- "sghgogs.com/sghblog/authorization-service/handler"
- authorization_service "sghgogs.com/sghblog/authorization-service/proto"
- "sghgogs.com/sghblog/authorization-service/utils/authutil"
- "sghgogs.com/sghblog/authorization-service/utils/middleware"
- "sghgogs.com/sghblog/authorization-service/utils/tracing"
- "strings"
- "time"
- )
- var (
- name = "authorizationservice"
- version = "1.0.0"
- )
- func main() {
- // Load conigurations
- if err := config.Load(); err != nil {
- logrus.Fatal(err)
- }
- // 1. 连接数据库
- var db *gorm.DB
- if cfg := config.DataBase(); cfg.Enable {
- 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)
- db, _ = gorm.Open(mysql.Open(address), &gorm.Config{
- // Logger: logger.Default.LogMode(logger.Info),
- NamingStrategy: schema.NamingStrategy{
- SingularTable: true,
- }})
- } else {
- // 没有配置数据库
- logrus.Info("There is no database configured")
- }
- if cfg := config.RedisAddress(); cfg.Enable {
- // UpdateRulesItems
- roles := make([]req.AdminRole, 0)
- db.Model(&req.AdminRole{}).Where("status = ?", authorization_service.StatusEnum_ENABLED).Preload("Permissions", "status = ?", authorization_service.StatusEnum_ENABLED).Find(&roles)
- authutil.NewJWTAuth(redis.NewClient(&redis.Options{
- Addr: cfg.URL, // Redis 服务器地址
- Password: cfg.Password, // Redis 密码,如果有的话
- DB: 0, // 默认数据库
- }), name, cfg.Enable, UpdateRulesItems(roles))
- // cfg.Password
- }
- // 2. Create service
- srv := micro.NewService(
- micro.Server(grpcs.NewServer()),
- micro.Client(grpcc.NewClient()),
- )
- authService := authutil.JWTAuthService.Auth
- opts := []micro.Option{
- micro.Name(name),
- micro.Version(version),
- micro.Address(config.Address()),
- micro.Auth(
- authService,
- ),
- }
- // 3.添加注册中心
- if cfg := config.Registry(); cfg.Enable {
- logrus.Info("添加注册中心")
- consul := consul.NewRegistry(func(options *registry.Options) {
- options.Addrs = []string{
- cfg.Consul.URL,
- }
- })
- opts = append(opts, micro.Registry(consul))
- }
- // 4.添加链路追踪
- if cfg := config.Tracing(); cfg.Enable {
- fmt.Println("加入进来了")
- tp, err := tracing.NewTracerProvider(name, version, srv.Server().Options().Id, cfg.Jaeger.URL)
- if err != nil {
- logrus.Fatal(err)
- }
- defer func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
- defer cancel()
- if err := tp.Shutdown(ctx); err != nil {
- logrus.Fatal(err)
- }
- }()
- otel.SetTracerProvider(tp)
- otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
- traceOpts := []opentelemetry.Option{
- opentelemetry.WithHandleFilter(func(ctx context.Context, r server.Request) bool {
- if e := r.Endpoint(); strings.HasPrefix(e, "Health.") {
- return true
- }
- return false
- }),
- }
- opts = append(opts, micro.WrapHandler(opentelemetry.NewHandlerWrapper(traceOpts...)))
- }
- opts = append(opts, micro.WrapHandler(middleware.NewAuthWrapper(srv)))
- srv.Init(opts...)
- // authutil.JWTAuthService.Client
- // 5. 初始化数据库
- newRepository := repository.NewRepository(db)
- newRepository.InitTable()
- // 6.初始化 service
- newService := service.NewService(newRepository)
- // 注册 Register handler
- // 公共
- authorization_service.RegisterCommonServiceHandler(srv.Server(), &handler.AdminCommon{
- Service: newService,
- })
- // 角色相关
- authorization_service.RegisterAdminRoleServiceHandler(srv.Server(), &handler.AdminRole{
- Service: newService,
- })
- authorization_service.RegisterAdminUserServiceHandler(srv.Server(), &handler.AdminUser{Service: newService})
- authorization_service.RegisterAdminPermissionServiceHandler(srv.Server(), &handler.AdminPermission{
- Service: newService,
- })
- // 权限认证使用
- authorization_service.RegisterAuthenticationServiceHandler(srv.Server(), &handler.Authentication{})
- // Run service
- logrus.Info("Run service")
- if err := srv.Run(); err != nil {
- logrus.Fatal(err)
- }
- }
- func UpdateRulesItems(roles []req.AdminRole) []*auth.Rule {
- rules := make([]*auth.Rule, 0)
- for _, role := range roles {
- for _, permission := range role.Permissions {
- rules = append(rules, &auth.Rule{
- Resource: &auth.Resource{
- Name: "authorizationservice",
- Type: "user",
- Endpoint: permission.Endpoint,
- },
- ID: uuid.New().String(),
- Scope: role.Name,
- Priority: 1,
- })
- fmt.Println(&auth.Rule{
- Resource: &auth.Resource{
- Name: "authorizationservice",
- Type: "user",
- Endpoint: permission.Endpoint,
- },
- ID: uuid.New().String(),
- Scope: role.Name,
- Priority: 1,
- })
- }
- }
- return rules
- }
|