Add users

This commit is contained in:
2022-02-13 21:45:27 +01:00
parent e03efbf09c
commit 3e843d429a
11 changed files with 326 additions and 28 deletions

10
pkg/users/model.go Normal file
View File

@@ -0,0 +1,10 @@
package users
type User struct {
Id int
Email string
}
func NewUser(id int, email string) *User {
return &User{id, email}
}

8
pkg/users/repository.go Normal file
View File

@@ -0,0 +1,8 @@
package users
import "context"
type Repository interface {
Create(ctx context.Context, user *CreateUser) (int, error)
GetByEmail(ctx context.Context, email string, passwordHash string) (*User, error)
}

44
pkg/users/service.go Normal file
View File

@@ -0,0 +1,44 @@
package users
import (
"context"
"github.com/eko/gocache/cache"
"go.uber.org/zap"
)
type Service struct {
logger *zap.Logger
cache *cache.Cache
repository Repository
passwordHasher PasswordHasher
}
func NewService(l *zap.Logger, ur Repository, c *cache.Cache) *Service {
return &Service{
logger: l,
repository: ur,
cache: c,
passwordHasher: NewPlainTextPasswordHasher(),
}
}
func (s *Service) Create(email string, password string) (int, error) {
createUser, err := NewCreateUser(email, password, s.passwordHasher)
if err != nil {
return -1, err
}
var userId int
userId, err = s.repository.Create(context.Background(), createUser)
if err != nil {
s.logger.Warn("Could not create user in service")
return 0, err
}
return userId, nil
}
func (s *Service) Authenticate(ctx context.Context, email string, password string) (*User, error) {
user, err := s.repository.GetByEmail(ctx, email, s.passwordHasher.HashPassword(password))
return user, err
}

49
pkg/users/user.go Normal file
View File

@@ -0,0 +1,49 @@
package users
import "errors"
type PasswordHasher interface {
HashPassword(password string) string
}
type CreateUser struct {
Email string
PasswordHash string
}
func NewCreateUser(email string, password string, hasher PasswordHasher) (*CreateUser, error) {
if email == "" {
return nil, errors.New("Email cannot be empty for user")
}
if password == "" || len(password) < 8 {
return nil, errors.New("password is doesn't fit requirements")
}
return &CreateUser{
Email: email,
PasswordHash: hasher.HashPassword(password),
}, nil
}
type bCryptPasswordHasher struct {
}
func NewBCryptPasswordHasher() PasswordHasher {
return &bCryptPasswordHasher{}
}
func (b bCryptPasswordHasher) HashPassword(password string) string {
//TODO implement me
panic("implement me")
}
type plainTextPasswordHasher struct {
}
func NewPlainTextPasswordHasher() PasswordHasher {
return &plainTextPasswordHasher{}
}
func (p plainTextPasswordHasher) HashPassword(password string) string {
return password
}