.
This commit is contained in:
1 parent
173c01b01b
commit
5772a7d855
22 files changed
+731
-149
No files matched your search
@@ -0,0 +1,88 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"time"
|
||||
"database/sql"
|
||||
"encoding/pem"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
)
|
||||
|
||||
type BlindSignRequest struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
IssueID int64 `json:"issue_id"`
|
||||
Created time.Time `json:"created"`
|
||||
}
|
||||
|
||||
type BlindSignRequestModel struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
func (m BlindSignRequestModel) Insert(blind_sign *BlindSignRequest) error {
|
||||
query := `
|
||||
INSERT INTO blind_sign_requests (user_id, issue_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING created`
|
||||
|
||||
args := []interface{}{
|
||||
blind_sign.UserID,
|
||||
blind_sign.IssueID,
|
||||
}
|
||||
|
||||
return m.DB.QueryRow(query, args...).Scan(
|
||||
&blind_sign.Created,
|
||||
)
|
||||
}
|
||||
|
||||
func (m BlindSignRequestModel) BlindSign(issueID int64, blindedVoteBytes []byte) ([]byte, error) {
|
||||
if issueID < 1 {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
|
||||
query := `SELECT rsa_private_pem FROM issues WHERE id = $1`
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
var pemBytes []byte
|
||||
err := m.DB.QueryRowContext(ctx, query, issueID).Scan(&pemBytes)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, ErrRecordNotFound
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
key, err := parsePrivateKey(pemBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse private key: %w", err)
|
||||
}
|
||||
|
||||
m_ := new(big.Int).SetBytes(blindedVoteBytes)
|
||||
|
||||
// Validate range: m′ must be in [1, n-1]
|
||||
one := big.NewInt(1)
|
||||
if m_.Cmp(one) < 0 || m_.Cmp(key.N) >= 0 {
|
||||
return nil, ErrInvalidBlindedVote
|
||||
}
|
||||
|
||||
// s′ = m′^d mod n
|
||||
sig := new(big.Int).Exp(m_, key.D, key.N)
|
||||
|
||||
return sig.Bytes(), nil
|
||||
}
|
||||
|
||||
func parsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error) {
|
||||
block, _ := pem.Decode(pemBytes)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode PEM block")
|
||||
}
|
||||
return x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
}
|
||||
|
||||
+38
-27
@@ -10,13 +10,16 @@ import (
|
||||
)
|
||||
|
||||
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"`
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
StartTime time.Time `json:"start_time"`
|
||||
EndTime time.Time `json:"end_time"`
|
||||
N []byte `json:"-"`
|
||||
E int `json:"-"`
|
||||
PrivatePem []byte `json:"-"`
|
||||
Created time.Time `json:"created"`
|
||||
Version int32 `json:"version"`
|
||||
}
|
||||
|
||||
func ValidateIssue(v *validator.Validator, issue *Issue) {
|
||||
@@ -36,8 +39,8 @@ type IssueModel struct {
|
||||
|
||||
func (m IssueModel) Insert(issue *Issue) error {
|
||||
query := `
|
||||
INSERT INTO issues (title, description, start_time, end_time)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
INSERT INTO issues (title, description, start_time, end_time, rsa_n, rsa_e, rsa_private_pem)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id, created, version`
|
||||
|
||||
args := []interface{}{
|
||||
@@ -45,6 +48,9 @@ RETURNING id, created, version`
|
||||
issue.Description,
|
||||
issue.StartTime,
|
||||
issue.EndTime,
|
||||
issue.N,
|
||||
issue.E,
|
||||
issue.PrivatePem,
|
||||
}
|
||||
|
||||
return m.DB.QueryRow(query, args...).Scan(
|
||||
@@ -60,32 +66,26 @@ func (m IssueModel) Get(id int64) (*Issue, error) {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
|
||||
// Define the SQL query for retrieving the issue data.
|
||||
query :=`
|
||||
SELECT id, title, description, start_time, end_time, created, version
|
||||
query := `
|
||||
SELECT id, title, description, start_time, end_time, rsa_n, rsa_e, rsa_private_pem, 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.N,
|
||||
&issue.E,
|
||||
&issue.PrivatePem,
|
||||
&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):
|
||||
@@ -94,29 +94,37 @@ WHERE id = $1`
|
||||
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
|
||||
SET
|
||||
title = $1,
|
||||
description = $2,
|
||||
start_time = $3,
|
||||
end_time = $4,
|
||||
rsa_n = $5,
|
||||
rsa_e = $6,
|
||||
rsa_private_pem = $7,
|
||||
version = version + 1
|
||||
WHERE id = $8 AND version = $9
|
||||
RETURNING version`
|
||||
|
||||
// Create an args slice containing the values for the placeholder parameters.
|
||||
args := []interface{}{
|
||||
issue.Title,
|
||||
issue.Description,
|
||||
issue.StartTime,
|
||||
issue.EndTime,
|
||||
issue.N,
|
||||
issue.E,
|
||||
issue.PrivatePem,
|
||||
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 {
|
||||
@@ -170,7 +178,7 @@ func (m IssueModel) GetAll(title string, filters Filters) ([]*Issue, Metadata, e
|
||||
// Construct the SQL query to retrieve all issue records.
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
COUNT(*) OVER(), id, title, description, start_time, end_time, created, version
|
||||
COUNT(*) OVER(), id, title, description, start_time, end_time, rsa_n, rsa_e, rsa_private_pem, created, version
|
||||
FROM
|
||||
issues
|
||||
WHERE
|
||||
@@ -217,6 +225,9 @@ func (m IssueModel) GetAll(title string, filters Filters) ([]*Issue, Metadata, e
|
||||
&issue.Description,
|
||||
&issue.StartTime,
|
||||
&issue.EndTime,
|
||||
&issue.N,
|
||||
&issue.E,
|
||||
&issue.PrivatePem,
|
||||
&issue.Created,
|
||||
&issue.Version,
|
||||
)
|
||||
|
||||
+15
-12
@@ -6,24 +6,27 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrRecordNotFound = errors.New("record not found")
|
||||
ErrEditConflict = errors.New("edit conflict")
|
||||
ErrRecordNotFound = errors.New("record not found")
|
||||
ErrEditConflict = errors.New("edit conflict")
|
||||
ErrInvalidBlindedVote = errors.New("invalid blinded vote")
|
||||
)
|
||||
|
||||
type Models struct {
|
||||
Users UserModel
|
||||
UserIdentities UserIdentityModel
|
||||
Issues IssueModel
|
||||
Tokens TokenModel
|
||||
Permissions PermissionModel
|
||||
Users UserModel
|
||||
UserIdentities UserIdentityModel
|
||||
Issues IssueModel
|
||||
Tokens TokenModel
|
||||
Permissions PermissionModel
|
||||
BlindSignRequests BlindSignRequestModel
|
||||
}
|
||||
|
||||
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},
|
||||
Users: UserModel{DB: db},
|
||||
UserIdentities: UserIdentityModel{DB: db},
|
||||
Issues: IssueModel{DB: db},
|
||||
Tokens: TokenModel{DB: db},
|
||||
Permissions: PermissionModel{DB: db},
|
||||
BlindSignRequests: BlindSignRequestModel{DB: db},
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ 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)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
rows, err := m.DB.QueryContext(ctx, query, userID)
|
||||
@@ -62,7 +62,7 @@ func (m PermissionModel) AddForUser(userID int64, codes ...string) error {
|
||||
INSERT INTO users_permissions
|
||||
SELECT $1, permissions.id FROM permissions WHERE permissions.code = ANY($2)`
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
_, err := m.DB.ExecContext(ctx, query, userID, pq.Array(codes))
|
||||
return err
|
||||
|
||||
@@ -75,7 +75,7 @@ func (m TokenModel) Insert(token *Token) error {
|
||||
|
||||
args := []interface{}{token.Hash, token.UserID, token.UserIdentityID, token.Expiry, token.Scope}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.DB.ExecContext(ctx, query, args...)
|
||||
|
||||
@@ -90,7 +90,7 @@ type UserIdentityModel struct {
|
||||
// userIdentity.Password.hash,
|
||||
// }
|
||||
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
// defer cancel()
|
||||
|
||||
// err := m.DB.QueryRowContext(ctx, query, args...).Scan(&userIdentity.ID, &userIdentity.Version)
|
||||
@@ -214,7 +214,7 @@ AND tokens.expiry > $3`
|
||||
|
||||
var userIdentity UserIdentity
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := m.DB.QueryRowContext(ctx, query, args...).Scan(
|
||||
@@ -252,7 +252,7 @@ func (m UserIdentityModel) Update(user *UserIdentity) error {
|
||||
user.Version,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := m.DB.QueryRowContext(ctx, query, args...).Scan(&user.Version)
|
||||
|
||||
+28
-8
@@ -23,7 +23,7 @@ type User struct {
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Country string `json:"country"`
|
||||
Name string `json:"name"`
|
||||
AltName sql.NullString `json:"alt_name"`
|
||||
AltName *string `json:"alt_name"`
|
||||
DateOfBirth time.Time `json:"date_of_birth"`
|
||||
Address string `json:"address"`
|
||||
Created time.Time `json:"created"`
|
||||
@@ -60,8 +60,8 @@ func (m UserModel) ExecuteRegistrationTx(user *User, userIdentity *UserIdentity)
|
||||
defer tx.Rollback()
|
||||
|
||||
query := `
|
||||
INSERT INTO users (email, phone_number, country, name, alt_name, date_of_birth, address)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
INSERT INTO users (email, phone_number, country, name, alt_name, date_of_birth, address, activated)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, created, last_login, version`
|
||||
|
||||
args := []interface{}{
|
||||
@@ -72,6 +72,7 @@ RETURNING id, created, last_login, version`
|
||||
user.AltName,
|
||||
user.DateOfBirth,
|
||||
user.Address,
|
||||
user.Activated,
|
||||
}
|
||||
|
||||
err = tx.QueryRowContext(ctx, query, args...).Scan(&user.ID, &user.Created, &user.LastLogin, &user.Version)
|
||||
@@ -163,7 +164,7 @@ WHERE id = $1`
|
||||
|
||||
func (m UserModel) GetByEmail(email string) (*User, error) {
|
||||
query :=`
|
||||
SELECT id, email, phone, country, name, alt_name, date_of_birth, address, created, last_login, activated, version
|
||||
SELECT id, email, phone_number, country, name, alt_name, date_of_birth, address, created, last_login, activated, version
|
||||
FROM users
|
||||
WHERE email = $1`
|
||||
|
||||
@@ -205,7 +206,17 @@ func (m UserModel) GetForToken(tokenScope, tokenPlaintext string) (*User, error)
|
||||
|
||||
// Set up the SQL query.
|
||||
query :=`
|
||||
SELECT users.id, users.email, user.phone_number, user.country, users.name, users.date_of_birth, users.address, users.created, users.activated, users.version
|
||||
SELECT
|
||||
users.id,
|
||||
users.email,
|
||||
users.phone_number,
|
||||
users.country,
|
||||
users.name,
|
||||
users.date_of_birth,
|
||||
users.address,
|
||||
users.created,
|
||||
users.activated,
|
||||
users.version
|
||||
FROM users
|
||||
INNER JOIN tokens ON users.id = tokens.user_id
|
||||
WHERE tokens.hash = $1
|
||||
@@ -218,7 +229,7 @@ AND tokens.expiry > $3`
|
||||
// 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)
|
||||
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
|
||||
@@ -251,7 +262,16 @@ AND tokens.expiry > $3`
|
||||
func (m UserModel) Update(user *User) error {
|
||||
query := `
|
||||
UPDATE users
|
||||
SET email = $1, phone_number = $2, country = $3, name = $4, alt_name = $5, date_of_birth = $6, address = $7, activated = $8, version = version + 1
|
||||
SET
|
||||
email = $1,
|
||||
phone_number = $2,
|
||||
country = $3,
|
||||
name = $4,
|
||||
alt_name = $5,
|
||||
date_of_birth = $6,
|
||||
address = $7,
|
||||
activated = $8,
|
||||
version = version + 1
|
||||
WHERE id = $9 AND version = $10
|
||||
RETURNING version`
|
||||
|
||||
@@ -269,7 +289,7 @@ func (m UserModel) Update(user *User) error {
|
||||
user.Version,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := m.DB.QueryRowContext(ctx, query, args...).Scan(&user.Version)
|
||||
|
||||
+12
-39
@@ -1,26 +1,23 @@
|
||||
package jsonlog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
"time"
|
||||
"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.
|
||||
LevelInfo Level = iota
|
||||
LevelError
|
||||
LevelFatal
|
||||
LevelOff
|
||||
)
|
||||
|
||||
// Return a human-friendly string for the severity level.
|
||||
func (l Level) String() string {
|
||||
switch l {
|
||||
case LevelInfo:
|
||||
@@ -34,17 +31,12 @@ func (l Level) String() string {
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
@@ -52,9 +44,6 @@ func New(out io.Writer, minLevel Level) *Logger {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -65,18 +54,14 @@ func (l *Logger) PrintError(err error, properties map[string]string) {
|
||||
|
||||
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.
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// 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"`
|
||||
@@ -90,35 +75,23 @@ func (l *Logger) print(level Level, message string, properties map[string]string
|
||||
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)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ The DigitalePartei Team
|
||||
<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><a href="dpoe://activate?token={{.token}}">Click here to activate!</a></p>
|
||||
<p>Thanks,</p>
|
||||
<p>The DigitalePartei Team</p>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user