interact: pull out authentication interaction

This commit is contained in:
c9s 2022-01-14 00:26:53 +08:00
parent 91c831140c
commit 14eea34394
3 changed files with 53 additions and 10 deletions

View File

@ -131,6 +131,11 @@ func main() {
Bot: b, Bot: b,
}) })
globalInteraction.AddCustomInteraction(&interact.AuthInteract{
Mode: interact.AuthModeToken,
Token: "123",
})
globalInteraction.AddCustomInteraction(&PositionInteraction{}) globalInteraction.AddCustomInteraction(&PositionInteraction{})
if err := globalInteraction.Start(ctx); err != nil { if err := globalInteraction.Start(ctx); err != nil {
log.Fatal(err) log.Fatal(err)

47
pkg/interact/auth.go Normal file
View File

@ -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
})
}

View File

@ -187,15 +187,6 @@ func (i *Interact) SetMessenger(messenger Messenger) {
// builtin initializes the built-in commands // builtin initializes the built-in commands
func (i *Interact) builtin() error { 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 { i.Command("/uptime", func(reply Reply) error {
reply.Message("uptime") reply.Message("uptime")
return nil return nil