github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/api/web/middleware/authenticate_test.go (about)

     1  package middleware
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"testing"
     8  
     9  	"github.com/grafviktor/keep-my-secret/internal/api"
    10  	"github.com/grafviktor/keep-my-secret/internal/api/auth"
    11  	"github.com/grafviktor/keep-my-secret/internal/config"
    12  )
    13  
    14  type mockAuthVerifier struct{}
    15  
    16  //nolint:lll
    17  func (m mockAuthVerifier) VerifyAuthHeader(config config.AppConfig, w http.ResponseWriter, r *http.Request) (string, *auth.Claims, error) {
    18  	claims := &auth.Claims{}
    19  	//nolint:goconst
    20  	claims.Subject = "testuser"
    21  
    22  	authHeader := r.Header.Get("Authorization")
    23  	if authHeader == "" {
    24  		return "", nil, errors.New("no auth header")
    25  	}
    26  
    27  	return "", claims, nil
    28  }
    29  
    30  func TestAuthRequired(t *testing.T) {
    31  	// Create an instance of my middleware with the mock dependency
    32  	mw := middleware{
    33  		config:       config.AppConfig{},
    34  		authVerifier: mockAuthVerifier{},
    35  	}
    36  
    37  	handler := mw.AuthRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    38  		// Retrieve the user login from the context
    39  		userLogin, ok := r.Context().Value(api.ContextUserLogin).(string)
    40  		if !ok {
    41  			t.Fatal("User login not found in context")
    42  		}
    43  
    44  		// Check if the user login matches the expected value
    45  		//noling:goconst
    46  		expectedUserLogin := "testuser" // Replace with the expected user login
    47  		if userLogin != expectedUserLogin {
    48  			t.Errorf("Expected user login '%s', got '%s'", expectedUserLogin, userLogin)
    49  		}
    50  
    51  		// Serve the response
    52  		w.WriteHeader(http.StatusOK)
    53  	}))
    54  
    55  	// Case 1 verifier should pass is OK
    56  	// Create a sample HTTP request
    57  	req, err := http.NewRequest("GET", "/test", nil)
    58  	if err != nil {
    59  		t.Fatalf("Failed to create request: %v", err)
    60  	}
    61  
    62  	req.Header.Set("Authorization", "Bearer bla-bla")
    63  
    64  	// Create a mock response recorder
    65  	rr := httptest.NewRecorder()
    66  
    67  	// Call the AuthRequired middleware
    68  	handler.ServeHTTP(rr, req)
    69  
    70  	// Check the response status code
    71  	if rr.Code != http.StatusOK {
    72  		t.Errorf("Expected status code %d, got %d", http.StatusOK, rr.Code)
    73  	}
    74  
    75  	// Case 2 verifier should send an error
    76  	// Create a sample HTTP request
    77  	req, err = http.NewRequest("GET", "/test", nil)
    78  	if err != nil {
    79  		t.Fatalf("Failed to create request: %v", err)
    80  	}
    81  
    82  	// Not setting auth header this time
    83  	// req.Header.Set("Authorization", "Bearer bla-bla")
    84  
    85  	// Create a mock response recorder
    86  	rr = httptest.NewRecorder()
    87  
    88  	// Call the AuthRequired middleware
    89  	handler.ServeHTTP(rr, req)
    90  
    91  	// Check the response status code
    92  	if rr.Code != http.StatusUnauthorized {
    93  		t.Errorf("Expected status code %d, got %d", http.StatusOK, rr.Code)
    94  	}
    95  }