github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/plugins/auth/auth.go (about)

     1  package auth
     2  
     3  import (
     4  	"github.com/nyan233/littlerpc/core/common/errorhandler"
     5  	"github.com/nyan233/littlerpc/core/middle/plugin"
     6  	perror "github.com/nyan233/littlerpc/core/protocol/error"
     7  	"github.com/nyan233/littlerpc/core/protocol/message"
     8  )
     9  
    10  const (
    11  	NameKey     = "user"
    12  	PasswordKey = "password"
    13  )
    14  
    15  var (
    16  	ErrorFailed = errorhandler.DefaultErrHandler.LNewErrorDesc(10024, "user_name or password never correct")
    17  )
    18  
    19  type LRPCAuthorization struct {
    20  	plugin.Abstract
    21  	UserName, Password string
    22  }
    23  
    24  func NewBasicAuth(userName, password string) plugin.Plugin {
    25  	return &LRPCAuthorization{
    26  		UserName: userName,
    27  		Password: password,
    28  	}
    29  }
    30  
    31  func (a *LRPCAuthorization) Receive4S(pub *plugin.Context, msg *message.Message) perror.LErrorDesc {
    32  	name := msg.MetaData.Load(NameKey)
    33  	password := msg.MetaData.Load(PasswordKey)
    34  	if name != a.UserName && password != a.Password {
    35  		pub.Logger.Info("authorization failed user_name=%s password=%s", name, password)
    36  		return ErrorFailed
    37  	}
    38  	return nil
    39  }
    40  
    41  func (a *LRPCAuthorization) Send4C(pub *plugin.Context, msg *message.Message, err perror.LErrorDesc) perror.LErrorDesc {
    42  	if err != nil {
    43  		return nil
    44  	}
    45  	if a.UserName == "" && a.Password == "" {
    46  		return nil
    47  	}
    48  	msg.MetaData.Store(NameKey, a.UserName)
    49  	msg.MetaData.Store(PasswordKey, a.Password)
    50  	return nil
    51  }