Skip to content

Commit 191e171

Browse files
committed
Add command for deleting expired sessions
1 parent 57fdc1e commit 191e171

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

backend/command/session.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,24 @@ import (
44
"time"
55

66
"github.com/theandrew168/bloggulus/backend/repository"
7+
"github.com/theandrew168/bloggulus/backend/timeutil"
78
)
89

910
func (cmd *Command) DeleteExpiredSessions(now time.Time) error {
1011
return cmd.repo.WithTransaction(func(tx *repository.Repository) error {
12+
now := timeutil.Now()
13+
expiredSessions, err := tx.Session().ListExpired(now)
14+
if err != nil {
15+
return err
16+
}
17+
18+
for _, session := range expiredSessions {
19+
err := tx.Session().Delete(session)
20+
if err != nil {
21+
return err
22+
}
23+
}
24+
1125
return nil
1226
})
1327
}

backend/repository/session.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,44 @@ func (r *SessionRepository) ReadBySessionID(sessionID string) (*model.Session, e
148148
return row.unmarshal()
149149
}
150150

151+
func (r *SessionRepository) ListExpired(now time.Time) ([]*model.Session, error) {
152+
stmt := `
153+
SELECT
154+
session.id,
155+
session.account_id,
156+
session.hash,
157+
session.expires_at,
158+
session.created_at,
159+
session.updated_at
160+
FROM session
161+
WHERE session.expires_at <= $1`
162+
163+
ctx, cancel := context.WithTimeout(context.Background(), postgres.Timeout)
164+
defer cancel()
165+
166+
rows, err := r.conn.Query(ctx, stmt, now)
167+
if err != nil {
168+
return nil, err
169+
}
170+
171+
sessionRows, err := pgx.CollectRows(rows, pgx.RowToStructByName[dbSession])
172+
if err != nil {
173+
return nil, postgres.CheckListError(err)
174+
}
175+
176+
var sessions []*model.Session
177+
for _, row := range sessionRows {
178+
session, err := row.unmarshal()
179+
if err != nil {
180+
return nil, err
181+
}
182+
183+
sessions = append(sessions, session)
184+
}
185+
186+
return sessions, nil
187+
}
188+
151189
func (r *SessionRepository) Delete(session *model.Session) error {
152190
stmt := `
153191
DELETE FROM session

0 commit comments

Comments
 (0)