start implementing auth
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"go-weather/models"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewUserService(db *sql.DB) *UserService {
|
||||
return &UserService{db: db}
|
||||
}
|
||||
|
||||
func (s *UserService) CreateUser(email string, password string) (*models.User, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var user models.User
|
||||
err = s.db.QueryRow(
|
||||
`INSERT INTO users (email, password_hash, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, email, created_at`,
|
||||
email, string(hashedPassword), time.Now(),
|
||||
).Scan(&user.ID, &user.Email, &user.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *UserService) GetUserByEmail(email string) (*models.User, error) {
|
||||
|
||||
var user models.User
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id, email, password_hash, created_at
|
||||
FROM users
|
||||
WHERE email = $1`, email,
|
||||
).Scan(&user.ID, &user.Email, &user.PasswordHash, &user.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *UserService) EmailExists(email string) (bool, error) {
|
||||
var exists bool
|
||||
err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)`, email).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
func (s *UserService) ValidatePassword(user *models.User, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
Reference in New Issue
Block a user