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