github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/database/accountStore.go (about)

     1  package database
     2  
     3  import (
     4  	"github.com/dhax/go-base/auth/jwt"
     5  	"github.com/dhax/go-base/auth/pwdless"
     6  	"github.com/dhax/go-base/models"
     7  	"github.com/go-pg/pg"
     8  )
     9  
    10  // AccountStore implements database operations for account management by user.
    11  type AccountStore struct {
    12  	db *pg.DB
    13  }
    14  
    15  // NewAccountStore returns an AccountStore.
    16  func NewAccountStore(db *pg.DB) *AccountStore {
    17  	return &AccountStore{
    18  		db: db,
    19  	}
    20  }
    21  
    22  // Get an account by ID.
    23  func (s *AccountStore) Get(id int) (*pwdless.Account, error) {
    24  	a := pwdless.Account{ID: id}
    25  	err := s.db.Model(&a).
    26  		Where("account.id = ?id").
    27  		Column("account.*", "Token").
    28  		First()
    29  	return &a, err
    30  }
    31  
    32  // Update an account.
    33  func (s *AccountStore) Update(a *pwdless.Account) error {
    34  	_, err := s.db.Model(a).
    35  		Column("email", "name").
    36  		WherePK().
    37  		Update()
    38  	return err
    39  }
    40  
    41  // Delete an account.
    42  func (s *AccountStore) Delete(a *pwdless.Account) error {
    43  	err := s.db.RunInTransaction(func(tx *pg.Tx) error {
    44  		if _, err := tx.Model(&jwt.Token{}).
    45  			Where("account_id = ?", a.ID).
    46  			Delete(); err != nil {
    47  			return err
    48  		}
    49  		if _, err := tx.Model(&models.Profile{}).
    50  			Where("account_id = ?", a.ID).
    51  			Delete(); err != nil {
    52  			return err
    53  		}
    54  		return tx.Delete(a)
    55  	})
    56  	return err
    57  }
    58  
    59  // UpdateToken updates a jwt refresh token.
    60  func (s *AccountStore) UpdateToken(t *jwt.Token) error {
    61  	_, err := s.db.Model(t).
    62  		Column("identifier").
    63  		WherePK().
    64  		Update()
    65  	return err
    66  }
    67  
    68  // DeleteToken deletes a jwt refresh token.
    69  func (s *AccountStore) DeleteToken(t *jwt.Token) error {
    70  	err := s.db.Delete(t)
    71  	return err
    72  }