33 lines
757 B
Go
33 lines
757 B
Go
package services
|
|
|
|
import (
|
|
"errors"
|
|
"gitea.zjmud.xyz/phyer/rbcp/models"
|
|
"gitea.zjmud.xyz/phyer/rbcp/repositories"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func Authenticate(username, password string) (*models.User, error) {
|
|
user, err := repositories.GetUserByUsername(username)
|
|
if err != nil {
|
|
return nil, errors.New("user not found")
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
|
return nil, errors.New("invalid password")
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func CreateUser(user *models.User) error {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
user.Password = string(hashedPassword)
|
|
return repositories.CreateUser(user)
|
|
}
|