user_credential.go 1.2 KB
package userAuth

import (
	"github.com/tiptok/gocomm/pkg/redis"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
)

//Redis用户权限
type RedisUserCredential struct {
	phone   string
	Options *Options
}

func NewRedisUserCredential(phone string, options ...Option) *RedisUserCredential {
	rua := &RedisUserCredential{
		Options: NewOptions(options...),
		phone:   phone,
	}
	return rua
}
func (auth RedisUserCredential) AddAuth(credential string) error {
	err := redis.Hset(
		auth.redisKey(),
		auth.field(),
		credential, 0,
	)
	return err
}
func (auth RedisUserCredential) RemoveAuth() error {
	if !auth.Exist() {
		return nil
	}
	return redis.Hdel(auth.redisKey(), auth.field())
}
func (auth RedisUserCredential) GetAuth() (string, error) {
	if !auth.Exist() {
		return "", errNotFound(auth.field())
	}
	data, err := redis.Hget(auth.redisKey(), auth.field())
	if err != nil {
		return "", err
	}
	return string(data), nil
}
func (auth RedisUserCredential) Exist() bool {
	return redis.Hexists(auth.redisKey(), auth.field())
}
func (auth RedisUserCredential) redisKey() string {
	if len(auth.phone) == 0 {
		return ""
	}
	return utils.RedisKey("user_credential")
}
func (auth RedisUserCredential) field() string {
	return auth.phone
}