package user import ( "fmt" "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 { 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 } 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 { 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 } _, err = tx.Exec(queryStmt) if err != nil { tx.Rollback() return } tx.Commit() return }