generated from tsivinsky/go-template
add user authentication
This commit is contained in:
50
model/user.go
Normal file
50
model/user.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import "github.com/jmoiron/sqlx"
|
||||
|
||||
type User struct {
|
||||
Model
|
||||
|
||||
Email string `json:"email" db:"email"`
|
||||
Password string `json:"-" db:"password"`
|
||||
}
|
||||
|
||||
func (u *User) Create(db *sqlx.DB) error {
|
||||
res, err := db.NamedExec("INSERT INTO users (email, password) VALUES (:email, :password)", map[string]any{
|
||||
"email": u.Email,
|
||||
"password": u.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u.ID, _ = res.LastInsertId()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *User) FindByID(db *sqlx.DB) error {
|
||||
row := db.QueryRowx("SELECT * FROM users WHERE id = ?", u.ID)
|
||||
if row.Err() != nil {
|
||||
return row.Err()
|
||||
}
|
||||
|
||||
if err := row.StructScan(u); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *User) FindByEmail(db *sqlx.DB) error {
|
||||
row := db.QueryRowx("SELECT * FROM users WHERE email = ?", u.Email)
|
||||
if row.Err() != nil {
|
||||
return row.Err()
|
||||
}
|
||||
|
||||
if err := row.StructScan(u); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user