login_form.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package cmd
  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 doneFn func(token string, err error)
  12. type loginForm struct {
  13. *tview.Form
  14. done doneFn
  15. }
  16. func newLoginForm(done doneFn, cfg *config.Config) *loginForm {
  17. if done == nil {
  18. done = func(_ string, _ error) {}
  19. }
  20. lf := &loginForm{
  21. Form: tview.NewForm(),
  22. done: done,
  23. }
  24. lf.AddInputField("Email", "", 0, nil, nil)
  25. lf.AddPasswordField("Password", "", 0, 0, nil)
  26. lf.AddPasswordField("Code (optional)", "", 0, 0, nil)
  27. lf.AddCheckbox("Remember Me", true, nil)
  28. lf.AddButton("Login", lf.login)
  29. lf.SetTitle("Login")
  30. lf.SetTitleColor(tcell.GetColor(cfg.Theme.TitleColor))
  31. lf.SetTitleAlign(tview.AlignLeft)
  32. p := cfg.Theme.BorderPadding
  33. lf.SetBorder(cfg.Theme.Border)
  34. lf.SetBorderColor(tcell.GetColor(cfg.Theme.BorderColor))
  35. lf.SetBorderPadding(p[0], p[1], p[2], p[3])
  36. return lf
  37. }
  38. func (lf *loginForm) login() {
  39. email := lf.GetFormItem(0).(*tview.InputField).GetText()
  40. password := lf.GetFormItem(1).(*tview.InputField).GetText()
  41. if email == "" || password == "" {
  42. return
  43. }
  44. // Create a new API client without an authentication token.
  45. apiClient := api.NewClient("")
  46. // Log in using the provided email and password.
  47. lr, err := apiClient.Login(email, password)
  48. if err != nil {
  49. lf.done("", err)
  50. return
  51. }
  52. // If the account has MFA-enabled, attempt to log in using the provided code.
  53. if lr.MFA && lr.Token == "" {
  54. code := lf.GetFormItem(2).(*tview.InputField).GetText()
  55. if code == "" {
  56. lf.done("", errors.New("code required"))
  57. return
  58. }
  59. lr, err = apiClient.TOTP(code, lr.Ticket)
  60. if err != nil {
  61. lf.done("", err)
  62. return
  63. }
  64. }
  65. if lr.Token == "" {
  66. lf.done("", errors.New("missing token"))
  67. return
  68. }
  69. rememberMe := lf.GetFormItem(3).(*tview.Checkbox).IsChecked()
  70. if rememberMe {
  71. go func() {
  72. if err := keyring.Set(constants.Name, "token", lr.Token); err != nil {
  73. lf.done("", err)
  74. }
  75. }()
  76. }
  77. lf.done(lr.Token, nil)
  78. }