Matrix/entities/user/userDatabaseConnector.go

130 lines
2.2 KiB
Go
Raw Normal View History

package user
import (
"fmt"
2020-10-12 14:16:28 +00:00
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/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 {
2020-10-17 10:07:39 +00:00
tx.Rollback()
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
}
2020-10-11 21:11:30 +00:00
func ReadUserFromAccessToken(accessToken string) (foundUser *User, err error) {
queryStmt := fmt.Sprintf(`SELECT u.id, u.name, u.password
FROM user as u
join device as d on u.id = d.userId
WHERE d.accessToken = '%s'`, accessToken)
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 {
2020-10-17 10:07:39 +00:00
tx.Rollback()
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
}
2020-10-17 10:07:39 +00:00
_, err = tx.Exec(queryStmt)
if err != nil {
2020-10-17 10:07:39 +00:00
tx.Rollback()
return
}
tx.Commit()
return
}