You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
package dbi
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
type User struct {
|
|
APIKey string `json:"api_key"`
|
|
FirstName string `json:"first_name"`
|
|
LastName string `json:"last_name"`
|
|
Password string `json:"password"`
|
|
Status string `json:"status"`
|
|
Username string `json:"username"`
|
|
}
|
|
|
|
func CreateUser(conn *sql.Conn, user *User) error {
|
|
if user.APIKey == "" {
|
|
user.APIKey = GenUUID()
|
|
}
|
|
if user.Password != "" {
|
|
hash := md5.Sum([]byte(user.Password))
|
|
user.Password = fmt.Sprintf("%x", hash)
|
|
}
|
|
_, err := conn.ExecContext(context.Background(),
|
|
`INSERT INTO users (APIKey, FirstName, LastName, Password, Status, Username)
|
|
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
user.APIKey, user.FirstName, user.LastName, user.Password, user.Status, user.Username,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func GetUser(conn *sql.Conn, username string) (User, error) {
|
|
row := conn.QueryRowContext(context.Background(),
|
|
`SELECT APIKey, FirstName, LastName, Password, Status, Username
|
|
FROM users WHERE Username = ?`,
|
|
username,
|
|
)
|
|
var u User
|
|
err := row.Scan(&u.APIKey, &u.FirstName, &u.LastName, &u.Password, &u.Status, &u.Username)
|
|
if err == sql.ErrNoRows {
|
|
return User{}, fmt.Errorf("user %q not found", username)
|
|
}
|
|
return u, err
|
|
}
|
|
|
|
func UpdateUser(conn *sql.Conn, user *User) error {
|
|
_, err := conn.ExecContext(context.Background(),
|
|
`UPDATE users SET APIKey = ?, FirstName = ?, LastName = ?, Password = ?, Status = ?
|
|
WHERE Username = ?`,
|
|
user.APIKey, user.FirstName, user.LastName, user.Password, user.Status, user.Username,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func DeleteUser(conn *sql.Conn, username string) error {
|
|
_, err := conn.ExecContext(context.Background(),
|
|
`DELETE FROM users WHERE Username = ?`,
|
|
username,
|
|
)
|
|
return err
|
|
}
|