101 lines
1.6 KiB
Go
101 lines
1.6 KiB
Go
package user
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"nutfactory.org/Matrix/entities/device"
|
|
"nutfactory.org/Matrix/utils/database"
|
|
)
|
|
|
|
func CreateUser(user *User) (err error) {
|
|
sqlStmt := fmt.Sprintf(`INSERT INTO user
|
|
(id, name, password)
|
|
VALUES
|
|
(?, ?, ?)`)
|
|
|
|
tx, err := database.DB.Begin()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
stmt, err := tx.Prepare(sqlStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer stmt.Close()
|
|
|
|
_, err = stmt.Exec(user.Id, user.Name, user.Password)
|
|
if err != nil {
|
|
return
|
|
}
|
|
tx.Commit()
|
|
return
|
|
}
|
|
|
|
func ReadUser(id string) (foundUser *User, err error) {
|
|
queryStmt := fmt.Sprintf(`SELECT id, name, password
|
|
FROM user
|
|
WHERE id = '%s'`, id)
|
|
|
|
rows, err := database.DB.Query(queryStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
if rows.Next() {
|
|
foundUser = &User{}
|
|
err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password)
|
|
if err != nil {
|
|
return
|
|
}
|
|
foundUser.Devices, err = device.ReadDevicesForUser(foundUser.Id)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func UpdateUser(user *User) (err error) {
|
|
sqlStmt := fmt.Sprintf(`UPDATE user SET
|
|
name = ?,
|
|
password = ?
|
|
WHERE id = ?`)
|
|
|
|
tx, err := database.DB.Begin()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
stmt, err := tx.Prepare(sqlStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer stmt.Close()
|
|
|
|
_, err = stmt.Exec(user.Name, user.Password, user.Id)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
tx.Commit()
|
|
return
|
|
}
|
|
|
|
func DeleteUser(id string) (err error) {
|
|
queryStmt := fmt.Sprintf(`DELETE FROM user
|
|
WHERE id = '%s'`, id)
|
|
|
|
tx, err := database.DB.Begin()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
_, err = database.DB.Exec(queryStmt)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
tx.Commit()
|
|
return
|
|
}
|