brute_force_login_protection.go 981 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package login
  2. import (
  3. "time"
  4. "github.com/grafana/grafana/pkg/bus"
  5. m "github.com/grafana/grafana/pkg/models"
  6. "github.com/grafana/grafana/pkg/setting"
  7. )
  8. var (
  9. maxInvalidLoginAttempts int64 = 5
  10. loginAttemptsWindow = time.Minute * 5
  11. )
  12. var validateLoginAttempts = func(username string) error {
  13. if setting.DisableBruteForceLoginProtection {
  14. return nil
  15. }
  16. loginAttemptCountQuery := m.GetUserLoginAttemptCountQuery{
  17. Username: username,
  18. Since: time.Now().Add(-loginAttemptsWindow),
  19. }
  20. if err := bus.Dispatch(&loginAttemptCountQuery); err != nil {
  21. return err
  22. }
  23. if loginAttemptCountQuery.Result >= maxInvalidLoginAttempts {
  24. return ErrTooManyLoginAttempts
  25. }
  26. return nil
  27. }
  28. var saveInvalidLoginAttempt = func(query *m.LoginUserQuery) {
  29. if setting.DisableBruteForceLoginProtection {
  30. return
  31. }
  32. loginAttemptCommand := m.CreateLoginAttemptCommand{
  33. Username: query.Username,
  34. IpAddress: query.IpAddress,
  35. }
  36. bus.Dispatch(&loginAttemptCommand)
  37. }