login_form.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package ui
  2. import (
  3. "context"
  4. "log"
  5. "github.com/ayn2op/discordo/config"
  6. "github.com/diamondburned/arikawa/v3/api"
  7. "github.com/rivo/tview"
  8. "github.com/zalando/go-keyring"
  9. )
  10. type LoginForm struct {
  11. *tview.Form
  12. app *Application
  13. }
  14. func newLoginForm(app *Application) *LoginForm {
  15. lf := &LoginForm{
  16. Form: tview.NewForm(),
  17. app: app,
  18. }
  19. lf.AddInputField("Email", "", 0, nil, nil)
  20. lf.AddPasswordField("Password", "", 0, 0, nil)
  21. lf.AddPasswordField("Code (optional)", "", 0, 0, nil)
  22. lf.AddButton("Login", lf.onLoginButtonSelected)
  23. lf.SetTitle("Login")
  24. lf.SetTitleAlign(tview.AlignLeft)
  25. lf.SetBorder(true)
  26. lf.SetBorderPadding(1, 1, 1, 1)
  27. return lf
  28. }
  29. func (v *LoginForm) onLoginButtonSelected() {
  30. email := v.GetFormItem(0).(*tview.InputField).GetText()
  31. password := v.GetFormItem(1).(*tview.InputField).GetText()
  32. if email == "" || password == "" {
  33. return
  34. }
  35. // Make a scratch HTTP client without a token
  36. client := api.NewClient("").WithContext(context.Background())
  37. // Try to login without TOTP
  38. l, err := client.Login(email, password)
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. // If the token is not dispatched in the response and the "mfa" field is set as true, login using MFA instead.
  43. if l.Token == "" && l.MFA {
  44. code := v.GetFormItem(2).(*tview.InputField).GetText()
  45. if code == "" {
  46. return
  47. }
  48. // Retry logging in with a 2FA token
  49. l, err = client.TOTP(code, l.Ticket)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. }
  54. err = v.app.Connect(l.Token)
  55. if err != nil {
  56. log.Fatal(err)
  57. }
  58. v.app.SetRoot(v.app.view, true)
  59. v.app.SetFocus(v.app.view.GuildsTree)
  60. go keyring.Set(config.Name, "token", l.Token)
  61. }