4f2dc018da
deliberately skipping salting and encrypting passwords at this point. intending to approach this in tandem with authenication. also starting to want db migrations, but trying not to get distracted.
51 lines
816 B
Go
51 lines
816 B
Go
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
)
|
|
|
|
type User struct {
|
|
Username string
|
|
}
|
|
|
|
type UserModel struct {
|
|
DB *sql.DB
|
|
}
|
|
|
|
// Insert
|
|
func (m *UserModel) Insert(username string, password string) (int, error) {
|
|
stmt := `INSERT INTO users (username, password, created)
|
|
VALUES(?, ?, UTC_TIMESTAMP())`
|
|
|
|
result, err := m.DB.Exec(stmt, username, password)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
id, err := result.LastInsertId()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return int(id), nil
|
|
}
|
|
|
|
// Get
|
|
func (m *UserModel) Get(id int) (User, error) {
|
|
stmt := "SELECT id, username FROM users WHERE id = ?"
|
|
|
|
var u User
|
|
|
|
err := m.DB.QueryRow(stmt, id).Scan(&u.Username)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return User{}, ErrNoRecord
|
|
} else {
|
|
return User{}, err
|
|
}
|
|
}
|
|
|
|
return u, nil
|
|
}
|