login_auth.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "youngee_b_api/consts"
  8. "youngee_b_api/model/redis_model"
  9. "youngee_b_api/model/system_model"
  10. "youngee_b_api/redis"
  11. )
  12. var LoginAuth *loginAuth
  13. func LoginAuthInit(config *system_model.Session) {
  14. auth := new(loginAuth)
  15. auth.sessionTTL = time.Duration(config.TTL) * time.Minute
  16. LoginAuth = auth
  17. }
  18. type loginAuth struct {
  19. sessionTTL time.Duration
  20. }
  21. func (l *loginAuth) AuthToken(ctx context.Context, token string) (*redis_model.Auth, error) {
  22. value, err := redis.Get(ctx, l.getRedisKey(token))
  23. if err != nil {
  24. if err == consts.RedisNil {
  25. return nil, fmt.Errorf("not found in redis,token:%+v", token)
  26. }
  27. return nil, err
  28. }
  29. auth := new(redis_model.Auth)
  30. if err = json.Unmarshal([]byte(value), auth); err != nil {
  31. return nil, err
  32. }
  33. return auth, nil
  34. }
  35. func (l *loginAuth) AuthPassword(ctx context.Context, phone, password string) *redis_model.Auth {
  36. // 需要添加mysql库认证逻辑
  37. // todo
  38. auth := &redis_model.Auth{
  39. Phone: phone,
  40. }
  41. if authJson, err := json.Marshal(auth); err == nil {
  42. err = redis.Set(ctx, l.getRedisKey(phone), string(authJson), l.sessionTTL)
  43. if err == nil {
  44. return auth
  45. }
  46. }
  47. return nil
  48. }
  49. func (l *loginAuth) getRedisKey(key string) string {
  50. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  51. }