mirror of
https://github.com/notherealmarco/WASAPhoto.git
synced 2025-05-05 04:18:40 +02:00
Add case-insensitive check for username equality
This commit is contained in:
parent
f95ec8dcf1
commit
d7f35991df
1 changed files with 29 additions and 2 deletions
|
@ -2,6 +2,7 @@ package database
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid"
|
||||||
"github.com/notherealmarco/WASAPhoto/service/database/db_errors"
|
"github.com/notherealmarco/WASAPhoto/service/database/db_errors"
|
||||||
|
@ -47,6 +48,16 @@ func (db *appdbimpl) GetUserID(name string) (string, error) {
|
||||||
|
|
||||||
// Create a new user
|
// Create a new user
|
||||||
func (db *appdbimpl) CreateUser(name string) (string, error) {
|
func (db *appdbimpl) CreateUser(name string) (string, error) {
|
||||||
|
|
||||||
|
// check if username is taken (case insensitive)
|
||||||
|
exists, err := db.nameExists(name)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
} else if exists {
|
||||||
|
return "", errors.New("username already exists")
|
||||||
|
}
|
||||||
|
|
||||||
uid, err := uuid.NewV4()
|
uid, err := uuid.NewV4()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
@ -55,14 +66,30 @@ func (db *appdbimpl) CreateUser(name string) (string, error) {
|
||||||
return uid.String(), err
|
return uid.String(), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if username exists
|
||||||
|
func (db *appdbimpl) nameExists(name string) (bool, error) {
|
||||||
|
var cnt int
|
||||||
|
err := db.c.QueryRow(`SELECT COUNT(*) FROM "users" WHERE "name" LIKE ?`, name).Scan(&cnt)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return cnt > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Update username
|
// Update username
|
||||||
func (db *appdbimpl) UpdateUsername(uid string, name string) (QueryResult, error) {
|
func (db *appdbimpl) UpdateUsername(uid string, name string) (QueryResult, error) {
|
||||||
_, err := db.c.Exec(`UPDATE "users" SET "name" = ? WHERE "uid" = ?`, name, uid)
|
|
||||||
|
|
||||||
if db_errors.UniqueViolation(err) {
|
// check if username is taken (case insensitive)
|
||||||
|
exists, err := db.nameExists(name)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return ERR_INTERNAL, err
|
||||||
|
} else if exists {
|
||||||
return ERR_EXISTS, nil
|
return ERR_EXISTS, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_, err = db.c.Exec(`UPDATE "users" SET "name" = ? WHERE "uid" = ?`, name, uid)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ERR_INTERNAL, err
|
return ERR_INTERNAL, err
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue