auth_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package auth
  2. import (
  3. "context"
  4. "testing"
  5. "git.i2edu.net/i2/go-zero/core/stores/redis/redistest"
  6. "github.com/stretchr/testify/assert"
  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, clean, err := redistest.CreateRedis()
  43. assert.Nil(t, err)
  44. defer clean()
  45. for _, test := range tests {
  46. t.Run(test.name, func(t *testing.T) {
  47. if len(test.app) > 0 {
  48. assert.Nil(t, store.Hset("apps", test.app, test.token))
  49. defer store.Hdel("apps", test.app)
  50. }
  51. authenticator, err := NewAuthenticator(store, "apps", test.strict)
  52. assert.Nil(t, err)
  53. assert.NotNil(t, authenticator.Authenticate(context.Background()))
  54. md := metadata.New(map[string]string{})
  55. ctx := metadata.NewIncomingContext(context.Background(), md)
  56. assert.NotNil(t, authenticator.Authenticate(ctx))
  57. md = metadata.New(map[string]string{
  58. "app": "",
  59. "token": "",
  60. })
  61. ctx = metadata.NewIncomingContext(context.Background(), md)
  62. assert.NotNil(t, authenticator.Authenticate(ctx))
  63. md = metadata.New(map[string]string{
  64. "app": "foo",
  65. "token": "bar",
  66. })
  67. ctx = metadata.NewIncomingContext(context.Background(), md)
  68. err = authenticator.Authenticate(ctx)
  69. if test.hasError {
  70. assert.NotNil(t, err)
  71. } else {
  72. assert.Nil(t, err)
  73. }
  74. })
  75. }
  76. }