diff options
author | Julien Dessaux | 2021-04-10 20:11:35 +0200 |
---|---|---|
committer | Julien Dessaux | 2021-04-12 11:11:38 +0200 |
commit | b7c3e058e9b161065b9024458fc7be0b3c5e8cb5 (patch) | |
tree | d8a5d047f2aaabb7118a86123cd61761aa4bda6a /pkg/database/users.go | |
parent | Began implementing a database backend (diff) | |
download | trains-b7c3e058e9b161065b9024458fc7be0b3c5e8cb5.tar.gz trains-b7c3e058e9b161065b9024458fc7be0b3c5e8cb5.tar.bz2 trains-b7c3e058e9b161065b9024458fc7be0b3c5e8cb5.zip |
Implemented a user table and the CreateUser function
Diffstat (limited to 'pkg/database/users.go')
-rw-r--r-- | pkg/database/users.go | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/pkg/database/users.go b/pkg/database/users.go new file mode 100644 index 0000000..3f75f62 --- /dev/null +++ b/pkg/database/users.go @@ -0,0 +1,47 @@ +package database + +import ( + "git.adyxax.org/adyxax/trains/pkg/model" +) + +// Creates a new user in the database +// a QueryError is return if the username already exists (database constraints not met) +func (env *DBEnv) CreateUser(reg *model.UserRegistration) (*model.User, error) { + hash, err := hashPassword(reg.Password) + if err != nil { + return nil, err + } + query := ` + INSERT INTO users + (username, password, email) + VALUES + ($1, $2, $3);` + tx, err := env.db.Begin() + if err != nil { + return nil, newTransactionError("Could not Begin()", err) + } + result, err := tx.Exec( + query, + reg.Username, + hash, + reg.Email, + ) + if err != nil { + tx.Rollback() + return nil, newQueryError("Could not run database query, most likely the username already exists", err) + } + id, err := result.LastInsertId() + if err != nil { + tx.Rollback() + return nil, newTransactionError("Could not get LastInsertId, the database driver does not support this feature", err) + } + if err := tx.Commit(); err != nil { + return nil, newTransactionError("Could not commit transaction", err) + } + user := model.User{ + Id: int(id), + Username: reg.Username, + Email: reg.Email, + } + return &user, nil +} |