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
}
+124
View File
@@ -0,0 +1,124 @@
package jsonlog
import (
"encoding/json"
"io"
"os"
"runtime/debug"
"sync"
"time"
)
// Define a Level type to represent the severity level for a log entry.
type Level int8
// Initialize constants which represent a specific severity level. We use the iota
// keyword as a shortcut to assign successive integer values to the constants.
const (
LevelInfo Level = iota // Has the value 0.
LevelError // Has the value 1.
LevelFatal // Has the value 2.
LevelOff // Has the value 3.
)
// Return a human-friendly string for the severity level.
func (l Level) String() string {
switch l {
case LevelInfo:
return "INFO"
case LevelError:
return "ERROR"
case LevelFatal:
return "FATAL"
default:
return ""
}
}
// Define a custom Logger type. This holds the output destination that the log entries
// will be written to, the minimum severity level that log entries will be written for,
// plus a mutex for coordinating the writes.
type Logger struct {
out io.Writer
minLevel Level
mu sync.Mutex
}
// Return a new Logger instance which writes log entries at or above a minimum severity
// level to a specific output destination.
func New(out io.Writer, minLevel Level) *Logger {
return &Logger{
out: out,
minLevel: minLevel,
}
}
// Declare some helper methods for writing log entries at the different levels. Notice
// that these all accept a map as the second parameter which can contain any arbitrary
// 'properties' that you want to appear in the log entry.
func (l *Logger) PrintInfo(message string, properties map[string]string) {
l.print(LevelInfo, message, properties)
}
func (l *Logger) PrintError(err error, properties map[string]string) {
l.print(LevelError, err.Error(), properties)
}
func (l *Logger) PrintFatal(err error, properties map[string]string) {
l.print(LevelFatal, err.Error(), properties)
os.Exit(1) // For entries at the FATAL level, we also terminate the application.
}
// Print is an internal method for writing the log entry.
func (l *Logger) print(level Level, message string, properties map[string]string) (int, error) {
// If the severity level of the log entry is below the minimum severity for the
// logger, then return with no further action.
if level < l.minLevel {
return 0, nil
}
// Declare an anonymous struct holding the data for the log entry.
aux := struct {
Level string `json:"level"`
Time string `json:"time"`
Message string `json:"message"`
Properties map[string]string `json:"properties,omitempty"`
Trace string `json:"trace,omitempty"`
}{
Level: level.String(),
Time: time.Now().UTC().Format(time.RFC3339),
Message: message,
Properties: properties,
}
// Include a stack trace for entries at the ERROR and FATAL levels.
if level >= LevelError {
aux.Trace = string(debug.Stack())
}
// Declare a line variable for holding the actual log entry text.
var line []byte
// Marshal the anonymous struct to JSON and store it in the line variable. If there
// was a problem creating the JSON, set the contents of the log entry to be that
// plain-text error message instead.
line, err := json.Marshal(aux)
if err != nil {
line = []byte(LevelError.String() + ": unable to marshal log message:" + err.Error())
}
// Lock the mutex so that no two writes to the output destination cannot happen
// concurrently. If we don't do this, it's possible that the text for two or more
// log entries will be intermingled in the output.
l.mu.Lock()
defer l.mu.Unlock()
// Write the log entry followed by a newline.
return l.out.Write(append(line, '\n'))
}
// We also implement a Write() method on our Logger type so that it satisfies the
// io.Writer interface. This writes a log entry at the ERROR level with no additional
// properties.
func (l *Logger) Write(message []byte) (n int, err error) {
return l.print(LevelError, string(message), nil)
}
+96
View File
@@ -0,0 +1,96 @@
package mailer
import (
"bytes"
"embed"
"html/template"
"log"
// "time"
"github.com/wneessen/go-mail"
)
//go:embed "templates"
var templateFS embed.FS
type Mailer struct {
dialer *mail.Client
sender string
}
func New(host string, port int, username, password, sender string) Mailer {
// Initialize a new mail.Dialer instance with the given SMTP server settings. We
// also configure this to use a 5-second timeout whenever we send an email.
dialer, err := mail.NewClient(host,
mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithTLSPortPolicy(mail.TLSMandatory),
mail.WithUsername(username), mail.WithPassword(password),
)
if err != nil {
log.Fatalf("failed to deliver mail: %s", err)
}
// dialer. = 5 * time.Second
// Return a Mailer instance containing the dialer and sender information.
return Mailer{
dialer: dialer,
sender: sender,
}
}
// Define a Send() method on the Mailer type. This takes the recipient email address
// as the first parameter, the name of the file containing the templates, and any
// dynamic data for the templates as an interface{} parameter.
func (m Mailer) Send(recipient, templateFile string, data interface{}) error {
// Use the ParseFS() method to parse the required template file from the embedded
// file system.
tmpl, err := template.New("email").ParseFS(templateFS, "templates/"+templateFile)
if err != nil {
return err
}
// Execute the named template "subject", passing in the dynamic data and storing the
// result in a bytes.Buffer variable.
subject := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(subject, "subject", data)
if err != nil {
return err
}
// Follow the same pattern to execute the "plainBody" template and store the result
// in the plainBody variable.
plainBody := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(plainBody, "plainBody", data)
if err != nil {
return err
}
// And likewise with the "htmlBody" template.
htmlBody := new(bytes.Buffer)
err = tmpl.ExecuteTemplate(htmlBody, "htmlBody", data)
if err != nil {
return err
}
// Use the mail.NewMessage() function to initialize a new mail.Message instance.
// Then we use the SetHeader() method to set the email recipient, sender and subject
// headers, the SetBody() method to set the plain-text body, and the AddAlternative()
// method to set the HTML body. It's important to note that AddAlternative() should
// always be called *after* SetBody().
msg := mail.NewMsg()
msg.SetAddrHeader("To", recipient)
msg.SetAddrHeader("From", m.sender)
msg.SetGenHeader("Subject", subject.String())
msg.SetBodyString("text/plain", plainBody.String())
msg.AddAlternativeString("text/html", htmlBody.String())
// Call the DialAndSend() method on the dialer, passing in the message to send. This
// opens a connection to the SMTP server, sends the message, then closes the
// connection. If there is a timeout, it will return a "dial tcp: i/o timeout"
// error.
err = m.dialer.DialAndSend(msg)
if err != nil {
return err
}
return nil
}
@@ -0,0 +1,35 @@
{{define "subject"}}Welcome to Digitale Partei Österreich!{{end}}
{{define "plainBody"}}
Hi,
Thanks for signing up for a Digitale Partei Österreich account. We're excited to have you on board!
For future reference, your user ID number is {{.ID}}.
Your activation token is {{.token}}
Thanks,
The DigitalePartei Team
{{end}}
{{define "htmlBody"}}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Hi,</p>
<p>Thanks for signing up for a Digitale Partei Österreich account. We're excited to have you on board!</p>
<p>For future reference, your user ID number is {{.ID}}.</p>
<p>Your activation token is {{.token}}</p>
<p>Thanks,</p>
<p>The DigitalePartei Team</p>
</body>
</html>
{{end}}
+61
View File
@@ -0,0 +1,61 @@
package validator
import (
"regexp"
)
// Declare a regular expression for sanity checking the format of email addresses (we'll
// use this later in the book). If you're interested, this regular expression pattern is
// taken from https://html.spec.whatwg.org/#valid-e-mail-address. Note: if you're
// reading this in PDF or EPUB format and cannot see the full pattern, please see the
// note further down the page.
var (
EmailRX = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
)
type Validator struct {
Errors map[string]string
}
func New() *Validator {
return &Validator{Errors: make(map[string]string)}
}
func (v *Validator) Valid() bool {
return len(v.Errors) == 0
}
func (v *Validator) AddError(key, message string) {
if _, exists := v.Errors[key]; !exists {
v.Errors[key] = message
}
}
func (v *Validator) Check(ok bool, key, message string) {
if !ok {
v.AddError(key, message)
}
}
func In(value string, list ...string) bool {
for i := range list {
if value == list[i] {
return true
}
}
return false
}
func Matches(value string, rx *regexp.Regexp) bool {
return rx.MatchString(value)
}
func Unique(values []string) bool {
uniqueValues := make(map[string]bool)
for _, value := range values {
uniqueValues[value] = true
}
return len(values) == len(uniqueValues)
}