login_attempt.go 1.8 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. if result == nil || len(result) == 0 || result[0] == nil {
  37. return nil
  38. }
  39. maxId = toInt64(result[0]["id"])
  40. if maxId == 0 {
  41. return nil
  42. }
  43. sql = "DELETE FROM login_attempt WHERE id <= ?"
  44. if result, err := sess.Exec(sql, maxId); err != nil {
  45. return err
  46. } else if cmd.DeletedRows, err = result.RowsAffected(); err != nil {
  47. return err
  48. }
  49. return nil
  50. })
  51. }
  52. func GetUserLoginAttemptCount(query *m.GetUserLoginAttemptCountQuery) error {
  53. loginAttempt := new(m.LoginAttempt)
  54. total, err := x.
  55. Where("username = ?", query.Username).
  56. And("created >= ?", query.Since.Unix()).
  57. Count(loginAttempt)
  58. if err != nil {
  59. return err
  60. }
  61. query.Result = total
  62. return nil
  63. }
  64. func toInt64(i interface{}) int64 {
  65. switch i := i.(type) {
  66. case []byte:
  67. n, _ := strconv.ParseInt(string(i), 10, 64)
  68. return n
  69. case int:
  70. return int64(i)
  71. case int64:
  72. return i
  73. }
  74. return 0
  75. }