auth_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package auth
  2. import (
  3. "os"
  4. "testing"
  5. "git.aetherial.dev/aeth/keiji/pkg/env"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. // Implementing the Source interface
  9. type testAuthSource struct {
  10. user string
  11. pass string
  12. }
  13. func (tst testAuthSource) AdminUsername() string { return tst.user }
  14. func (tst testAuthSource) AdminPassword() string { return tst.pass }
  15. /*
  16. Table testing the authorize function
  17. */
  18. func TestAuthorize(t *testing.T) {
  19. type authTestCase struct {
  20. desc string
  21. inputUsername string
  22. inputPassword string
  23. realUsername string
  24. realPassword string
  25. expectError error
  26. }
  27. cache := NewCache()
  28. for _, tc := range []authTestCase{
  29. {
  30. desc: "Passing test case where auth works",
  31. inputUsername: "admin",
  32. inputPassword: "abc123",
  33. realUsername: "admin",
  34. realPassword: "abc123",
  35. expectError: nil,
  36. },
  37. {
  38. desc: "Auth fails because username is empty",
  39. inputUsername: "",
  40. inputPassword: "abc123",
  41. realUsername: "admin",
  42. realPassword: "abc123",
  43. expectError: &InvalidCredentials{},
  44. },
  45. {
  46. desc: "Auth fails because password is empty",
  47. inputUsername: "admin",
  48. inputPassword: "",
  49. realUsername: "admin",
  50. realPassword: "abc123",
  51. expectError: &InvalidCredentials{},
  52. },
  53. {
  54. desc: "Auth fails because password is wrong",
  55. inputUsername: "admin",
  56. inputPassword: "xyz987",
  57. realUsername: "admin",
  58. realPassword: "abc123",
  59. expectError: &InvalidCredentials{},
  60. },
  61. {
  62. desc: "Auth fails because username is wrong",
  63. inputUsername: "admin",
  64. inputPassword: "abc123",
  65. realUsername: "superuser",
  66. realPassword: "abc123",
  67. expectError: &InvalidCredentials{},
  68. },
  69. } {
  70. t.Run(tc.desc, func(t *testing.T) {
  71. _, err := Authorize(&Credentials{Username: tc.inputUsername,
  72. Password: tc.inputPassword},
  73. cache,
  74. testAuthSource{user: tc.realUsername, pass: tc.realPassword})
  75. assert.Equal(t, tc.expectError, err)
  76. })
  77. }
  78. }
  79. func TestEnvAuth(t *testing.T) {
  80. username := "testuser"
  81. password := "testpass"
  82. os.Setenv(env.KEIJI_USERNAME, username)
  83. os.Setenv(env.KEIJI_PASSWORD, password)
  84. defer os.Unsetenv(env.KEIJI_PASSWORD)
  85. defer os.Unsetenv(env.KEIJI_PASSWORD)
  86. authSrc := EnvAuth{}
  87. assert.Equal(t, username, authSrc.AdminUsername())
  88. assert.Equal(t, password, authSrc.AdminPassword())
  89. }