github.com/weplanx/server@v0.2.6-0.20240318110640-f7e75155779a/xapi/emqx/service.go (about)

     1  package emqx
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/cloudwego/hertz/pkg/common/errors"
     7  	transfer "github.com/weplanx/collector/client"
     8  	"github.com/weplanx/go/passport"
     9  	"github.com/weplanx/server/common"
    10  	"github.com/weplanx/server/model"
    11  	"go.mongodb.org/mongo-driver/bson"
    12  	"go.mongodb.org/mongo-driver/bson/primitive"
    13  	"strings"
    14  	"time"
    15  )
    16  
    17  type Service struct {
    18  	*common.Inject
    19  }
    20  
    21  func (x *Service) Auth(ctx context.Context, dto AuthDto) (err error) {
    22  	var data model.Project
    23  	id, _ := primitive.ObjectIDFromHex(dto.Identity)
    24  	if err = x.Db.Collection("projects").
    25  		FindOne(ctx, bson.M{"_id": id}).
    26  		Decode(&data); err != nil {
    27  		return
    28  	}
    29  	p := passport.New(
    30  		passport.SetIssuer(x.V.Namespace),
    31  		passport.SetKey(fmt.Sprintf(`%s:%s`, data.SecretId, data.SecretKey)),
    32  	)
    33  	if _, err = p.Verify(dto.Token); err != nil {
    34  		return
    35  	}
    36  	return
    37  }
    38  
    39  func (x *Service) Acl(ctx context.Context, dto AclDto) (err error) {
    40  	deny := true
    41  	topic := strings.Split(dto.Topic, "/")
    42  	msg := fmt.Sprintf(`The user [%s] is not authorized for this topic [%s]`,
    43  		dto.Identity, dto.Topic)
    44  	if !(len(topic) >= 2 && topic[1] == dto.Identity) {
    45  		return errors.NewPublic(msg)
    46  	}
    47  	var data model.Imessage
    48  	if err = x.Db.Collection("imessages").
    49  		FindOne(ctx, bson.M{"topic": topic[0]}).
    50  		Decode(&data); err != nil {
    51  		return
    52  	}
    53  	for _, pid := range data.Projects {
    54  		if pid.Hex() == dto.Identity {
    55  			deny = false
    56  			break
    57  		}
    58  	}
    59  	if deny {
    60  		return errors.NewPublic(msg)
    61  	}
    62  	return
    63  }
    64  
    65  func (x *Service) Bridge(ctx context.Context, dto BridgeDto) (err error) {
    66  	return x.Transfer.Publish(ctx, "logset_imessages", transfer.Payload{
    67  		Timestamp: time.Now(),
    68  		Data: map[string]interface{}{
    69  			"metadata": map[string]interface{}{
    70  				"client": dto.Client,
    71  				"topic":  dto.Topic,
    72  			},
    73  			"payload": dto.Payload,
    74  		},
    75  	})
    76  }