github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/tequilapi/middlewares/auth_middleware_test.go (about)

     1  /*
     2   * Copyright (C) 2023 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package middlewares
    19  
    20  import (
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"testing"
    24  
    25  	"github.com/pkg/errors"
    26  
    27  	"github.com/gin-gonic/gin"
    28  	"github.com/stretchr/testify/assert"
    29  )
    30  
    31  type MockAuthenticator struct {
    32  	Err error
    33  }
    34  
    35  func (m *MockAuthenticator) ValidateToken(token string) (bool, error) {
    36  	return false, m.Err
    37  }
    38  
    39  func (m *MockAuthenticator) SetErr(err error) {
    40  	m.Err = err
    41  }
    42  
    43  func TestTokenParsing(t *testing.T) {
    44  	// given
    45  	authenticator := &MockAuthenticator{Err: errors.New("")}
    46  
    47  	req, err := http.NewRequest(http.MethodGet, "/not-important", nil)
    48  	assert.NoError(t, err)
    49  	respRecorder := httptest.NewRecorder()
    50  
    51  	g := gin.Default()
    52  	g.Use(ApplyMiddlewareTokenAuth(authenticator))
    53  
    54  	// expect
    55  	g.ServeHTTP(respRecorder, req)
    56  	assert.Equal(
    57  		t,
    58  		http.StatusUnauthorized,
    59  		respRecorder.Code,
    60  	)
    61  
    62  	//and
    63  	authenticator.SetErr(nil)
    64  	respRecorder = httptest.NewRecorder()
    65  	g.ServeHTTP(respRecorder, req)
    66  	assert.Equal(
    67  		t,
    68  		http.StatusNotFound,
    69  		respRecorder.Code,
    70  	)
    71  
    72  	//and
    73  	authenticator.SetErr(nil)
    74  	req, err = http.NewRequest(http.MethodGet, "/not-important", nil)
    75  	assert.NoError(t, err)
    76  	respRecorder = httptest.NewRecorder()
    77  
    78  	// no 'Bearer' prefix
    79  	req.Header = map[string][]string{"Authorization": {"123"}}
    80  
    81  	g.ServeHTTP(respRecorder, req)
    82  	assert.Equal(
    83  		t,
    84  		http.StatusBadRequest,
    85  		respRecorder.Code,
    86  	)
    87  }