MCPcopy Index your code
hub / github.com/dnote/dnote / TestAuth

Function TestAuth

pkg/server/middleware/auth_test.go:64–169  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

62}
63
64func TestAuth(t *testing.T) {
65 db := testutils.InitMemoryDB(t)
66
67 user := testutils.SetupUserData(db, "alice@test.com", "pass1234")
68
69 session := database.Session{
70 Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=",
71 UserID: user.ID,
72 ExpiresAt: time.Now().Add(time.Hour * 24),
73 }
74 testutils.MustExec(t, db.Save(&session), "preparing session")
75 expiredSession := database.Session{
76 Key: "Vvgm3eBXfXGEFWERI7faiRJ3DAzJw+7DdT9J1LEyNfI=",
77 UserID: user.ID,
78 ExpiresAt: time.Now().Add(-time.Hour * 24),
79 }
80 testutils.MustExec(t, db.Save(&expiredSession), "preparing expired session")
81
82 handler := func(w http.ResponseWriter, r *http.Request) {
83 w.WriteHeader(http.StatusOK)
84 }
85
86 t.Run("valid session with header", func(t *testing.T) {
87 server := httptest.NewServer(Auth(db, handler, nil))
88 defer server.Close()
89
90 req := testutils.MakeReq(server.URL, "GET", "/", "")
91 req.Header.Set("Authorization", "Bearer "+session.Key)
92 res := testutils.HTTPDo(t, req)
93
94 assert.Equal(t, res.StatusCode, http.StatusOK, "status code mismatch")
95 })
96
97 t.Run("expired session with header", func(t *testing.T) {
98 server := httptest.NewServer(Auth(db, handler, nil))
99 defer server.Close()
100
101 req := testutils.MakeReq(server.URL, "GET", "/", "")
102 req.Header.Set("Authorization", "Bearer "+expiredSession.Key)
103 res := testutils.HTTPDo(t, req)
104
105 assert.Equal(t, res.StatusCode, http.StatusUnauthorized, "status code mismatch")
106 })
107
108 t.Run("invalid session with header", func(t *testing.T) {
109 server := httptest.NewServer(Auth(db, handler, nil))
110 defer server.Close()
111
112 req := testutils.MakeReq(server.URL, "GET", "/", "")
113 req.Header.Set("Authorization", "Bearer someInvalidSessionKey=")
114 res := testutils.HTTPDo(t, req)
115
116 assert.Equal(t, res.StatusCode, http.StatusUnauthorized, "status code mismatch")
117 })
118
119 t.Run("valid session with cookie", func(t *testing.T) {
120 server := httptest.NewServer(Auth(db, handler, nil))
121 defer server.Close()

Callers

nothing calls this directly

Calls 10

InitMemoryDBFunction · 0.92
SetupUserDataFunction · 0.92
MustExecFunction · 0.92
MakeReqFunction · 0.92
HTTPDoFunction · 0.92
EqualFunction · 0.92
AuthFunction · 0.85
WriteHeaderMethod · 0.80
NowMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected