Change store All to use channel

This commit is contained in:
2022-08-26 12:21:52 +02:00
parent 4c77b5ef9b
commit 07fe16b72a
6 changed files with 52 additions and 22 deletions

View File

@@ -9,6 +9,8 @@ import (
_ "github.com/jackc/pgx/v4/stdlib"
)
var _ LoginAttemptStore = &PostgresStore{}
const DBSchema = `
CREATE TABLE IF NOT EXISTS login_attempts(
id serial PRIMARY KEY,
@@ -61,27 +63,30 @@ RETURNING id;`
return tx.Commit()
}
func (s *PostgresStore) All() ([]models.LoginAttempt, error) {
func (s *PostgresStore) All() (<-chan models.LoginAttempt, error) {
stmt := `SELECT date, remote_ip, username, password, client_version, connection_uuid, country FROM login_attempts`
rows, err := s.db.Query(stmt)
if err != nil {
return nil, err
}
defer rows.Close()
var attempts []models.LoginAttempt
for rows.Next() {
var a models.LoginAttempt
var ip string
if err := rows.Scan(&a.Date, &ip, &a.Username, &a.Password, &a.SSHClientVersion, &a.SSHClientVersion, &a.Country); err != nil {
return nil, err
ch := make(chan models.LoginAttempt)
go func() {
defer rows.Close()
for rows.Next() {
var a models.LoginAttempt
var ip string
if err := rows.Scan(&a.Date, &ip, &a.Username, &a.Password, &a.SSHClientVersion, &a.SSHClientVersion, &a.Country); err != nil {
panic(err)
}
a.RemoteIP = net.ParseIP(ip)
ch <- a
}
a.RemoteIP = net.ParseIP(ip)
attempts = append(attempts, a)
}
close(ch)
}()
return attempts, nil
return ch, nil
}
func (s *PostgresStore) Stats(statType LoginStats, limit int) ([]StatsResult, error) {