auth_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package auth
  2. import (
  3. "context"
  4. "testing"
  5. "github.com/alicebob/miniredis"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/tal-tech/go-zero/core/stores/redis"
  8. "google.golang.org/grpc/metadata"
  9. )
  10. func TestAuthenticator(t *testing.T) {
  11. tests := []struct {
  12. name string
  13. app string
  14. token string
  15. strict bool
  16. hasError bool
  17. }{
  18. {
  19. name: "strict=false",
  20. strict: false,
  21. hasError: false,
  22. },
  23. {
  24. name: "strict=true",
  25. strict: true,
  26. hasError: true,
  27. },
  28. {
  29. name: "strict=true,with token",
  30. app: "foo",
  31. token: "bar",
  32. strict: true,
  33. hasError: false,
  34. },
  35. {
  36. name: "strict=true,with error token",
  37. app: "foo",
  38. token: "error",
  39. strict: true,
  40. hasError: true,
  41. },
  42. }
  43. r := miniredis.NewMiniRedis()
  44. assert.Nil(t, r.Start())
  45. defer r.Close()
  46. for _, test := range tests {
  47. t.Run(test.name, func(t *testing.T) {
  48. store := redis.NewRedis(r.Addr(), redis.NodeType)
  49. if len(test.app) > 0 {
  50. assert.Nil(t, store.Hset("apps", test.app, test.token))
  51. defer store.Hdel("apps", test.app)
  52. }
  53. authenticator, err := NewAuthenticator(store, "apps", test.strict)
  54. assert.Nil(t, err)
  55. assert.NotNil(t, authenticator.Authenticate(context.Background()))
  56. md := metadata.New(map[string]string{})
  57. ctx := metadata.NewIncomingContext(context.Background(), md)
  58. assert.NotNil(t, authenticator.Authenticate(ctx))
  59. md = metadata.New(map[string]string{
  60. "app": "",
  61. "token": "",
  62. })
  63. ctx = metadata.NewIncomingContext(context.Background(), md)
  64. assert.NotNil(t, authenticator.Authenticate(ctx))
  65. md = metadata.New(map[string]string{
  66. "app": "foo",
  67. "token": "bar",
  68. })
  69. ctx = metadata.NewIncomingContext(context.Background(), md)
  70. err = authenticator.Authenticate(ctx)
  71. if test.hasError {
  72. assert.NotNil(t, err)
  73. } else {
  74. assert.Nil(t, err)
  75. }
  76. })
  77. }
  78. }