This commit is contained in:
vfs committed 2026-04-08 07:51:15 +02:00
1 parent 943408255c
commit ffa5cd9cd7
38 files changed
+2938 -68

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
package data
type AuthProvider struct {
ID int64 `json:"id"`
Description string `json:"description"`
Active bool `json:"active"`
}
type AuthProviderID int64
const (
ProviderUnknown AuthProviderID = 0
ProviderLocal AuthProviderID = 1
ProviderIDAustria AuthProviderID = 2
)
+77
View File
@@ -0,0 +1,77 @@
package data
import (
"math"
"strings"
"party.at/party/internal/validator"
)
type Filters struct {
Page int
PageSize int
Sort string
SortSafelist []string
}
func (f Filters) sortColumn() string {
for _, safeValue := range f.SortSafelist {
if f.Sort == safeValue {
return strings.TrimPrefix(f.Sort, "-")
}
}
panic("unsafe sort parameter: " + f.Sort)
}
// Return the sort direction ("ASC" or "DESC") depending on the prefix character of the
// Sort field.
func (f Filters) sortDirection() string {
if strings.HasPrefix(f.Sort, "-") {
return "DESC"
}
return "ASC"
}
func (f Filters) limit() int {
return f.PageSize
}
func (f Filters) offset() int {
return (f.Page - 1) * f.PageSize
}
func ValidateFilters(v *validator.Validator, f Filters) {
// Check that the page and page_size parameters contain sensible values.
v.Check(f.Page > 0, "page", "must be greater than zero")
v.Check(f.Page <= 10_000_000, "page", "must be a maximum of 10 million")
v.Check(f.PageSize > 0, "page_size", "must be greater than zero")
v.Check(f.PageSize <= 100, "page_size", "must be a maximum of 100")
// Check that the sort parameter matches a value in the safelist.
v.Check(validator.In(f.Sort, f.SortSafelist...), "sort", "invalid sort value")
}
type Metadata struct {
CurrentPage int `json:"current_page,omitempty"`
PageSize int `json:"page_size,omitempty"`
FirstPage int `json:"first_page,omitempty"`
LastPage int `json:"last_page,omitempty"`
TotalRecords int `json:"total_records,omitempty"`
}
func calculateMetadata(totalRecords, page, pageSize int) Metadata {
if totalRecords == 0 {
// Note that we return an empty Metadata struct if there are no records.
return Metadata{}
}
return Metadata{
CurrentPage: page,
PageSize: pageSize,
FirstPage: 1,
LastPage: int(math.Ceil(float64(totalRecords) / float64(pageSize))),
TotalRecords: totalRecords,
}
}
+242
View File
@@ -0,0 +1,242 @@
package data
import (
"time"
"party.at/party/internal/validator"
"database/sql"
"errors"
"context"
"fmt"
)
type Issue struct {
ID int64 `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Created time.Time `json:"created"`
Version int32 `json:"version"`
}
func ValidateIssue(v *validator.Validator, issue *Issue) {
v.Check(issue.Title != "", "title", "must be provided")
v.Check(len(issue.Title) <= 500, "title", "must not be more than 500 bytes long")
v.Check(issue.Description != "", "description", "must be provided")
v.Check(len(issue.Description) <= 500, "description", "must not be greater than 500 bytes long")
// v.Check(issue.StartTime != "", "start_time", "must be provided")
// v.Check(len(issue.StartTime) <= 500, "start_time", "must not be more than 500 bytes long")
// v.Check(issue.EndTime != "", "end_time", "must be provided")
// v.Check(len(issue.EndTime) <= 500, "end_time", "must not be more than 500 bytes long")
}
type IssueModel struct {
DB *sql.DB
}
func (m IssueModel) Insert(issue *Issue) error {
query := `
INSERT INTO issues (title, description, start_time, end_time)
VALUES ($1, $2, $3, $4)
RETURNING id, created, version`
args := []interface{}{
issue.Title,
issue.Description,
issue.StartTime,
issue.EndTime,
}
return m.DB.QueryRow(query, args...).Scan(
&issue.ID,
&issue.Created,
&issue.Version,
)
}
// Add a placeholder method for fetching a specific record from the issues table.
func (m IssueModel) Get(id int64) (*Issue, error) {
if id < 1 {
return nil, ErrRecordNotFound
}
// Define the SQL query for retrieving the issue data.
query :=`
SELECT id, title, description, start_time, end_time, created, version
FROM issues
WHERE id = $1`
// Declare a Issue struct to hold the data returned by the query.
var issue Issue
// Execute the query using the QueryRow() method, passing in the provided id value
// as a placeholder parameter, and scan the response data into the fields of the
// Issue struct. Importantly, notice that we need to convert the scan target for the
// genres column using the pq.Array() adapter function again.
err := m.DB.QueryRow(query, id).Scan(
&issue.ID,
&issue.Title,
&issue.Description,
&issue.StartTime,
&issue.EndTime,
&issue.Created,
&issue.Version,
)
// Handle any errors. If there was no matching issue found, Scan() will return
// a sql.ErrNoRows error. We check for this and return our custom ErrRecordNotFound
// error instead.
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
// Otherwise, return a pointer to the Issue struct.
return &issue, nil
}
func (m IssueModel) Update(issue *Issue) error {
query := `
UPDATE issues
SET title = $1, description = $2, start_time = $3, end_time = $4, version = version + 1
WHERE id = $5 AND version = $6
RETURNING version`
// Create an args slice containing the values for the placeholder parameters.
args := []interface{}{
issue.Title,
issue.Description,
issue.StartTime,
issue.EndTime,
issue.ID,
issue.Version,
}
// Use the QueryRow() method to execute the query, passing in the args slice as a
// variadic parameter and scanning the new version value into the issue struct.
err := m.DB.QueryRow(query, args...).Scan(&issue.Version)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return ErrEditConflict
default:
return err
}
}
return nil
}
// Add a placeholder method for deleting a specific record from the issues table.
func (m IssueModel) Delete(id int64) error {
if id < 1 {
return ErrRecordNotFound
}
// Construct the SQL query to delete the record.
query := `
DELETE FROM issues
WHERE id = $1`
// Execute the SQL query using the Exec() method, passing in the id variable as
// the value for the placeholder parameter. The Exec() method returns a sql.Result
// object.
result, err := m.DB.Exec(query, id)
if err != nil {
return err
}
// Call the RowsAffected() method on the sql.Result object to get the number of rows
// affected by the query.
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
// If no rows were affected, we know that the issues table didn't contain a record
// with the provided ID at the moment we tried to delete it. In that case we
// return an ErrRecordNotFound error.
if rowsAffected == 0 {
return ErrRecordNotFound
}
return nil
}
func (m IssueModel) GetAll(title string, filters Filters) ([]*Issue, Metadata, error) {
// Construct the SQL query to retrieve all issue records.
query := fmt.Sprintf(`
SELECT
COUNT(*) OVER(), id, title, description, start_time, end_time, created, version
FROM
issues
WHERE
(to_tsvector('simple', title) @@ plainto_tsquery('simple', $1) OR $1 = '')
ORDER BY
%s %s, id ASC
LIMIT
$2
OFFSET
$3`,
filters.sortColumn(),
filters.sortDirection(),
)
// Create a context with a 3-second timeout.
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()
args := []interface{}{title, filters.limit(), filters.offset()}
rows, err := m.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, Metadata{}, err
}
// Importantly, defer a call to rows.Close() to ensure that the resultset is closed
// before GetAll() returns.
defer rows.Close()
totalRecords := 0
issues := []*Issue{}
// Use rows.Next to iterate through the rows in the resultset.
for rows.Next() {
// Initialize an empty Issue struct to hold the data for an individual issue.
var issue Issue
// Scan the values from the row into the Issue struct. Again, note that we're
// using the pq.Array() adapter on the genres field here.
err := rows.Scan(
&totalRecords,
&issue.ID,
&issue.Title,
&issue.Description,
&issue.StartTime,
&issue.EndTime,
&issue.Created,
&issue.Version,
)
if err != nil {
return nil, Metadata{}, err
}
// Add the Issue struct to the slice.
issues = append(issues, &issue)
}
// When the rows.Next() loop has finished, call rows.Err() to retrieve any error
// that was encountered during the iteration.
if err = rows.Err(); err != nil {
return nil, Metadata{}, err
}
metadata := calculateMetadata(totalRecords, filters.Page, filters.PageSize)
// If everything went OK, then return the slice of issues.
return issues, metadata, nil
}
+29
View File
@@ -0,0 +1,29 @@
package data
import (
"database/sql"
"errors"
)
var (
ErrRecordNotFound = errors.New("record not found")
ErrEditConflict = errors.New("edit conflict")
)
type Models struct {
Users UserModel
UserIdentities UserIdentityModel
Issues IssueModel
Tokens TokenModel
Permissions PermissionModel
}
func NewModels(db *sql.DB) Models {
return Models{
Users: UserModel{DB: db},
UserIdentities: UserIdentityModel{DB: db},
Issues: IssueModel{DB: db},
Tokens: TokenModel{DB: db},
Permissions: PermissionModel{DB: db},
}
}
+69
View File
@@ -0,0 +1,69 @@
package data
import (
"context"
"database/sql"
"time"
"github.com/lib/pq"
)
type Permissions []string
func (p Permissions) Include(code string) bool {
for i := range p {
if code == p[i] {
return true
}
}
return false
}
type PermissionModel struct {
DB *sql.DB
}
func (m PermissionModel) GetAllForUser(userID int64) (Permissions, error) {
query :=`
SELECT permissions.code
FROM permissions
INNER JOIN users_permissions ON users_permissions.permission_id = permissions.id
INNER JOIN users ON users_permissions.user_id = users.id
WHERE users.id = $1`
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
rows, err := m.DB.QueryContext(ctx, query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var permissions Permissions
for rows.Next() {
var permission string
err := rows.Scan(&permission)
if err != nil {
return nil, err
}
permissions = append(permissions, permission)
}
if err = rows.Err(); err != nil {
return nil, err
}
return permissions, nil
}
func (m PermissionModel) AddForUser(userID int64, codes ...string) error {
query :=`
INSERT INTO users_permissions
SELECT $1, permissions.id FROM permissions WHERE permissions.code = ANY($2)`
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, err := m.DB.ExecContext(ctx, query, userID, pq.Array(codes))
return err
}
+95
View File
@@ -0,0 +1,95 @@
package data
import (
"crypto/rand"
"crypto/sha256"
"encoding/base32"
"time"
"context"
"database/sql"
"party.at/party/internal/validator"
)
const (
ScopeActivation = "activation"
ScopeAuthentication = "authentication"
)
type Token struct {
Plaintext string `json:"token"`
Hash []byte `json:"-"`
UserID int64 `json:"-"`
UserIdentityID int64 `json:"-"`
Expiry time.Time `json:"expiry"`
Scope string `json:"-"`
}
func generateToken(userID int64, userIdentityID int64, ttl time.Duration, scope string) (*Token, error) {
token := &Token{
UserID: userID,
UserIdentityID: userIdentityID,
Expiry: time.Now().Add(ttl),
Scope: scope,
}
// Initialize a zero-valued byte slice with a length of 16 bytes.
randomBytes := make([]byte, 16)
_, err := rand.Read(randomBytes)
if err != nil {
return nil, err
}
token.Plaintext = base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes)
hash := sha256.Sum256([]byte(token.Plaintext))
token.Hash = hash[:]
return token, nil
}
func ValidateTokenPlaintext(v *validator.Validator, tokenPlaintext string) {
v.Check(tokenPlaintext != "", "token", "must be provided")
v.Check(len(tokenPlaintext) == 26, "token", "must be 26 bytes long")
}
type TokenModel struct {
DB *sql.DB
}
func (m TokenModel) New(userID int64, userIdentityID int64, ttl time.Duration, scope string) (*Token, error) {
token, err := generateToken(userID, userIdentityID, ttl, scope)
if err != nil {
return nil, err
}
err = m.Insert(token)
return token, err
}
func (m TokenModel) Insert(token *Token) error {
query :=`
INSERT INTO tokens (hash, user_id, user_identity_id, expiry, scope)
VALUES ($1, $2, $3, $4, $5)`
args := []interface{}{token.Hash, token.UserID, token.UserIdentityID, token.Expiry, token.Scope}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, err := m.DB.ExecContext(ctx, query, args...)
return err
}
func (m TokenModel) DeleteAllForUser(scope string, userID int64) error {
query :=`
DELETE FROM tokens
WHERE scope = $1 AND user_id = $2`
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()
_, err := m.DB.ExecContext(ctx, query, scope, userID)
return err
}
+306
View File
@@ -0,0 +1,306 @@
package data
import (
"golang.org/x/crypto/bcrypt"
"errors"
"party.at/party/internal/validator"
"database/sql"
"context"
"time"
"crypto/sha256"
)
type UserIdentity struct {
ID int64 `json:"id"`
ProviderID int64 `json:"provider_id"`
UserID int64 `json:"user_id"`
ProviderUserID string `json:"provider_user_id"`
Password password `json:"-"`
Version int32 `json:"version"`
}
type password struct {
plaintext *string
hash []byte
}
func (p *password) Set(plaintextPassword string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(plaintextPassword), 12)
if err != nil {
return err
}
p.plaintext = &plaintextPassword
p.hash = hash
return nil
}
func (p *password) Matches(plaintextPassword string) (bool, error) {
err := bcrypt.CompareHashAndPassword(p.hash, []byte(plaintextPassword))
if err != nil {
switch {
case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
return false, nil
default:
return false, err
}
}
return true, nil
}
func ValidatePasswordPlaintext(v *validator.Validator, password string) {
v.Check(password != "", "password", "must be provided")
v.Check(len(password) >= 8, "password", "must be at least 8 bytes long")
v.Check(len(password) <= 72, "password", "must not be more than 72 bytes long")
}
func ValidateUserIdentity(v *validator.Validator, userIdentity *UserIdentity) {
v.Check(userIdentity.ProviderID == int64(ProviderLocal), "provider_id", "must be 1");
if userIdentity.ProviderID == int64(ProviderLocal) {
v.Check(userIdentity.ProviderUserID != "", "username", "must be provided")
v.Check(len(userIdentity.ProviderUserID) <= 500, "username", "must not be more than 500 bytes long")
}
if userIdentity.Password.plaintext != nil {
ValidatePasswordPlaintext(v,
*userIdentity.Password.plaintext)
}
if userIdentity.Password.hash == nil {
panic("missing password hash for user")
}
}
type UserIdentityModel struct {
DB *sql.DB
}
// func (m UserIdentityModel) Insert(userIdentity *UserIdentity) error {
// query := `
// INSERT INTO user_identities (provider_id, user_id, provider_user, password)
// VALUES ($1, $2, $3, $4)
// RETURNING id, version`
// args := []interface{}{
// userIdentity.ProviderID,
// userIdentity.UserID,
// userIdentity.ProviderUserID,
// userIdentity.Password.hash,
// }
// ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// defer cancel()
// err := m.DB.QueryRowContext(ctx, query, args...).Scan(&userIdentity.ID, &userIdentity.Version)
// if err != nil {
// switch {
// case err.Error() ==
// `pq: duplicate key value violates unique constraint "users_email_key"`:
// return ErrDuplicateEmail
// default:
// return err
// }
// }
// return nil
// }
func (m UserIdentityModel) Get(id int64) (*UserIdentity, error) {
if id < 1 {
return nil, ErrRecordNotFound
}
query :=`
SELECT id, provider_id, user_id, provider_user, password, version
FROM user_identities
WHERE id = $1`
// Declare a User struct to hold the data returned by the query.
var userIdentity UserIdentity
// Execute the query using the QueryRow() method, passing in the provided id value
// as a placeholder parameter, and scan the response data into the fields of the
// User struct. Importantly, notice that we need to convert the scan target for the
// genres column using the pq.Array() adapter function again.
err := m.DB.QueryRow(query, id).Scan(
&userIdentity.ID,
&userIdentity.ProviderID,
&userIdentity.UserID,
&userIdentity.ProviderUserID,
&userIdentity.Password,
&userIdentity.Version,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
// Otherwise, return a pointer to the User struct.
return &userIdentity, nil
}
func (m UserIdentityModel) GetByUser(user_id int64) ([]*UserIdentity, error) {
if user_id < 1 {
return nil, ErrRecordNotFound
}
query :=`
SELECT identity.id, identity.provider_id, identity.user_id, identity.provider_user_id, identity.password, identity.version
FROM user_identities identity
JOIN users u on identity.user_id = u.id
WHERE u.id = $1`
// Execute the query using the QueryRow() method, passing in the provided id value
// as a placeholder parameter, and scan the response data into the fields of the
// User struct. Importantly, notice that we need to convert the scan target for the
// genres column using the pq.Array() adapter function again.
rows, err := m.DB.Query(query, user_id)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
defer rows.Close()
var identities []*UserIdentity
for rows.Next() {
var userIdentity UserIdentity
err := rows.Scan(
&userIdentity.ID,
&userIdentity.ProviderID,
&userIdentity.UserID,
&userIdentity.ProviderUserID,
&userIdentity.Password.hash,
&userIdentity.Version,
)
if err != nil {
return nil, err
}
identities = append(identities, &userIdentity)
}
if len(identities) == 0 {
return nil, ErrRecordNotFound
}
// Otherwise, return a pointer to the User struct.
return identities, nil
}
func (m UserIdentityModel) GetForToken(tokenScope, tokenPlaintext string) (*UserIdentity, error) {
tokenHash := sha256.Sum256([]byte(tokenPlaintext))
query := `
SELECT ui.id, ui.provider_id, ui.user_id, ui.provider_user_id, ui.password, ui.version
FROM user_identities ui
INNER JOIN tokens ON ui.id = tokens.user_identity_id
WHERE tokens.hash = $1
AND tokens.scope = $2
AND tokens.expiry > $3`
args := []interface{}{tokenHash[:], tokenScope, time.Now()}
var userIdentity UserIdentity
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := m.DB.QueryRowContext(ctx, query, args...).Scan(
&userIdentity.ID,
&userIdentity.ProviderID,
&userIdentity.UserID,
&userIdentity.ProviderUserID,
&userIdentity.Password.hash,
&userIdentity.Version,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
return &userIdentity, nil
}
func (m UserIdentityModel) Update(user *UserIdentity) error {
query := `
UPDATE user_identities
SET provider_user_id = $1, password = $2, version = version + 1
WHERE id = $3 AND version = $4
RETURNING version`
// Create an args slice containing the values for the placeholder parameters.
args := []interface{}{
user.ProviderUserID,
user.Password.hash,
user.ID,
user.Version,
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := m.DB.QueryRowContext(ctx, query, args...).Scan(&user.Version)
if err != nil {
switch {
case err.Error() == `pq: duplicate key value violates unique constraint "users_email_key"`:
return ErrDuplicateEmail
case errors.Is(err, sql.ErrNoRows):
return ErrEditConflict
default:
return err
}
}
return nil
}
func (m UserIdentityModel) Delete(id int64) error {
if id < 1 {
return ErrRecordNotFound
}
// Construct the SQL query to delete the record.
query := `
DELETE FROM user_identities
WHERE id = $1`
// Execute the SQL query using the Exec() method, passing in the id variable as
// the value for the placeholder parameter. The Exec() method returns a sql.Result
// object.
result, err := m.DB.Exec(query, id)
if err != nil {
return err
}
// Call the RowsAffected() method on the sql.Result object to get the number of rows
// affected by the query.
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
// If no rows were affected, we know that the issues table didn't contain a record
// with the provided ID at the moment we tried to delete it. In that case we
// return an ErrRecordNotFound error.
if rowsAffected == 0 {
return ErrRecordNotFound
}
return nil
}
+329
View File
@@ -0,0 +1,329 @@
package data
import (
"context"
"time"
"party.at/party/internal/validator"
"database/sql"
"github.com/lib/pq"
"errors"
"crypto/sha256"
)
var (
ErrDuplicateEmail = errors.New("duplicate email")
ErrDuplicateUser = errors.New("duplicate username")
)
var AnonymousUser = &User{}
type User struct {
ID int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
AltName sql.NullString `json:"alt_name"`
Created time.Time `json:"created"`
LastLogin time.Time `json:"last_login"`
Activated bool `json:"activated"`
Version int32 `json:"-"`
}
func (u *User) IsAnonymous() bool {
return u == AnonymousUser
}
func ValidateEmail(v *validator.Validator, email string) {
v.Check(email != "", "email", "must be provided")
v.Check(validator.Matches(email, validator.EmailRX), "email" , "must be a valid email address")
}
func ValidateUser(v *validator.Validator, user *User) {
ValidateEmail(v, user.Email)
}
type UserModel struct {
DB *sql.DB
}
func (m UserModel) ExecuteRegistrationTx(user *User, userIdentity *UserIdentity) error {
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
defer cancel()
tx, err := m.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
query := `
INSERT INTO users (email, name, alt_name)
VALUES ($1, $2, $3)
RETURNING id, created, last_login, version`
args := []interface{}{
user.Email,
user.Name,
user.AltName,
}
err = tx.QueryRowContext(ctx, query, args...).Scan(&user.ID, &user.Created, &user.LastLogin, &user.Version)
if pgErr, ok := err.(*pq.Error); ok {
if pgErr.Code == "23505" {
if pgErr.Constraint == "users_email_key" {
return ErrDuplicateEmail
}
}
}
if err != nil {
return err
}
userIdentity.UserID = user.ID
// Insert Identity
query = `
INSERT INTO user_identities (provider_id, user_id, provider_user_id, password)
VALUES ($1, $2, $3, $4)
RETURNING id, version`
args = []interface{}{
userIdentity.ProviderID,
userIdentity.UserID,
userIdentity.ProviderUserID,
userIdentity.Password.hash,
}
err = tx.QueryRowContext(ctx, query, args...).Scan(&userIdentity.ID, &userIdentity.Version)
if pgErr, ok := err.(*pq.Error); ok {
if pgErr.Code == "23505" {
if pgErr.Constraint == "user_identities_provider_id_provider_user_id_key" {
return ErrDuplicateUser
}
}
}
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
// func (m UserModel) Insert(user *User) error {
// query := `
// INSERT INTO users (email, name, alt_name, activated)
// VALUES ($1, $2, $3, $4)
// RETURNING id, created, last_login, version`
// args := []interface{}{
// user.Email,
// user.Name,
// user.AltName,
// user.Activated,
// }
// ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// defer cancel()
// err := m.DB.QueryRowContext(ctx, query, args...).Scan(&user.ID, &user.Created, &user.LastLogin, &user.Version)
// if err != nil {
// switch {
// case err.Error() ==
// `pq: duplicate key value violates unique constraint "users_email_key"`:
// return ErrDuplicateEmail
// default:
// return err
// }
// }
// return nil
// }
func (m UserModel) Get(id int64) (*User, error) {
if id < 1 {
return nil, ErrRecordNotFound
}
// Define the SQL query for retrieving the issue data.
query :=`
SELECT id, email, name, alt_name, created, last_login, activated, version
FROM users
WHERE id = $1`
// Declare a User struct to hold the data returned by the query.
var user User
err := m.DB.QueryRow(query, id).Scan(
&user.ID,
&user.Email,
&user.Name,
&user.AltName,
&user.Created,
&user.LastLogin,
&user.Activated,
&user.Version,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
return &user, nil
}
func (m UserModel) GetByEmail(email string) (*User, error) {
query :=`
SELECT id, email, name, alt_name, created, last_login, activated, version
FROM users
WHERE email = $1`
var user User
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()
err := m.DB.QueryRowContext(ctx, query, email).Scan(
&user.ID,
&user.Email,
&user.Name,
&user.AltName,
&user.Created,
&user.LastLogin,
&user.Activated,
&user.Version,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
return &user, nil
}
func (m UserModel) GetForToken(tokenScope, tokenPlaintext string) (*User, error) {
// Calculate the SHA-256 hash of the plaintext token provided by the client.
// Remember that this returns a byte *array* with length 32, not a slice.
tokenHash := sha256.Sum256([]byte(tokenPlaintext))
// Set up the SQL query.
query :=`
SELECT users.id, users.created, users.name, users.email, users.activated, users.version
FROM users
INNER JOIN tokens ON users.id = tokens.user_id
WHERE tokens.hash = $1
AND tokens.scope = $2
AND tokens.expiry > $3`
// Create a slice containing the query arguments. Notice how we use the [:] operator
// to get a slice containing the token hash, rather than passing in the array (which
// is not supported by the pq driver), and that we pass the current time as the
// value to check against the token expiry.
args := []interface{}{tokenHash[:], tokenScope, time.Now()}
var user User
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Execute the query, scanning the return values into a User struct. If no matching
// record is found we return an ErrRecordNotFound error.
err := m.DB.QueryRowContext(ctx, query, args...).Scan(
&user.ID,
&user.Created,
&user.Name,
&user.Email,
&user.Activated,
&user.Version,
)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrRecordNotFound
default:
return nil, err
}
}
// Return the matching user.
return &user, nil
}
func (m UserModel) Update(user *User) error {
query := `
UPDATE users
SET email = $1, name = $2, alt_name = $3, activated = $4, version = version + 1
WHERE id = $5 AND version = $6
RETURNING version`
// Create an args slice containing the values for the placeholder parameters.
args := []interface{}{
user.Email,
user.Name,
user.AltName,
user.Activated,
user.ID,
user.Version,
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := m.DB.QueryRowContext(ctx, query, args...).Scan(&user.Version)
if err != nil {
switch {
case err.Error() == `pq: duplicate key value violates unique constraint "users_email_key"`:
return ErrDuplicateEmail
case errors.Is(err, sql.ErrNoRows):
return ErrEditConflict
default:
return err
}
}
return nil
}
func (m UserModel) Delete(id int64) error {
if id < 1 {
return ErrRecordNotFound
}
// Construct the SQL query to delete the record.
query := `
DELETE FROM users
WHERE id = $1`
// Execute the SQL query using the Exec() method, passing in the id variable as
// the value for the placeholder parameter. The Exec() method returns a sql.Result
// object.
result, err := m.DB.Exec(query, id)
if err != nil {
return err
}
// Call the RowsAffected() method on the sql.Result object to get the number of rows
// affected by the query.
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
// If no rows were affected, we know that the issues table didn't contain a record
// with the provided ID at the moment we tried to delete it. In that case we
// return an ErrRecordNotFound error.
if rowsAffected == 0 {
return ErrRecordNotFound
}
return nil
}