package logic import ( "context" "errors" "fmt" "member/gen_result/pb/member" "member/internal/domain" ers "member/internal/lib/error" "member/internal/model" "member/internal/svc" "member/internal/utils" "time" "github.com/go-sql-driver/mysql" "github.com/zeromicro/go-zero/core/logx" ) type CreateUserAccountLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewCreateUserAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserAccountLogic { return &CreateUserAccountLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } type createLoginUserReq struct { LoginId string `json:"login_id" validate:"account"` Platform int64 `json:"platform" validate:"required,oneof=1 2 3"` Token string `json:"token" validate:"required"` } // HasPasswordFunc 這樣方便測試 var HasPasswordFunc = utils.HashPassword // CreateUserAccount 建立帳號與密碼 -> 可登入,但可不可以做其他事情看業務流程,也可以只註冊就好 func (l *CreateUserAccountLogic) CreateUserAccount(in *member.CreateLoginUserReq) (*member.Response, error) { // 驗證資料 if err := l.svcCtx.Validate.ValidateAll(&createLoginUserReq{ LoginId: in.GetLoginId(), Platform: in.GetPlatform(), Token: in.GetToken(), }); err != nil { return nil, ers.InvalidFormat(err.Error()) } token, err := HasPasswordFunc(in.GetToken(), l.svcCtx.Config.Bcrypt.Cost) if err != nil { return nil, ers.ArkInternal(fmt.Sprintf("failed to encrypt err: %v", err.Error())) } // 新增進去 now := time.Now().UTC().Unix() _, err = l.svcCtx.AccountModel.Insert(l.ctx, &model.Account{ Account: in.LoginId, Token: token, Platform: in.Platform, CreateTime: now, UpdateTime: now, }) if err != nil { // 新增進去 var mysqlErr *mysql.MySQLError if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 { // 處理重複條目錯誤 return nil, ers.DBDuplicate(in.LoginId) } return nil, ers.DBError(err.Error()) } return &member.Response{ Status: &member.BaseResp{ Code: domain.CodeOk.ToString(), Message: "success", Error: "", }, }, nil }