pg_user_auth_phone_authentication.go 1.8 KB
package domainService

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/linmadan/egglib-go/core/application"
	coreDomain "github.com/linmadan/egglib-go/core/domain"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/repository"
	"time"
)

const defaultPassword = "7c4a8d09ca3762af61e59520943dc26494f8941b" //sha1 mmm123456

type PhoneAuthenticationService struct {
	coreDomain.BaseEventPublisher
	transactionContext *pgTransaction.TransactionContext
}

func (service *PhoneAuthenticationService) PhoneAuth(userId int64, phone, passwd string) (*domain.UserAuth, error) {
	var userAuth *domain.UserAuth
	var err error
	UserAuthRepository, _ := repository.NewUserAuthRepository(service.transactionContext)
	userAuth, err = UserAuthRepository.FindOne(map[string]interface{}{"phone": phone})
	if userAuth != nil {
		userAuth.Update(map[string]interface{}{"password": passwd, "userId": userId})
	}
	if err == pg.ErrNoRows {
		if passwd == "" {
			passwd = defaultPassword
		}
		userAuth = &domain.UserAuth{
			Users: []int64{userId},
			PhoneAuth: &domain.PhoneAuth{
				Phone:    phone,
				Password: passwd,
			},
			CredentialAuths: []*domain.CredentialAuth{},
			CreateAt:        time.Now(),
			UpdateAt:        time.Now(),
		}
		err = nil
	}
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return UserAuthRepository.Save(userAuth)
}

func NewPhoneAuthenticationService(transactionContext *pgTransaction.TransactionContext) (*PhoneAuthenticationService, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &PhoneAuthenticationService{
			transactionContext: transactionContext,
		}, nil
	}
}