106 lines
2.3 KiB
Go
106 lines
2.3 KiB
Go
|
package services
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"errors"
|
||
|
"go-cook/api/models"
|
||
|
"go-cook/api/repositories"
|
||
|
"strings"
|
||
|
|
||
|
"golang.org/x/crypto/bcrypt"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ErrPasswordNotLongEnough = "password needs to be 8 character or longer"
|
||
|
ErrPasswordMissingSpecialCharacter = "password needs to contain one of the following: !, @, #"
|
||
|
ErrInvalidPassword = "invalid password"
|
||
|
)
|
||
|
|
||
|
// This will handle operations that are user related, but one layer higher then the repository
|
||
|
type UserService struct {
|
||
|
repo repositories.IUserTable
|
||
|
}
|
||
|
|
||
|
func NewUserService(conn *sql.DB) UserService {
|
||
|
return UserService{
|
||
|
repo: repositories.NewUserRepository(conn),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (us UserService) DoesUserExist(username string) error {
|
||
|
_, err := us.repo.GetByName(username)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (us UserService) DoesPasswordMatchHash(username, password string) error {
|
||
|
passwordBytes := []byte(password)
|
||
|
hash, err := bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
model, err := us.GetUser(username)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if model.Hash != string(hash) {
|
||
|
return errors.New(ErrInvalidPassword)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (us UserService) GetUser(username string) (models.UserModel, error) {
|
||
|
return us.repo.GetByName(username)
|
||
|
}
|
||
|
|
||
|
func (us UserService) CreateNewUser(name, password string) (models.UserModel, error) {
|
||
|
err := us.CheckPasswordForRequirements(password)
|
||
|
if err != nil {
|
||
|
return models.UserModel{}, err
|
||
|
}
|
||
|
|
||
|
us.repo.Create(name, password)
|
||
|
return models.UserModel{}, nil
|
||
|
}
|
||
|
|
||
|
func (us UserService) CheckPasswordForRequirements(password string) error {
|
||
|
err := us.checkPasswordLength(password)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
err = us.checkPasswordForSpecialCharacters(password)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (us UserService) checkPasswordLength(password string) error {
|
||
|
if len(password) <= 8 {
|
||
|
return errors.New(ErrPasswordNotLongEnough)
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (us UserService) checkPasswordForSpecialCharacters(password string) error {
|
||
|
var chars []string
|
||
|
chars = append(chars, "!")
|
||
|
chars = append(chars, "@")
|
||
|
chars = append(chars, "#")
|
||
|
|
||
|
for _, char := range chars {
|
||
|
if strings.Contains(password, char) {
|
||
|
return nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return errors.New(ErrPasswordMissingSpecialCharacter)
|
||
|
}
|