login_form.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package cmd
  2. import (
  3. "errors"
  4. "github.com/ayn2op/discordo/internal/constants"
  5. "github.com/diamondburned/arikawa/v3/api"
  6. "github.com/gdamore/tcell/v2"
  7. "github.com/rivo/tview"
  8. "github.com/zalando/go-keyring"
  9. )
  10. type DoneFn func(token string, err error)
  11. type LoginForm struct {
  12. *tview.Form
  13. done DoneFn
  14. }
  15. func NewLoginForm(done DoneFn) *LoginForm {
  16. lf := &LoginForm{
  17. Form: tview.NewForm(),
  18. done: done,
  19. }
  20. lf.AddInputField("Email", "", 0, nil, nil)
  21. lf.AddPasswordField("Password", "", 0, 0, nil)
  22. lf.AddPasswordField("Code (optional)", "", 0, 0, nil)
  23. lf.AddCheckbox("Remember Me", true, nil)
  24. lf.AddButton("Login", lf.login)
  25. lf.SetTitle("Login")
  26. lf.SetTitleColor(tcell.GetColor(cfg.Theme.TitleColor))
  27. lf.SetTitleAlign(tview.AlignLeft)
  28. p := cfg.Theme.BorderPadding
  29. lf.SetBorder(cfg.Theme.Border)
  30. lf.SetBorderColor(tcell.GetColor(cfg.Theme.BorderColor))
  31. lf.SetBorderPadding(p[0], p[1], p[2], p[3])
  32. return lf
  33. }
  34. func (lf *LoginForm) login() {
  35. email := lf.GetFormItem(0).(*tview.InputField).GetText()
  36. password := lf.GetFormItem(1).(*tview.InputField).GetText()
  37. if email == "" || password == "" {
  38. return
  39. }
  40. // Create a new API client without an authentication token.
  41. apiClient := api.NewClient("")
  42. // Log in using the provided email and password.
  43. lr, err := apiClient.Login(email, password)
  44. if err != nil {
  45. if lf.done != nil {
  46. lf.done("", err)
  47. }
  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. if lf.done != nil {
  55. lf.done("", errors.New("code required"))
  56. }
  57. return
  58. }
  59. lr, err = apiClient.TOTP(code, lr.Ticket)
  60. if err != nil {
  61. if lf.done != nil {
  62. lf.done("", err)
  63. }
  64. return
  65. }
  66. }
  67. if lr.Token == "" {
  68. if lf.done != nil {
  69. lf.done("", errors.New("missing token"))
  70. }
  71. return
  72. }
  73. rememberMe := lf.GetFormItem(3).(*tview.Checkbox).IsChecked()
  74. if rememberMe {
  75. go func() {
  76. if err := keyring.Set(constants.Name, "token", lr.Token); err != nil {
  77. if lf.done != nil {
  78. lf.done("", err)
  79. }
  80. }
  81. }()
  82. }
  83. if lf.done != nil {
  84. lf.done(lr.Token, nil)
  85. }
  86. }