(t *testing.T)
| 169 | } |
| 170 | |
| 171 | func TestTokenAuth(t *testing.T) { |
| 172 | db := testutils.InitMemoryDB(t) |
| 173 | |
| 174 | user := testutils.SetupUserData(db, "user@test.com", "password123") |
| 175 | tok := database.Token{ |
| 176 | UserID: user.ID, |
| 177 | Type: database.TokenTypeResetPassword, |
| 178 | Value: "xpwFnc0MdllFUePDq9DLeQ==", |
| 179 | } |
| 180 | testutils.MustExec(t, db.Save(&tok), "preparing token") |
| 181 | session := database.Session{ |
| 182 | Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", |
| 183 | UserID: user.ID, |
| 184 | ExpiresAt: time.Now().Add(time.Hour * 24), |
| 185 | } |
| 186 | testutils.MustExec(t, db.Save(&session), "preparing session") |
| 187 | |
| 188 | handler := func(w http.ResponseWriter, r *http.Request) { |
| 189 | w.WriteHeader(http.StatusOK) |
| 190 | } |
| 191 | |
| 192 | server := httptest.NewServer(TokenAuth(db, handler, database.TokenTypeResetPassword, nil)) |
| 193 | defer server.Close() |
| 194 | |
| 195 | t.Run("with token", func(t *testing.T) { |
| 196 | req := testutils.MakeReq(server.URL, "GET", "/?token=xpwFnc0MdllFUePDq9DLeQ==", "") |
| 197 | res := testutils.HTTPDo(t, req) |
| 198 | |
| 199 | assert.Equal(t, res.StatusCode, http.StatusOK, "status code mismatch") |
| 200 | }) |
| 201 | |
| 202 | t.Run("with invalid token", func(t *testing.T) { |
| 203 | req := testutils.MakeReq(server.URL, "GET", "/?token=someRandomToken==", "") |
| 204 | res := testutils.HTTPDo(t, req) |
| 205 | |
| 206 | assert.Equal(t, res.StatusCode, http.StatusUnauthorized, "status code mismatch") |
| 207 | }) |
| 208 | |
| 209 | t.Run("with session header", func(t *testing.T) { |
| 210 | req := testutils.MakeReq(server.URL, "GET", "/", "") |
| 211 | req.Header.Set("Authorization", "Bearer "+session.Key) |
| 212 | res := testutils.HTTPDo(t, req) |
| 213 | |
| 214 | assert.Equal(t, res.StatusCode, http.StatusOK, "status code mismatch") |
| 215 | }) |
| 216 | |
| 217 | t.Run("with invalid session", func(t *testing.T) { |
| 218 | req := testutils.MakeReq(server.URL, "GET", "/", "") |
| 219 | req.Header.Set("Authorization", "Bearer someInvalidSessionKey=") |
| 220 | res := testutils.HTTPDo(t, req) |
| 221 | |
| 222 | assert.Equal(t, res.StatusCode, http.StatusUnauthorized, "status code mismatch") |
| 223 | }) |
| 224 | |
| 225 | t.Run("without anything", func(t *testing.T) { |
| 226 | req := testutils.MakeReq(server.URL, "GET", "/", "") |
| 227 | res := testutils.HTTPDo(t, req) |
| 228 |
nothing calls this directly
no test coverage detected