add plugin system

This commit is contained in:
ginuerzh
2023-04-18 20:52:56 +08:00
parent 7576651a67
commit 32c8188351
48 changed files with 761 additions and 115 deletions

View File

@ -12,6 +12,7 @@ import (
"github.com/go-gost/core/logger"
"github.com/go-gost/x/internal/loader"
xlogger "github.com/go-gost/x/logger"
"google.golang.org/grpc"
)
type options struct {
@ -20,6 +21,7 @@ type options struct {
redisLoader loader.Loader
httpLoader loader.Loader
period time.Duration
client *grpc.ClientConn
logger logger.Logger
}
@ -55,6 +57,12 @@ func HTTPLoaderOption(httpLoader loader.Loader) Option {
}
}
func PluginConnOption(c *grpc.ClientConn) Option {
return func(opts *options) {
opts.client = c
}
}
func LoggerOption(logger logger.Logger) Option {
return func(opts *options) {
opts.logger = logger
@ -97,14 +105,18 @@ func NewAuthenticator(opts ...Option) auth.Authenticator {
}
// Authenticate checks the validity of the provided user-password pair.
func (p *authenticator) Authenticate(user, password string) bool {
if p == nil || len(p.kvs) == 0 {
func (p *authenticator) Authenticate(ctx context.Context, user, password string) bool {
if p == nil {
return true
}
p.mu.RLock()
defer p.mu.RUnlock()
if len(p.kvs) == 0 {
return true
}
v, ok := p.kvs[user]
return ok && (v == "" || password == v)
}

58
auth/plugin.go Normal file
View File

@ -0,0 +1,58 @@
package auth
import (
"context"
"github.com/go-gost/core/auth"
"github.com/go-gost/plugin/auth/proto"
xlogger "github.com/go-gost/x/logger"
)
type pluginAuthenticator struct {
client proto.AuthenticatorClient
options options
}
// NewPluginAuthenticator creates an Authenticator that authenticates client by plugin.
func NewPluginAuthenticator(opts ...Option) auth.Authenticator {
var options options
for _, opt := range opts {
opt(&options)
}
if options.logger == nil {
options.logger = xlogger.Nop()
}
p := &pluginAuthenticator{
options: options,
}
if options.client != nil {
p.client = proto.NewAuthenticatorClient(options.client)
}
return p
}
// Authenticate checks the validity of the provided user-password pair.
func (p *pluginAuthenticator) Authenticate(ctx context.Context, user, password string) bool {
if p.client == nil {
return false
}
r, err := p.client.Authenticate(ctx,
&proto.AuthenticateRequest{
Username: user,
Password: password,
})
if err != nil {
p.options.logger.Error(err)
return false
}
return r.Ok
}
func (p *pluginAuthenticator) Close() error {
if p.options.client != nil {
return p.options.client.Close()
}
return nil
}