user_auth.go 2.6 KB
package domain

import (
	"strings"
	"time"
)

// 用户认证实体
type UserAuth struct {
	// 用户认证编号
	UserAuthId int64 `json:"userAuthId"`
	// 用户id列表
	Users []int64 `json:"users"`
	// 手机认证
	PhoneAuth *PhoneAuth `json:"phoneAuth"`
	// 凭证认证
	CredentialAuths []*CredentialAuth `credentialAuths`
	// 创建时间
	CreateAt time.Time `json:"createAt"`
	// 更新时间
	UpdateAt time.Time `json:"updateAt"`
}

type UserAuthRepository interface {
	Save(userAuth *UserAuth) (*UserAuth, error)
	Remove(userAuth *UserAuth) (*UserAuth, error)
	FindOne(queryOptions map[string]interface{}) (*UserAuth, error)
	Find(queryOptions map[string]interface{}) (int64, []*UserAuth, error)
}

func (userAuth *UserAuth) Identify() interface{} {
	if userAuth.UserAuthId == 0 {
		return nil
	}
	return userAuth.UserAuthId
}

func (userAuth *UserAuth) Update(data map[string]interface{}) error {
	if userAuthId, ok := data["userAuthId"]; ok {
		userAuth.UserAuthId = userAuthId.(int64)
	}
	if users, ok := data["users"]; ok {
		userAuth.Users = users.([]int64)
	}
	if phone, ok := data["phone"]; ok {
		userAuth.PhoneAuth.Phone = phone.(string)
	}
	if password, ok := data["password"]; ok {
		userAuth.PhoneAuth.Password = password.(string)
	}
	if createAt, ok := data["createAt"]; ok {
		userAuth.CreateAt = createAt.(time.Time)
	}
	if updateAt, ok := data["updateAt"]; ok {
		userAuth.UpdateAt = updateAt.(time.Time)
	}
	return nil
}

// 绑定凭证
func (userAuth *UserAuth) BindCredentialAuth(cred *CredentialAuth) error {
	var exists bool
	if err := cred.Check(); err != nil {
		return err
	}
	for i, v := range userAuth.CredentialAuths {
		if v.DeviceType == cred.DeviceType {
			userAuth.CredentialAuths[i] = cred
			exists = true
		}
	}
	if !exists {
		userAuth.CredentialAuths = append(userAuth.CredentialAuths, cred)
	}
	return nil
}

// 解除凭证
func (userAuth *UserAuth) UnbindCredentialAuth(deviceType int) error {
	length := len(userAuth.CredentialAuths)
	for i, v := range userAuth.CredentialAuths {
		if v.DeviceType == deviceType {
			if length <= 1 {
				userAuth.CredentialAuths = []*CredentialAuth{}
			} else {
				userAuth.CredentialAuths[i] = userAuth.CredentialAuths[length-1]
				userAuth.CredentialAuths = userAuth.CredentialAuths[:length-1]
			}
			return nil
		}
	}
	return nil
}

// 检查凭证
func (userAuth *UserAuth) CheckCredentialAuth(deviceType int, cred string) bool {
	for _, v := range userAuth.CredentialAuths {
		if v.DeviceType == deviceType && strings.EqualFold(v.Credential, cred) {
			if err := v.Check(); err != nil {
				return false
			}
			return true
		}
	}
	return false
}