login_form.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package ui
  2. import (
  3. "errors"
  4. "github.com/ayn2op/discordo/internal/config"
  5. "github.com/ayn2op/discordo/internal/constants"
  6. "github.com/diamondburned/arikawa/v3/api"
  7. "github.com/gdamore/tcell/v2"
  8. "github.com/rivo/tview"
  9. "github.com/zalando/go-keyring"
  10. )
  11. type LoginForm struct {
  12. *tview.Form
  13. Token chan string
  14. Error chan error
  15. }
  16. func NewLoginForm(cfg *config.Config) *LoginForm {
  17. lf := &LoginForm{
  18. Form: tview.NewForm(),
  19. Token: make(chan string, 1),
  20. Error: make(chan error),
  21. }
  22. lf.AddInputField("Email", "", 0, nil, nil)
  23. lf.AddPasswordField("Password", "", 0, 0, nil)
  24. lf.AddPasswordField("Code (optional)", "", 0, 0, nil)
  25. lf.AddCheckbox("Remember Me", true, nil)
  26. lf.AddButton("Login", lf.onLoginButtonSelected)
  27. lf.SetTitle("Login")
  28. lf.SetTitleColor(tcell.GetColor(cfg.Theme.TitleColor))
  29. lf.SetTitleAlign(tview.AlignLeft)
  30. p := cfg.Theme.BorderPadding
  31. lf.SetBorder(cfg.Theme.Border)
  32. lf.SetBorderColor(tcell.GetColor(cfg.Theme.BorderColor))
  33. lf.SetBorderPadding(p[0], p[1], p[2], p[3])
  34. return lf
  35. }
  36. func (lf *LoginForm) onLoginButtonSelected() {
  37. email := lf.GetFormItem(0).(*tview.InputField).GetText()
  38. password := lf.GetFormItem(1).(*tview.InputField).GetText()
  39. if email == "" || password == "" {
  40. return
  41. }
  42. // Create a new API client without an authentication token.
  43. apiClient := api.NewClient("")
  44. // Log in using the provided email and password.
  45. lr, err := apiClient.Login(email, password)
  46. if err != nil {
  47. lf.Error <- err
  48. return
  49. }
  50. // If the account has MFA-enabled, attempt to log in using the provided code.
  51. if lr.MFA && lr.Token == "" {
  52. code := lf.GetFormItem(2).(*tview.InputField).GetText()
  53. if code == "" {
  54. return
  55. }
  56. lr, err = apiClient.TOTP(code, lr.Ticket)
  57. if err != nil {
  58. lf.Error <- err
  59. return
  60. }
  61. }
  62. if lr.Token == "" {
  63. lf.Error <- errors.New("token is missing")
  64. return
  65. }
  66. rememberMe := lf.GetFormItem(3).(*tview.Checkbox).IsChecked()
  67. if rememberMe {
  68. go keyring.Set(constants.Name, "token", lr.Token)
  69. }
  70. lf.Token <- lr.Token
  71. }