github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/tests/auth_test.go (about)

     1  package tests
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/ShoshinNikita/budget-manager/internal/web"
    12  	"github.com/ShoshinNikita/budget-manager/internal/web/api/models"
    13  )
    14  
    15  func TestAuth(t *testing.T) {
    16  	t.Parallel()
    17  
    18  	RunTest(t, TestFn(testAuth), func(env *TestEnv) {
    19  		env.Cfg.Server.Auth.Disable = false
    20  		env.Cfg.Server.Auth.BasicAuthCreds = web.Credentials{
    21  			"user": "$2y$05$wK5Ad.qdY.ZLPsfEv3rc/.uO.8SkbD6r2ptiuZefMUOX0wgGK/1rC", // user:qwerty
    22  		}
    23  	})
    24  }
    25  
    26  func testAuth(t *testing.T, host string) {
    27  	url := fmt.Sprintf("http://%s/api/search/spends", host)
    28  
    29  	const (
    30  		User  = "user"
    31  		Pass  = "qwerty"
    32  		Wrong = "123"
    33  	)
    34  
    35  	tests := []struct {
    36  		name               string
    37  		username, password string
    38  		//
    39  		wantAuthorized bool
    40  	}{
    41  		{name: "no auth"},
    42  		{name: "wrong username and password", username: Wrong, password: Wrong},
    43  		{name: "wrong username", username: Wrong, password: Pass},
    44  		{name: "wrong password", username: User, password: Wrong},
    45  		{name: "correct credentials", username: User, password: Pass, wantAuthorized: true},
    46  	}
    47  	for _, tt := range tests {
    48  		tt := tt
    49  		t.Run(tt.name, func(t *testing.T) {
    50  			require := require.New(t)
    51  
    52  			req, cancel := newRequest(t, GET, url, nil)
    53  			defer cancel()
    54  
    55  			if tt.username != "" {
    56  				req.SetBasicAuth(tt.username, tt.password)
    57  			}
    58  
    59  			resp, err := http.DefaultClient.Do(req)
    60  			require.NoError(err)
    61  			defer resp.Body.Close()
    62  
    63  			var baseResp models.BaseResponse
    64  			dec := json.NewDecoder(resp.Body)
    65  			require.NoError(dec.Decode(&baseResp))
    66  			require.False(dec.More())
    67  
    68  			var (
    69  				wantStatusCode         = http.StatusUnauthorized
    70  				wantError              = "unauthorized"
    71  				wantAuthenticateHeader = `Basic realm="Budget Manager"`
    72  			)
    73  			if tt.wantAuthorized {
    74  				wantStatusCode = http.StatusOK
    75  				wantError = ""
    76  				wantAuthenticateHeader = ""
    77  			}
    78  
    79  			require.Equal(wantStatusCode, resp.StatusCode)
    80  			require.Equal(wantError, baseResp.Error)
    81  			require.Equal(wantAuthenticateHeader, resp.Header.Get("WWW-Authenticate"))
    82  		})
    83  	}
    84  }