github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/session/session_test.go (about)

     1  package session
     2  
     3  import (
     4  	"net/http/httptest"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/fragmenta/auth"
     9  )
    10  
    11  var (
    12  	testKey = "12353bce2bbc4efb90eff81c29dc982de9a0176b568db18a61b4f4732cadabbc"
    13  	set     = "foo"
    14  )
    15  
    16  // TestAuthenticate tests storing a value in a cookie and retreiving it again.
    17  func TestAuthenticate(t *testing.T) {
    18  	// Setup auth with some test values - could read these from config I guess
    19  	auth.HMACKey = auth.HexToBytes(testKey)
    20  	auth.SecretKey = auth.HexToBytes(testKey)
    21  	auth.SessionName = "test_session"
    22  
    23  	r := httptest.NewRequest("GET", "/", nil)
    24  	w := httptest.NewRecorder()
    25  
    26  	// Get the current user for this request (nil)
    27  	currentUser := CurrentUser(w, r)
    28  	if currentUser.ID != 0 {
    29  		t.Fatalf("auth: failed to get empty user")
    30  	}
    31  
    32  	// Now set a user on session on request, and try again
    33  	session, err := auth.Session(w, r)
    34  	if err != nil {
    35  		t.Fatalf("auth: failed to build session")
    36  	}
    37  	session.Set(auth.SessionUserKey, "1")
    38  
    39  	// Set the cookie on the recorder
    40  	err = session.Save(w)
    41  	if err != nil {
    42  		t.Fatalf("auth: failed to save session")
    43  	}
    44  
    45  	// Now get the cookie back out and put it on the request as if it were coming in from browser
    46  	r.Header.Set("Cookie", strings.Join(w.HeaderMap["Set-Cookie"], ""))
    47  
    48  	t.Logf("SESSION:%v", session)
    49  
    50  	session, err = auth.Session(w, r)
    51  	if err != nil {
    52  		t.Fatalf("auth: failed to build session")
    53  	}
    54  	if session.Get(auth.SessionUserKey) != "1" {
    55  		t.Fatalf("auth: failed to restore session value")
    56  	}
    57  
    58  }