2020-10-19 12:11:25 +01:00
|
|
|
// Copyright (C) 2020 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package storagenodedb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/zeebo/errs"
|
|
|
|
|
2020-11-09 15:22:30 +00:00
|
|
|
"storj.io/storj/storagenode/apikeys"
|
2020-10-19 12:11:25 +01:00
|
|
|
)
|
|
|
|
|
2020-11-09 15:22:30 +00:00
|
|
|
// ensures that secretDB implements apikeys.DB interface.
|
|
|
|
var _ apikeys.DB = (*secretDB)(nil)
|
2020-10-19 12:11:25 +01:00
|
|
|
|
|
|
|
// ErrSecret represents errors from the apikey database.
|
|
|
|
var ErrSecret = errs.Class("apikey db error")
|
|
|
|
|
|
|
|
// SecretDBName represents the database name.
|
|
|
|
const SecretDBName = "secret"
|
|
|
|
|
|
|
|
// secretDB works with node apikey DB.
|
|
|
|
type secretDB struct {
|
|
|
|
dbContainerImpl
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store stores apikey into database.
|
2020-11-09 15:22:30 +00:00
|
|
|
func (db *secretDB) Store(ctx context.Context, secret apikeys.APIKey) (err error) {
|
2020-10-19 12:11:25 +01:00
|
|
|
defer mon.Task()(&ctx)(&err)
|
|
|
|
|
|
|
|
query := `INSERT INTO secret (
|
|
|
|
token,
|
|
|
|
created_at
|
|
|
|
) VALUES(?,?)`
|
|
|
|
|
|
|
|
_, err = db.ExecContext(ctx, query,
|
|
|
|
secret.Secret[:],
|
|
|
|
secret.CreatedAt,
|
|
|
|
)
|
|
|
|
|
|
|
|
return ErrSecret.Wrap(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check checks if apikey exists in db by token.
|
2020-11-09 15:22:30 +00:00
|
|
|
func (db *secretDB) Check(ctx context.Context, token apikeys.Secret) (err error) {
|
2020-10-19 12:11:25 +01:00
|
|
|
defer mon.Task()(&ctx)(&err)
|
|
|
|
|
|
|
|
var bytes []uint8
|
|
|
|
var createdAt string
|
|
|
|
|
|
|
|
rowStub := db.QueryRowContext(ctx,
|
|
|
|
`SELECT token, created_at FROM secret WHERE token = ?`,
|
|
|
|
token[:],
|
|
|
|
)
|
|
|
|
|
|
|
|
err = rowStub.Scan(
|
|
|
|
&bytes,
|
|
|
|
&createdAt,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
2020-11-09 15:22:30 +00:00
|
|
|
return apikeys.ErrNoSecret.Wrap(err)
|
2020-10-19 12:11:25 +01:00
|
|
|
}
|
|
|
|
return ErrSecret.Wrap(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Revoke removes apikey from db.
|
2020-11-09 15:22:30 +00:00
|
|
|
func (db *secretDB) Revoke(ctx context.Context, secret apikeys.Secret) (err error) {
|
2020-10-19 12:11:25 +01:00
|
|
|
defer mon.Task()(&ctx)(&err)
|
|
|
|
|
|
|
|
query := `DELETE FROM secret WHERE token = ?`
|
|
|
|
|
|
|
|
_, err = db.ExecContext(ctx, query, secret[:])
|
|
|
|
|
|
|
|
return ErrSecret.Wrap(err)
|
|
|
|
}
|