github.com/hzck/speedroute@v0.0.0-20201115191102-403b7d0e443f/model/account.go (about)

     1  package model
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"time"
     8  
     9  	"github.com/jackc/pgx/v4/pgxpool"
    10  )
    11  
    12  // Account contains all information regarding user accounts.
    13  type Account struct {
    14  	ID          int
    15  	Username    string
    16  	Password    string
    17  	Created     time.Time
    18  	LastUpdated time.Time
    19  }
    20  
    21  func (a *Account) String() string {
    22  	return fmt.Sprintf("ID=%d, Username=%s, Password=%s, Created=%s, LastUpdated=%s",
    23  		a.ID, a.Username, a.Password, a.Created.String(), a.LastUpdated.String())
    24  }
    25  
    26  // CreateAccount creates and stores a new account to the database.
    27  func (a *Account) CreateAccount(dbpool *pgxpool.Pool) error {
    28  	query := "INSERT INTO account (username, password, created, last_updated) VALUES ($1, $2, $3, $3)"
    29  	_, err := dbpool.Exec(context.Background(), query, a.Username, a.Password, time.Now())
    30  	if err != nil {
    31  		// Assume username already taken
    32  		log.Println(err)
    33  		return err
    34  	}
    35  	return nil
    36  }