zrok/controller/store/invite_tokens.go

54 lines
1.5 KiB
Go
Raw Normal View History

2023-01-10 19:26:22 +01:00
package store
import (
"fmt"
"strings"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type InviteToken struct {
Model
Token string
Deleted bool
2023-01-10 19:26:22 +01:00
}
func (str *Store) CreateInviteTokens(inviteTokens []*InviteToken, tx *sqlx.Tx) error {
sql := "insert into invite_tokens (token) values %s"
invs := make([]any, len(inviteTokens))
queries := make([]string, len(inviteTokens))
for i, inv := range inviteTokens {
invs[i] = inv.Token
queries[i] = fmt.Sprintf("($%d)", i+1)
}
stmt, err := tx.Prepare(fmt.Sprintf(sql, strings.Join(queries, ",")))
if err != nil {
2023-01-12 21:01:34 +01:00
return errors.Wrap(err, "error preparing invite_tokens insert statement")
2023-01-10 19:26:22 +01:00
}
if _, err := stmt.Exec(invs...); err != nil {
return errors.Wrap(err, "error executing invites_tokens insert statement")
}
return nil
}
2023-03-10 17:10:48 +01:00
func (str *Store) FindInviteTokenByToken(token string, tx *sqlx.Tx) (*InviteToken, error) {
2023-01-10 19:26:22 +01:00
inviteToken := &InviteToken{}
2023-03-10 17:10:48 +01:00
if err := tx.QueryRowx("select * from invite_tokens where token = $1 and not deleted", token).StructScan(inviteToken); err != nil {
2023-01-10 19:26:22 +01:00
return nil, errors.Wrap(err, "error getting unused invite_token")
}
return inviteToken, nil
}
func (str *Store) DeleteInviteToken(id int, tx *sqlx.Tx) error {
2023-03-10 17:10:48 +01:00
stmt, err := tx.Prepare("update invite_tokens set updated_at = current_timestamp, deleted = true where id = $1")
2023-01-10 19:26:22 +01:00
if err != nil {
return errors.Wrap(err, "error preparing invite_tokens delete statement")
}
_, err = stmt.Exec(id)
if err != nil {
return errors.Wrap(err, "error executing invite_tokens delete statement")
}
return nil
}