1
0

auth_test.go 1.8 KB

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