github.com/cheikhshift/buffalo@v0.9.5/middleware/basicauth/basicauth_test.go (about)

     1  package basicauth_test
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/gobuffalo/buffalo"
     9  	"github.com/gobuffalo/buffalo/middleware/basicauth"
    10  	"github.com/markbates/willie"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func app() *buffalo.App {
    15  	h := func(c buffalo.Context) error {
    16  		return c.Render(200, nil)
    17  	}
    18  	auth := func(c buffalo.Context, u, p string) (bool, error) {
    19  		return (u == "tester" && p == "pass123"), nil
    20  	}
    21  	a := buffalo.New(buffalo.Options{})
    22  	a.Use(basicauth.Middleware(auth))
    23  	a.GET("/", h)
    24  	return a
    25  }
    26  
    27  func TestBasicAuth(t *testing.T) {
    28  	r := require.New(t)
    29  
    30  	w := willie.New(app())
    31  
    32  	authfail := "invalid basic auth"
    33  
    34  	// missing authorization
    35  	res := w.Request("/").Get()
    36  	r.Equal(401, res.Code)
    37  	r.Contains(res.Header().Get("WWW-Authenticate"), `Basic realm="Basic Authentication"`)
    38  	r.Contains(res.Body.String(), "Unauthorized")
    39  
    40  	// bad header value, not Basic
    41  	req := w.Request("/")
    42  	req.Headers["Authorization"] = "badcreds"
    43  	res = req.Get()
    44  	r.Equal(401, res.Code)
    45  	r.Contains(res.Body.String(), "Unauthorized")
    46  
    47  	// bad cred values
    48  	req = w.Request("/")
    49  	req.Headers["Authorization"] = "bad creds"
    50  	res = req.Get()
    51  	r.Equal(500, res.Code)
    52  	r.Contains(res.Body.String(), authfail)
    53  
    54  	creds := base64.StdEncoding.EncodeToString([]byte("badcredvalue"))
    55  
    56  	// invalid cred values in authorization
    57  	req = w.Request("/")
    58  	req.Headers["Authorization"] = fmt.Sprintf("Basic %s", creds)
    59  	res = req.Get()
    60  	r.Equal(500, res.Code)
    61  	r.Contains(res.Body.String(), authfail)
    62  
    63  	creds = base64.StdEncoding.EncodeToString([]byte("tester:pass123"))
    64  
    65  	// valid cred values
    66  	req = w.Request("/")
    67  	req.Headers["Authorization"] = fmt.Sprintf("Basic %s", creds)
    68  	res = req.Get()
    69  	r.Equal(200, res.Code)
    70  }