login_form.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/ayn2op/discordo/internal/config"
  6. "github.com/diamondburned/arikawa/v3/api"
  7. "github.com/gdamore/tcell/v2"
  8. "github.com/rivo/tview"
  9. )
  10. type LoginForm struct {
  11. *tview.Form
  12. }
  13. func newLoginForm() *LoginForm {
  14. lf := &LoginForm{
  15. Form: tview.NewForm(),
  16. }
  17. lf.AddInputField("Email", "", 0, nil, nil)
  18. lf.AddPasswordField("Password", "", 0, 0, nil)
  19. lf.AddPasswordField("Code (optional)", "", 0, 0, nil)
  20. lf.AddButton("Login", lf.onLoginButtonSelected)
  21. lf.SetTitle("Login")
  22. lf.SetTitleColor(tcell.GetColor(config.Current.Theme.TitleColor))
  23. p := config.Current.Theme.BorderPadding
  24. lf.SetBorder(config.Current.Theme.Border)
  25. lf.SetBorderColor(tcell.GetColor(config.Current.Theme.BorderColor))
  26. lf.SetBorderPadding(p[0], p[1], p[2], p[3])
  27. return lf
  28. }
  29. func (lf *LoginForm) onLoginButtonSelected() {
  30. email := lf.GetFormItem(0).(*tview.InputField).GetText()
  31. password := lf.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. // Retry logging in with a 2FA token
  43. if l.Token == "" && l.MFA {
  44. code := lf.GetFormItem(2).(*tview.InputField).GetText()
  45. if code == "" {
  46. return
  47. }
  48. l, err = client.TOTP(code, l.Ticket)
  49. if err != nil {
  50. log.Fatal(err)
  51. }
  52. }
  53. mainFlex = newMainFlex()
  54. // We got the token, return with a new Session.
  55. if err = openState(l.Token); err != nil {
  56. log.Fatal(err)
  57. }
  58. app.SetRoot(mainFlex, true)
  59. }