From 14eea34394022562aaa4f1b7fb3aa880071e4a69 Mon Sep 17 00:00:00 2001 From: c9s Date: Fri, 14 Jan 2022 00:26:53 +0800 Subject: [PATCH] interact: pull out authentication interaction --- examples/interact/main.go | 7 +++++- pkg/interact/auth.go | 47 +++++++++++++++++++++++++++++++++++++++ pkg/interact/interact.go | 9 -------- 3 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 pkg/interact/auth.go diff --git a/examples/interact/main.go b/examples/interact/main.go index ea661fa19..7499ac6ed 100644 --- a/examples/interact/main.go +++ b/examples/interact/main.go @@ -128,7 +128,12 @@ func main() { globalInteraction := interact.New() globalInteraction.SetMessenger(&interact.Telegram{ - Bot: b, + Bot: b, + }) + + globalInteraction.AddCustomInteraction(&interact.AuthInteract{ + Mode: interact.AuthModeToken, + Token: "123", }) globalInteraction.AddCustomInteraction(&PositionInteraction{}) diff --git a/pkg/interact/auth.go b/pkg/interact/auth.go new file mode 100644 index 000000000..9bd472c77 --- /dev/null +++ b/pkg/interact/auth.go @@ -0,0 +1,47 @@ +package interact + +import ( + "errors" + + "github.com/pquerna/otp" +) + +type AuthMode string + +const ( + AuthModeOTP AuthMode = "OTP" + AuthModeToken AuthMode = "TOKEN" +) + +var ErrAuthenticationFailed = errors.New("authentication failed") + +type AuthInteract struct { + Mode AuthMode `json:"authMode"` + + Token string `json:"authToken,omitempty"` + + OneTimePasswordKey *otp.Key `json:"otpKey,omitempty"` +} + +func (i *AuthInteract) Commands(interact *Interact) { + interact.Command("/auth", func(reply Reply) error { + reply.Message("Enter your authentication code") + return nil + }).NamedNext(StateAuthenticated, func(reply Reply, code string) error { + switch i.Mode { + case AuthModeToken: + if code == i.Token { + reply.Message("Great! You're authenticated!") + return nil + } else { + reply.Message("Incorrect authentication code") + return ErrAuthenticationFailed + } + + case AuthModeOTP: + + } + + return nil + }) +} diff --git a/pkg/interact/interact.go b/pkg/interact/interact.go index 50ac637c7..d77275bc8 100644 --- a/pkg/interact/interact.go +++ b/pkg/interact/interact.go @@ -187,15 +187,6 @@ func (i *Interact) SetMessenger(messenger Messenger) { // builtin initializes the built-in commands func (i *Interact) builtin() error { - i.Command("/auth", func(reply Reply) error { - reply.Message("Enter your authentication code") - return nil - }).NamedNext(StateAuthenticated, func(reply Reply, code string) error { - // check code - reply.Message("Great! You're authenticated!") - return nil - }) - i.Command("/uptime", func(reply Reply) error { reply.Message("uptime") return nil