forked from baron/baron-sso
54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package audit
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/ClickHouse/clickhouse-go/v2"
|
|
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
|
|
)
|
|
|
|
type AuditLogger struct {
|
|
conn driver.Conn
|
|
}
|
|
|
|
func NewAuditLogger(host string, port int, user, password, db string) (*AuditLogger, error) {
|
|
conn, err := clickhouse.Open(&clickhouse.Options{
|
|
Addr: []string{fmt.Sprintf("%s:%d", host, port)},
|
|
Auth: clickhouse.Auth{
|
|
Database: db,
|
|
Username: user,
|
|
Password: password,
|
|
},
|
|
Debug: true,
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open clickhouse connection: %w", err)
|
|
}
|
|
|
|
if err := conn.Ping(context.Background()); err != nil {
|
|
return nil, fmt.Errorf("failed to ping clickhouse: %w", err)
|
|
}
|
|
|
|
return &AuditLogger{conn: conn}, nil
|
|
}
|
|
|
|
func (l *AuditLogger) CreateSchema(ctx context.Context) error {
|
|
query := `
|
|
CREATE TABLE IF NOT EXISTS audit_logs (
|
|
timestamp DateTime DEFAULT now(),
|
|
user_id String,
|
|
event_type String,
|
|
status String,
|
|
ip_address String,
|
|
user_agent String,
|
|
details String
|
|
) ENGINE = MergeTree()
|
|
ORDER BY timestamp
|
|
`
|
|
return l.conn.Exec(ctx, query)
|
|
}
|