github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/net/http/authn/authn_test.go (about)

     1  package authn
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/bytom/bytom/accesstoken"
    10  	dbm "github.com/bytom/bytom/database/leveldb"
    11  	"github.com/bytom/bytom/errors"
    12  )
    13  
    14  func TestAuthenticate(t *testing.T) {
    15  	tokenDB := dbm.NewDB("testdb", "leveldb", "temp")
    16  	defer os.RemoveAll("temp")
    17  	tokenStore := accesstoken.NewStore(tokenDB)
    18  	token, err := tokenStore.Create("alice", "test")
    19  	if err != nil {
    20  		t.Errorf("create token error")
    21  	}
    22  
    23  	cases := []struct {
    24  		id, tok string
    25  		want    error
    26  	}{
    27  		{"alice", token.Token, nil},
    28  		{"alice", "alice:abcsdsdfassdfsefsfsfesfesfefsefa", ErrInvalidToken},
    29  	}
    30  
    31  	api := NewAPI(tokenStore, false)
    32  
    33  	for _, c := range cases {
    34  		var username, password string
    35  		toks := strings.SplitN(c.tok, ":", 2)
    36  		if len(toks) > 0 {
    37  			username = toks[0]
    38  		}
    39  		if len(toks) > 1 {
    40  			password = toks[1]
    41  		}
    42  
    43  		req, _ := http.NewRequest("GET", "/", nil)
    44  		req.SetBasicAuth(username, password)
    45  
    46  		_, err := api.Authenticate(req)
    47  		if errors.Root(err) != c.want {
    48  			t.Errorf("Authenticate(%s) error = %s want %s", c.id, err, c.want)
    49  		}
    50  	}
    51  }