github.com/infraboard/keyauth@v0.8.1/apps/role/impl/impl.go (about)

     1  package impl
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/infraboard/mcube/app"
     7  	"github.com/infraboard/mcube/logger"
     8  	"github.com/infraboard/mcube/logger/zap"
     9  	"go.mongodb.org/mongo-driver/mongo"
    10  	"go.mongodb.org/mongo-driver/mongo/options"
    11  	"go.mongodb.org/mongo-driver/x/bsonx"
    12  	"google.golang.org/grpc"
    13  
    14  	"github.com/infraboard/keyauth/apps/policy"
    15  	"github.com/infraboard/keyauth/apps/role"
    16  	"github.com/infraboard/keyauth/conf"
    17  )
    18  
    19  var (
    20  	// Service 服务实例
    21  	svr = &service{}
    22  )
    23  
    24  type service struct {
    25  	col  *mongo.Collection
    26  	perm *mongo.Collection
    27  
    28  	policy policy.ServiceServer
    29  	log    logger.Logger
    30  	role.UnimplementedServiceServer
    31  }
    32  
    33  func (s *service) Config() error {
    34  	s.policy = app.GetGrpcApp(policy.AppName).(policy.ServiceServer)
    35  
    36  	db := conf.C().Mongo.GetDB()
    37  	col := db.Collection("role")
    38  
    39  	indexs := []mongo.IndexModel{
    40  		{
    41  			Keys: bsonx.Doc{
    42  				{Key: "name", Value: bsonx.Int32(-1)},
    43  				{Key: "domain", Value: bsonx.Int32(-1)},
    44  			},
    45  			Options: options.Index().SetUnique(true),
    46  		},
    47  		{
    48  			Keys: bsonx.Doc{{Key: "create_at", Value: bsonx.Int32(-1)}},
    49  		},
    50  	}
    51  
    52  	_, err := col.Indexes().CreateMany(context.Background(), indexs)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	perm := db.Collection("permission")
    58  	permIndexs := []mongo.IndexModel{
    59  		{
    60  			Keys: bsonx.Doc{{Key: "create_at", Value: bsonx.Int32(-1)}},
    61  		},
    62  	}
    63  
    64  	_, err = perm.Indexes().CreateMany(context.Background(), permIndexs)
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	s.col = col
    70  	s.perm = perm
    71  	s.log = zap.L().Named("Role")
    72  	return nil
    73  }
    74  
    75  func (s *service) Name() string {
    76  	return role.AppName
    77  }
    78  
    79  func (s *service) Registry(server *grpc.Server) {
    80  	role.RegisterServiceServer(server, svr)
    81  }
    82  
    83  func init() {
    84  	app.RegistryGrpcApp(svr)
    85  }