Files
2022-02-10 18:42:52 +08:00

93 lines
2.4 KiB
Go

package account
import (
"SciencesServer/app/api/enterprise/model"
model2 "SciencesServer/app/common/model"
"SciencesServer/app/handle"
"SciencesServer/serve/orm"
"SciencesServer/utils"
"errors"
"gorm.io/gorm"
)
type Register struct{ tenantID uint64 }
type RegisterHandle func(tenantID uint64) *Register
type (
RegisterParams struct {
Name, Mobile, Captcha, Password, RepeatPass string
}
)
func (c *RegisterParams) checkPassword() bool {
return c.Password == c.RepeatPass
}
func (c *RegisterParams) checkCaptcha() (bool, error) {
return handle.NewCaptcha().Validate(&handle.CaptchaSms{Captcha: c.Captcha, Mobile: c.Mobile})
}
func (c *RegisterParams) checkUserExist(mUserInstance *model2.UserInstance, tenantID uint64) (bool, error) {
var count int64
if err := model2.Count(mUserInstance, &count, model2.NewWhere("mobile", c.Mobile)); //model2.NewWhere("local", local)
err != nil {
return false, err
}
return count <= 0, nil
}
// Launch 发起注册
func (c *Register) Launch(params *RegisterParams) (*InstanceLoginReturn, error) {
if !utils.ValidateMobile(params.Mobile) {
return nil, errors.New("手机号码错误")
}
// 验证密码
if !params.checkPassword() {
return nil, errors.New("两次密码不一致")
}
// 验证验证码
pass, err := params.checkCaptcha()
if err != nil {
return nil, err
} else if !pass {
return nil, errors.New("验证码错误或已过期")
}
// 验证账号信息
mUserInstance := model.NewUserInstance()
if pass, err = params.checkUserExist(mUserInstance.UserInstance, c.tenantID); err != nil {
return nil, err
} else if !pass {
return nil, errors.New("当前手机号码已注册")
}
if params.Name == "" {
params.Name = params.Mobile
}
mUserInstance.Source = model2.UserInstanceSourceForLocal
mUserInstance.Mobile = params.Mobile
mUserInstance.Name = params.Name
mUserInstance.Password = params.Password
if err = orm.GetDB().Transaction(func(tx *gorm.DB) error {
if err = model2.Create(mUserInstance.UserInstance, tx); err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return NewInstance()().Login()(&InstanceLoginParams{
UID: mUserInstance.UUID, Name: mUserInstance.Name, Mobile: mUserInstance.Mobile,
Identity: mUserInstance.Identity,
}), err
}
func NewRegister() RegisterHandle {
return func(tenantID uint64) *Register {
return &Register{tenantID: tenantID}
}
}