auth_cache_subscriber.go 1.5 KB
package subscriber

import (
	"github.com/tiptok/gocomm/xa/eda"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
	devent "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/event"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
	"strconv"
)

type AuthCacheSubscribe struct {
}

func (s *AuthCacheSubscribe) HandleEvent(event eda.Event) error {
	switch event.EventType() {
	case devent.ACCESS_TOKEN_EVENT:
		e, _ := event.(*devent.AccessTokenEvent)
		return s.addAuth(e.UserPhone, e.AccessToken, e.RefreshToken)
	case devent.REFRESH_TOKEN_EVENT:
		e, _ := event.(*devent.RefreshTokenEvent)
		if err := s.removeAuth(e.UserPhone, e.OldAccessToken, e.OldRefreshToken); err != nil {
			return err
		}
		return s.addAuth(e.UserPhone, e.AccessToken, e.RefreshToken)
	default:
		break
	}
	return nil
}

func (s *AuthCacheSubscribe) addAuth(phone, accessToken, refreshToken string) error {
	userPhone, _ := strconv.Atoi(phone)
	auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)),
		userAuth.WithAccessToken(accessToken),
		userAuth.WithRefreshToken(refreshToken))
	if err := auth.AddAuth(); err != nil {
		log.Error(err)
		return err
	}
	return nil
}

func (s *AuthCacheSubscribe) removeAuth(phone, accessToken, refreshToken string) error {
	userPhone, _ := strconv.Atoi(phone)
	oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)))
	if err := oldAuth.Check(
		userAuth.NewOptions(
			userAuth.WithRefreshToken(refreshToken),
			userAuth.WithAccessToken(accessToken),
		)); err != nil {
		log.Error(err)
		return err
	}
	return nil
}