credential_auth.go 977 字节
package domain

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"
)

var (
	errorCredentialIsEmpty = fmt.Errorf("credential is empty")
	errorCredentialExpired = fmt.Errorf("credential has expired")
)

const (
	defaultCredExpireDuration = 3600 * time.Second
)

// 凭证认证
type CredentialAuth struct {
	// 设备类型 0:ios 1:android 2:web
	DeviceType int `json:"deviceType"`
	// 凭证信息
	Credential string `json:"credential"`
	// 过期时间
	Expire int64 `json:"expire"`
}

func (auth *CredentialAuth) Check() error {
	if len(auth.Credential) == 0 {
		return errorCredentialIsEmpty
	}
	if auth.Expire == 0 || auth.Expire < time.Now().Unix() {
		return errorCredentialExpired
	}
	return nil
}

func NewCredentialAuth(deviceType int, cred string) *CredentialAuth {
	if cred == "" {
		cred = "cred:" + strconv.Itoa(rand.Int())
	}
	return &CredentialAuth{
		DeviceType: deviceType,
		Credential: cred,
		Expire:     time.Now().Add(defaultCredExpireDuration).Unix(),
	}
}