refactoring psql

This commit is contained in:
sbouaram 2023-04-27 09:18:52 +02:00
parent d56343f167
commit d196373abc
2 changed files with 120 additions and 72 deletions

View File

@ -6,7 +6,6 @@ import (
"fmt" "fmt"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"github.com/spf13/viper" "github.com/spf13/viper"
"regexp"
"strconv" "strconv"
"strings" "strings"
) )
@ -45,62 +44,69 @@ func (psql PostgresqlStorage) GetAccount(id string) (*Account, error) {
data, metadata, emailValidation, phoneValidation []byte data, metadata, emailValidation, phoneValidation []byte
) )
account := &Account{} account := &Account{}
if isUUIDv4(id) { stmtAccounts, err := psql.DbConnection.Prepare("" +
stmtAccounts, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata FROM accounts WHERE id = $1") "SELECT id, namespace, data, " +
if err != nil { "metadata, username, password, email, email_validation, " +
return nil, fmt.Errorf("psql connection failed") "phone_number, phone_number_validation FROM accounts a JOIN " +
} "account_auth auth ON id = account_id WHERE id = $1")
defer stmtAccounts.Close() if err != nil {
err = stmtAccounts.QueryRow(id).Scan(&account.ID, &account.Namespace, &data, &metadata) return nil, fmt.Errorf("psql connection failed")
if err != nil { }
return nil, fmt.Errorf("psql select account query failed") defer stmtAccounts.Close()
} err = stmtAccounts.QueryRow(id).Scan(&account.ID,
err = json.Unmarshal(data, &account.Data) &account.Namespace,
if err != nil { &data,
return nil, err &metadata,
} &account.Authentication.Local.Username,
err = json.Unmarshal(metadata, &account.Metadata) &account.Authentication.Local.Password,
if err != nil { &account.Authentication.Local.Email,
return nil, err &emailValidation,
} &account.Authentication.Local.PhoneNumber,
stmtAccount_auth, err := psql.DbConnection.Prepare("SELECT username, password, email, email_validation, phone_number, phone_number_validation FROM account_auth WHERE account_id= $1") &phoneValidation)
if err != nil { if err != nil {
return nil, fmt.Errorf("psql connection failed") return nil, fmt.Errorf("psql select account query failed")
} }
defer stmtAccount_auth.Close() err = json.Unmarshal(data, &account.Data)
err = stmtAccount_auth.QueryRow(id).Scan(&account.Authentication.Local.Username, if err != nil {
&account.Authentication.Local.Password, return nil, err
&account.Authentication.Local.Email, }
&emailValidation, err = json.Unmarshal(metadata, &account.Metadata)
&account.Authentication.Local.PhoneNumber, if err != nil {
&phoneValidation) return nil, err
if err != nil { }
return nil, fmt.Errorf("psql select account auth query failed") err = json.Unmarshal(emailValidation, &account.Authentication.Local.EmailValidation)
} if err != nil {
err = json.Unmarshal(emailValidation, &account.Authentication.Local.EmailValidation) return nil, err
if err != nil { }
return nil, err err = json.Unmarshal(phoneValidation, &account.Authentication.Local.PhoneNumberValidation)
} if err != nil {
err = json.Unmarshal(phoneValidation, &account.Authentication.Local.PhoneNumberValidation) return nil, err
if err != nil {
return nil, err
}
} }
return account, nil return account, nil
} }
func (psql PostgresqlStorage) LocalAuthentication(namespace string, username string, email string, phone_number string) (*Account, error) { func (psql PostgresqlStorage) LocalAuthentication(namespace string, username string, email string,
phone_number string) (*Account, error) {
account := &Account{} account := &Account{}
var ( var (
data, metadata, emailValidation, phoneValidation []byte data, metadata, emailValidation, phoneValidation []byte
) )
if username != "" { if username != "" {
usernameStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata, username, password, email, email_validation, phone_number, phone_number_validation FROM accounts INNER JOIN account_auth ON accounts.id = account_auth.account_id WHERE namespace = $1 AND username = $2;") usernameStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata, username, " +
"password, email, email_validation, phone_number, phone_number_validation " +
"FROM accounts INNER JOIN account_auth ON accounts.id = account_auth.account_id WHERE " +
"namespace = $1 AND username = $2;")
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = usernameStmt.QueryRow(namespace, username).Scan(&account.ID, &account.Namespace, &data, &metadata, &account.Authentication.Local.Username, err = usernameStmt.QueryRow(namespace, username).Scan(
&account.Authentication.Local.Password, &account.Authentication.Local.Email, &emailValidation, &account.Authentication.Local.PhoneNumber, &phoneValidation) &account.ID,
&account.Namespace, &data, &metadata,
&account.Authentication.Local.Username,
&account.Authentication.Local.Password,
&account.Authentication.Local.Email,
&emailValidation, &account.Authentication.Local.PhoneNumber,
&phoneValidation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -123,12 +129,22 @@ func (psql PostgresqlStorage) LocalAuthentication(namespace string, username str
return account, nil return account, nil
} else if email != "" { } else if email != "" {
account.Authentication.Local.Email = email account.Authentication.Local.Email = email
emailStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata, username, password, email_validation, phone_number, phone_number_validation FROM accounts INNER JOIN account_auth ON accounts.id = account_auth.account_id WHERE namespace = $1 AND email = $2;") emailStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata, username, " +
"password, email_validation, phone_number, phone_number_validation " +
"FROM accounts INNER JOIN account_auth ON " +
"accounts.id = account_auth.account_id WHERE namespace = $1 AND email = $2;")
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = emailStmt.QueryRow(namespace, email).Scan(&account.ID, &account.Namespace, &data, &metadata, &account.Authentication.Local.Username, err = emailStmt.QueryRow(namespace, email).Scan(
&account.Authentication.Local.Password, &emailValidation, &account.Authentication.Local.PhoneNumber, &phoneValidation) &account.ID,
&account.Namespace,
&data, &metadata,
&account.Authentication.Local.Username,
&account.Authentication.Local.Password,
&emailValidation,
&account.Authentication.Local.PhoneNumber,
&phoneValidation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -151,12 +167,23 @@ func (psql PostgresqlStorage) LocalAuthentication(namespace string, username str
return account, nil return account, nil
} else if phone_number != "" { } else if phone_number != "" {
account.Authentication.Local.PhoneNumber = phone_number account.Authentication.Local.PhoneNumber = phone_number
phoneStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, data, metadata, username, password, email, email_validation, phone_number_validation FROM accounts INNER JOIN account_auth ON accounts.id = account_auth.account_id WHERE namespace = $1 AND phone_number = $2;") phoneStmt, err := psql.DbConnection.Prepare("SELECT id, namespace, " +
"data, metadata, username, password, email, " +
"email_validation, phone_number_validation FROM accounts " +
"INNER JOIN account_auth ON accounts.id = account_auth.account_id WHERE " +
"namespace = $1 AND phone_number = $2;")
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = phoneStmt.QueryRow(namespace, phone_number).Scan(&account.ID, &account.Namespace, &data, &metadata, &account.Authentication.Local.Username, err = phoneStmt.QueryRow(namespace, phone_number).Scan(&account.ID,
&account.Authentication.Local.Password, &account.Authentication.Local.Email, &emailValidation, &phoneValidation) &account.Namespace,
&data,
&metadata,
&account.Authentication.Local.Username,
&account.Authentication.Local.Password,
&account.Authentication.Local.Email,
&emailValidation,
&phoneValidation)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -178,7 +205,7 @@ func (psql PostgresqlStorage) LocalAuthentication(namespace string, username str
} }
return account, nil return account, nil
} }
return account, nil return nil, fmt.Errorf("localauthentication func error PSQL")
} }
func (psql PostgresqlStorage) GetAccounts(namespaces []string) ([]Account, error) { func (psql PostgresqlStorage) GetAccounts(namespaces []string) ([]Account, error) {
@ -308,7 +335,8 @@ func (psql PostgresqlStorage) GetAccountsByIds(accountids []string) ([]Account,
} }
func (psql PostgresqlStorage) CreateAccount(account Account) error { func (psql PostgresqlStorage) CreateAccount(account Account) error {
insertAccountStmt, err := psql.DbConnection.Prepare("INSERT INTO accounts (id, namespace, data, metadata) VALUES ($1, $2, $3, $4)") insertAccountStmt, err := psql.DbConnection.Prepare("INSERT INTO accounts (id, namespace, data, metadata)" +
" VALUES ($1, $2, $3, $4)")
if err != nil { if err != nil {
return err return err
} }
@ -324,7 +352,9 @@ func (psql PostgresqlStorage) CreateAccount(account Account) error {
if err != nil { if err != nil {
return err return err
} }
insertAccountAuthStmt, err := psql.DbConnection.Prepare("INSERT INTO account_auth (account_id, username, password, email, email_validation,phone_number,phone_number_validation) values($1, $2, $3, $4, $5, $6, $7)") insertAccountAuthStmt, err := psql.DbConnection.Prepare("INSERT INTO account_auth (account_id, username," +
" password, email, email_validation,phone_number,phone_number_validation) " +
"values($1, $2, $3, $4, $5, $6, $7)")
if err != nil { if err != nil {
return err return err
} }
@ -336,8 +366,13 @@ func (psql PostgresqlStorage) CreateAccount(account Account) error {
if err != nil { if err != nil {
return err return err
} }
_, err = insertAccountAuthStmt.Exec(account.ID, account.Authentication.Local.Username, account.Authentication.Local.Password, _, err = insertAccountAuthStmt.Exec(account.ID,
account.Authentication.Local.Email, emailValidationJson, account.Authentication.Local.PhoneNumber, phoneValidationJson) account.Authentication.Local.Username,
account.Authentication.Local.Password,
account.Authentication.Local.Email,
emailValidationJson,
account.Authentication.Local.PhoneNumber,
phoneValidationJson)
if err != nil { if err != nil {
return err return err
} }
@ -345,7 +380,8 @@ func (psql PostgresqlStorage) CreateAccount(account Account) error {
} }
func (psql PostgresqlStorage) UpdateAccount(account Account) error { func (psql PostgresqlStorage) UpdateAccount(account Account) error {
updateAccountStmt, err := psql.DbConnection.Prepare("update accounts set namespace=$1, data=$2, metadata=$3 where id= $4") updateAccountStmt, err := psql.DbConnection.Prepare("update accounts set namespace=$1, data=$2, " +
" metadata=$3 where id= $4")
if err != nil { if err != nil {
return err return err
} }
@ -361,7 +397,10 @@ func (psql PostgresqlStorage) UpdateAccount(account Account) error {
if err != nil { if err != nil {
return err return err
} }
updateAccountAuthStmt, err := psql.DbConnection.Prepare("update account_auth set username = $1, password = $2, email = $3, email_validation = $4 ,phone_number = $5,phone_number_validation = $6 where account_id = $7") updateAccountAuthStmt, err := psql.DbConnection.Prepare("update account_auth set username = $1," +
" password = $2," +
" email = $3, email_validation = $4 ," +
"phone_number = $5,phone_number_validation = $6 where account_id = $7")
if err != nil { if err != nil {
return err return err
} }
@ -373,15 +412,14 @@ func (psql PostgresqlStorage) UpdateAccount(account Account) error {
if err != nil { if err != nil {
return err return err
} }
_, err = updateAccountAuthStmt.Exec(account.Authentication.Local.Username, account.Authentication.Local.Password, account.Authentication.Local.Email, _, err = updateAccountAuthStmt.Exec(account.Authentication.Local.Username,
emailValidationJson, account.Authentication.Local.PhoneNumber, phoneValidationJson, account.ID) account.Authentication.Local.Password,
account.Authentication.Local.Email,
emailValidationJson,
account.Authentication.Local.PhoneNumber,
phoneValidationJson, account.ID)
if err != nil { if err != nil {
return err return err
} }
return nil return nil
} }
func isUUIDv4(str string) bool {
pattern := regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)
return pattern.MatchString(str)
}

View File

@ -41,7 +41,9 @@ func generateUUIDv4() string {
} }
uuid[6] = (uuid[6] & 0x0f) | 0x40 uuid[6] = (uuid[6] & 0x0f) | 0x40
uuid[8] = (uuid[8] & 0xbf) | 0x80 uuid[8] = (uuid[8] & 0xbf) | 0x80
return hex.EncodeToString(uuid[:4]) + "-" + hex.EncodeToString(uuid[4:6]) + "-" + hex.EncodeToString(uuid[6:8]) + "-" + hex.EncodeToString(uuid[8:10]) + "-" + hex.EncodeToString(uuid[10:]) return hex.EncodeToString(uuid[:4]) + "-" + hex.EncodeToString(uuid[4:6]) + "-" +
hex.EncodeToString(uuid[6:8]) + "-" + hex.EncodeToString(uuid[8:10]) + "-" +
hex.EncodeToString(uuid[10:])
} }
func TestGetAccount(t *testing.T) { func TestGetAccount(t *testing.T) {
@ -73,7 +75,8 @@ func TestGetAccount(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("error account data and metdata") t.Errorf("error account data and metdata")
} }
_, err = db.DbConnection.Exec("INSERT INTO accounts (id, namespace, data, metadata) VALUES ($1, $2, $3, $4)", account.ID, account.Namespace, dataJSON, dataJSON) _, err = db.DbConnection.Exec("INSERT INTO accounts (id, namespace, data, metadata) "+
"VALUES ($1, $2, $3, $4)", account.ID, account.Namespace, dataJSON, dataJSON)
if err != nil { if err != nil {
t.Errorf("error in inserting a new account") t.Errorf("error in inserting a new account")
} }
@ -94,7 +97,10 @@ func TestGetAccount(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("error account_auth localAuth") t.Errorf("error account_auth localAuth")
} }
_, err = db.DbConnection.Exec("INSERT INTO account_auth (account_id, username, password, email, email_validation, phone_number,phone_number_validation) VALUES ($1, $2, $3, $4, $5, $6, $7)", account.ID, localAuth.Username, localAuth.Password, localAuth.Email, localAuthJSON, localAuth.PhoneNumber, localAuthJSON) _, err = db.DbConnection.Exec("INSERT INTO account_auth (account_id, username, password, "+
"email, email_validation, "+
"phone_number,phone_number_validation) VALUES ($1, $2, $3, $4, $5, $6, $7)", account.ID,
localAuth.Username, localAuth.Password, localAuth.Email, localAuthJSON, localAuth.PhoneNumber, localAuthJSON)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
t.Errorf("error in iserting a new account in account_auth") t.Errorf("error in iserting a new account in account_auth")
@ -242,22 +248,26 @@ func TestPostgresqlStorage_LocalAuthentication(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("failed to create new psql connection") t.Errorf("failed to create new psql connection")
} }
accountByUsername, err := db.LocalAuthentication("test_namespace", "testuser", "", "") accountByUsername, err := db.LocalAuthentication("test_namespace", "testuser",
"", "")
if err != nil { if err != nil {
t.Errorf("Failed LocalAuthentication based on username and namespace") t.Errorf("Failed LocalAuthentication based on username and namespace")
} }
fmt.Println(accountByUsername) fmt.Println(accountByUsername)
accountByEmail, err := db.LocalAuthentication("test_namespace", "", "test@test.com", "") accountByEmail, err := db.LocalAuthentication("test_namespace", "",
"test@test.com", "")
if err != nil { if err != nil {
t.Errorf("Failed LocalAuthentication based on username and namespace") t.Errorf("Failed LocalAuthentication based on username and namespace")
} }
fmt.Println(accountByEmail) fmt.Println(accountByEmail)
accountByPhone, err := db.LocalAuthentication("test_namespace", "", "", "1234567890") accountByPhone, err := db.LocalAuthentication("test_namespace", "",
"", "1234567890")
if err != nil { if err != nil {
t.Errorf("Failed LocalAuthentication based on username and namespace") t.Errorf("Failed LocalAuthentication based on username and namespace")
} }
fmt.Println(accountByPhone) fmt.Println(accountByPhone)
accountByAll, err := db.LocalAuthentication("test_namespace", "testuser", "test@test.com", "1234567890") accountByAll, err := db.LocalAuthentication("test_namespace", "testuser",
"test@test.com", "1234567890")
if err != nil { if err != nil {
t.Errorf("Failed LocalAuthentication based on username and namespace") t.Errorf("Failed LocalAuthentication based on username and namespace")
} }