login_attempt.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package sqlstore
  2. import (
  3. "strconv"
  4. "time"
  5. "github.com/grafana/grafana/pkg/bus"
  6. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. var getTimeNow = time.Now
  9. func init() {
  10. bus.AddHandler("sql", CreateLoginAttempt)
  11. bus.AddHandler("sql", DeleteOldLoginAttempts)
  12. bus.AddHandler("sql", GetUserLoginAttemptCount)
  13. }
  14. func CreateLoginAttempt(cmd *m.CreateLoginAttemptCommand) error {
  15. return inTransaction(func(sess *DBSession) error {
  16. loginAttempt := m.LoginAttempt{
  17. Username: cmd.Username,
  18. IpAddress: cmd.IpAddress,
  19. Created: getTimeNow().Unix(),
  20. }
  21. if _, err := sess.Insert(&loginAttempt); err != nil {
  22. return err
  23. }
  24. cmd.Result = loginAttempt
  25. return nil
  26. })
  27. }
  28. func DeleteOldLoginAttempts(cmd *m.DeleteOldLoginAttemptsCommand) error {
  29. return inTransaction(func(sess *DBSession) error {
  30. var maxId int64
  31. sql := "SELECT max(id) as id FROM login_attempt WHERE created < ?"
  32. result, err := sess.Query(sql, cmd.OlderThan.Unix())
  33. if err != nil {
  34. return err
  35. }
  36. // nolint: gosimple
  37. if result == nil || len(result) == 0 || result[0] == nil {
  38. return nil
  39. }
  40. maxId = toInt64(result[0]["id"])
  41. if maxId == 0 {
  42. return nil
  43. }
  44. sql = "DELETE FROM login_attempt WHERE id <= ?"
  45. if result, err := sess.Exec(sql, maxId); err != nil {
  46. return err
  47. } else if cmd.DeletedRows, err = result.RowsAffected(); err != nil {
  48. return err
  49. }
  50. return nil
  51. })
  52. }
  53. func GetUserLoginAttemptCount(query *m.GetUserLoginAttemptCountQuery) error {
  54. loginAttempt := new(m.LoginAttempt)
  55. total, err := x.
  56. Where("username = ?", query.Username).
  57. And("created >= ?", query.Since.Unix()).
  58. Count(loginAttempt)
  59. if err != nil {
  60. return err
  61. }
  62. query.Result = total
  63. return nil
  64. }
  65. func toInt64(i interface{}) int64 {
  66. switch i := i.(type) {
  67. case []byte:
  68. n, _ := strconv.ParseInt(string(i), 10, 64)
  69. return n
  70. case int:
  71. return int64(i)
  72. case int64:
  73. return i
  74. }
  75. return 0
  76. }