fix comment again

This commit is contained in:
Hoang 2021-11-08 17:04:01 +07:00
parent b06431b9b9
commit d620c7c40e
7 changed files with 63 additions and 43 deletions

View File

@ -2,7 +2,6 @@ package usermngmt
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"github.com/Selly-Modules/logger" "github.com/Selly-Modules/logger"
@ -15,7 +14,7 @@ type CreateOptions struct {
Name string Name string
Phone string Phone string
Email string Email string
HashedPassword string Password string
Status string Status string
RoleID primitive.ObjectID RoleID primitive.ObjectID
Other string Other string
@ -29,7 +28,7 @@ func (s Service) Create(payload CreateOptions) error {
) )
// Validate payload // Validate payload
err := payload.validate() err := payload.validate(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -40,16 +39,6 @@ func (s Service) Create(payload CreateOptions) error {
return err return err
} }
// Find roleID exists or not
if !s.isRoleIDAlreadyExisted(ctx, userData.RoleID) {
return errors.New("roleID does not exist")
}
// Find phone number,email exists or not
if s.isPhoneNumberOrEmailAlreadyExisted(ctx, userData.Phone, userData.Email) {
return errors.New("phone number or email already existed")
}
// Create device // Create device
_, err = col.InsertOne(ctx, userData) _, err = col.InsertOne(ctx, userData)
if err != nil { if err != nil {
@ -70,7 +59,7 @@ func (payload CreateOptions) newUser() (result User, err error) {
Name: payload.Name, Name: payload.Name,
Phone: payload.Phone, Phone: payload.Phone,
Email: payload.Email, Email: payload.Email,
HashedPassword: payload.HashedPassword, HashedPassword: hashPassword(payload.Password),
Status: payload.Status, Status: payload.Status,
RoleID: payload.RoleID, RoleID: payload.RoleID,
Other: payload.Other, Other: payload.Other,

View File

@ -6,4 +6,6 @@ const (
tableRole = "roles" tableRole = "roles"
timezoneHCM = "Asia/Ho_Chi_Minh" timezoneHCM = "Asia/Ho_Chi_Minh"
passwordHashingCost = 14
) )

28
db.go
View File

@ -12,18 +12,23 @@ import (
// getUserCollection ... // getUserCollection ...
func (s Service) getUserCollection() *mongo.Collection { func (s Service) getUserCollection() *mongo.Collection {
if s.TablePrefix != "" {
return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableUser)) return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableUser))
} }
return s.DB.Collection(tableUser)
}
// getRoleCollection ... // getRoleCollection ...
func (s Service) getRoleCollection() *mongo.Collection { func (s Service) getRoleCollection() *mongo.Collection {
return s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableRole)) if s.TablePrefix != "" {
s.DB.Collection(fmt.Sprintf("%s-%s", s.TablePrefix, tableRole))
}
return s.DB.Collection(tableRole)
} }
func (s Service) isPhoneNumberOrEmailAlreadyExisted(ctx context.Context, phone, email string) bool { func (s Service) isPhoneNumberOrEmailExisted(ctx context.Context, phone, email string) bool {
var ( var (
col = s.getUserCollection() col = s.getUserCollection()
user = User{}
) )
// Find // Find
@ -37,32 +42,33 @@ func (s Service) isPhoneNumberOrEmailAlreadyExisted(ctx context.Context, phone,
}, },
}, },
} }
if err := col.FindOne(ctx, cond).Decode(&user); err != nil { total, err := col.CountDocuments(ctx, cond)
logger.Error("usermngmt - findByCondition", logger.LogData{ if err != nil {
logger.Error("usermngmt - countUserByCondition", logger.LogData{
"condition": cond, "condition": cond,
"err": err.Error(), "err": err.Error(),
}) })
return true return true
} }
return !user.ID.IsZero() return total != 0
} }
func (s Service) isRoleIDAlreadyExisted(ctx context.Context, roleID primitive.ObjectID) bool { func (s Service) isRoleIDExisted(ctx context.Context, roleID primitive.ObjectID) bool {
var ( var (
col = s.getRoleCollection() col = s.getRoleCollection()
role = Role{}
) )
// Find // Find
cond := bson.M{ cond := bson.M{
"_id": roleID, "_id": roleID,
} }
if err := col.FindOne(ctx, cond).Decode(&role); err != nil { total, err := col.CountDocuments(ctx, cond)
logger.Error("usermngmt - findRoleByCondition", logger.LogData{ if err != nil {
logger.Error("usermngmt - countRoleByCondition", logger.LogData{
"condition": cond, "condition": cond,
"err": err.Error(), "err": err.Error(),
}) })
return false return false
} }
return !role.ID.IsZero() return total != 0
} }

View File

@ -1 +1,13 @@
package usermngmt package usermngmt
import "golang.org/x/crypto/bcrypt"
func hashPassword(password string) string {
bytes, _ := bcrypt.GenerateFromPassword([]byte(password), passwordHashingCost)
return string(bytes)
}
func checkPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

View File

@ -12,9 +12,9 @@ type User struct {
Name string `bson:"name" json:"name"` Name string `bson:"name" json:"name"`
Phone string `bson:"phone" json:"phone"` // unique Phone string `bson:"phone" json:"phone"` // unique
Email string `bson:"email" json:"email"` // unique Email string `bson:"email" json:"email"` // unique
HashedPassword string `bson:"hashedPassword" json:"hashedPassword"` HashedPassword string `bson:"hashedPassword" json:"-"`
Status string `bson:"status" json:"status"` Status string `bson:"status" json:"status"`
RoleID primitive.ObjectID `bson:"roleID" json:"roleId"` RoleID primitive.ObjectID `bson:"roleId" json:"roleId"`
Other string `bson:"other" json:"other"` Other string `bson:"other" json:"other"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"` CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"` UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`

View File

@ -31,7 +31,7 @@ var s *Service
// Init ... // Init ...
func Init(config Config) (*Service, error) { func Init(config Config) (*Service, error) {
if config.MongoDB.Host == "" || config.TablePrefix == "" { if config.MongoDB.Host == "" {
return nil, errors.New("please provide all necessary information for init user") return nil, errors.New("please provide all necessary information for init user")
} }

View File

@ -1,12 +1,13 @@
package usermngmt package usermngmt
import ( import (
"context"
"errors" "errors"
"github.com/Selly-Modules/logger" "github.com/Selly-Modules/logger"
) )
func (co CreateOptions) validate() error { func (co CreateOptions) validate(ctx context.Context) error {
// Name // Name
if co.Name == "" { if co.Name == "" {
logger.Error("usermngmt - Create: no Name data", logger.LogData{ logger.Error("usermngmt - Create: no Name data", logger.LogData{
@ -31,12 +32,12 @@ func (co CreateOptions) validate() error {
return errors.New("no email data") return errors.New("no email data")
} }
// HashedPassword // Password
if co.HashedPassword == "" { if co.Password == "" {
logger.Error("usermngmt - Create: no hashedPassword data", logger.LogData{ logger.Error("usermngmt - Create: no password data", logger.LogData{
"payload": co, "payload": co,
}) })
return errors.New("no hashedPassword data") return errors.New("no password data")
} }
// Status // Status
@ -55,5 +56,15 @@ func (co CreateOptions) validate() error {
return errors.New("invalid roleID data") return errors.New("invalid roleID data")
} }
// Find roleID exists or not
if !s.isRoleIDExisted(ctx, co.RoleID) {
return errors.New("role id does not exist")
}
// Find phone number,email exists or not
if s.isPhoneNumberOrEmailExisted(ctx, co.Phone, co.Email) {
return errors.New("phone number or email already existed")
}
return nil return nil
} }