summaryrefslogtreecommitdiff
path: root/pkg/database/sessions.go
blob: decba8eb8ea49f49b4b657ddddcb0c3e2a956707 (plain)
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
package database

import (
	"database/sql"
	"errors"
	"fmt"
	"time"

	"git.adyxax.org/adyxax/tfstated/pkg/model"
	"go.n16f.net/uuid"
)

func (db *DB) CreateSession(account *model.Account) (string, error) {
	var sessionId uuid.UUID
	if err := sessionId.Generate(uuid.V4); err != nil {
		return "", fmt.Errorf("failed to generate session id: %w", err)
	}
	if _, err := db.Exec(
		`INSERT INTO sessions(id, account_id, data)
		   VALUES (?, ?, ?);`,
		sessionId.String(),
		account.Id,
		"",
	); err != nil {
		return "", fmt.Errorf("failed insert new session in database: %w", err)
	}
	return sessionId.String(), nil
}

func (db *DB) LoadSessionById(id string) (*model.Session, error) {
	session := model.Session{
		Id: id,
	}
	var (
		created int64
		updated int64
	)
	err := db.QueryRow(
		`SELECT account_id,
                created,
                updated,
                data
           FROM sessions
           WHERE id = ?;`,
		id,
	).Scan(&session.AccountId,
		&created,
		&updated,
		&session.Data,
	)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to load session by id %s: %w", id, err)
	}
	session.Created = time.Unix(created, 0)
	session.Updated = time.Unix(updated, 0)
	return &session, nil
}

func (db *DB) TouchSession(sessionId string) error {
	now := time.Now().UTC()
	_, err := db.Exec(`UPDATE sessions SET updated = ? WHERE id = ?`, now.Unix(), sessionId)
	if err != nil {
		return fmt.Errorf("failed to touch updated for session %s: %w", sessionId, err)
	}
	return nil
}