package storage import ( "context" "database/sql" "errors" "fmt" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/devices" ) type deviceRow struct { bun.BaseModel `bun:"table:device_passwords"` ID int64 `bun:"id,pk,autoincrement"` UserID int64 `bun:"user_id,notnull"` Name string `bun:"name,notnull"` KeyHash string `bun:"key_hash,notnull"` Sealed []byte `bun:"sealed,notnull"` CreatedAt int64 `bun:"created_at,notnull"` LastUsedAt *int64 `bun:"last_used_at"` } func (r deviceRow) device() devices.Row { out := devices.Row{ID: r.ID, UserID: r.UserID, Name: r.Name, KeyHash: r.KeyHash, Sealed: r.Sealed, CreatedAt: time.Unix(r.CreatedAt, 0)} if r.LastUsedAt != nil { t := time.Unix(*r.LastUsedAt, 0) out.LastUsedAt = &t } return out } // DevicesRepo keeps the passwords of apps and devices. It implements devices.Store. type DevicesRepo struct{ db *bun.DB } // NewDevicesRepo builds a DevicesRepo. func NewDevicesRepo(db *bun.DB) *DevicesRepo { return &DevicesRepo{db: db} } // Create stores a device and returns it with its id. func (r *DevicesRepo) Create(ctx context.Context, d devices.Row) (devices.Row, error) { row := &deviceRow{UserID: d.UserID, Name: d.Name, KeyHash: d.KeyHash, Sealed: d.Sealed, CreatedAt: d.CreatedAt.Unix()} if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil { return devices.Row{}, fmt.Errorf("insert device: %w", err) } return row.device(), nil } // List returns the devices of a person. func (r *DevicesRepo) List(ctx context.Context, userID int64) ([]devices.Row, error) { var rows []deviceRow if err := r.db.NewSelect().Model(&rows).Where("user_id = ?", userID).Order("id DESC").Scan(ctx); err != nil { return nil, fmt.Errorf("select devices: %w", err) } out := make([]devices.Row, len(rows)) for i, row := range rows { out[i] = row.device() } return out, nil } // Delete removes a device of a person, with devices.ErrNotFound when there is none. func (r *DevicesRepo) Delete(ctx context.Context, userID, id int64) error { res, err := r.db.NewDelete().Model((*deviceRow)(nil)).Where("id = ? AND user_id = ?", id, userID).Exec(ctx) if err != nil { return fmt.Errorf("delete device: %w", err) } if n, _ := res.RowsAffected(); n == 0 { return devices.ErrNotFound } return nil } // deviceWithEmail is a device with the address of its person. type deviceWithEmail struct { deviceRow `bun:",extend"` Email string `bun:"email"` } func (r deviceWithEmail) device() devices.Row { out := r.deviceRow.device() out.Email = r.Email return out } // ByKeyHash finds a device by the hash of its secret, with the address of its person, or devices.ErrNotFound. func (r *DevicesRepo) ByKeyHash(ctx context.Context, hash string) (devices.Row, error) { var row deviceWithEmail err := r.db.NewSelect(). TableExpr("device_passwords AS d"). ColumnExpr("d.id, d.user_id, d.name, d.key_hash, d.sealed, d.created_at, d.last_used_at, u.email"). Join("JOIN users AS u ON u.id = d.user_id"). Where("d.key_hash = ?", hash). Limit(1).Scan(ctx, &row) if errors.Is(err, sql.ErrNoRows) { return devices.Row{}, devices.ErrNotFound } if err != nil { return devices.Row{}, fmt.Errorf("find device by key: %w", err) } return row.device(), nil } // ByEmail returns the devices of the person with that address (lower case), with the address. func (r *DevicesRepo) ByEmail(ctx context.Context, email string) ([]devices.Row, error) { var rows []deviceWithEmail err := r.db.NewSelect(). TableExpr("device_passwords AS d"). ColumnExpr("d.id, d.user_id, d.name, d.key_hash, d.sealed, d.created_at, d.last_used_at, u.email"). Join("JOIN users AS u ON u.id = d.user_id"). Where("LOWER(u.email) = ?", email). Order("d.id"). Scan(ctx, &rows) if err != nil { return nil, fmt.Errorf("find devices by address: %w", err) } out := make([]devices.Row, len(rows)) for i, row := range rows { out[i] = row.device() } return out, nil } // Touch notes when a device was last used. func (r *DevicesRepo) Touch(ctx context.Context, id int64, at time.Time) error { if _, err := r.db.NewUpdate().Model((*deviceRow)(nil)).Set("last_used_at = ?", at.Unix()).Where("id = ?", id).Exec(ctx); err != nil { return fmt.Errorf("touch device: %w", err) } return nil }