2021-06-19 06:37:16 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
2021-07-03 10:11:57 +00:00
|
|
|
"path/filepath"
|
2021-06-19 06:37:16 +00:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2021-06-28 20:17:18 +00:00
|
|
|
"go.goblog.app/app/pkgs/contenttype"
|
2021-06-19 06:37:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func Test_captchaMiddleware(t *testing.T) {
|
|
|
|
app := &goBlog{
|
|
|
|
cfg: &config{
|
2021-07-03 10:11:57 +00:00
|
|
|
Db: &configDb{
|
|
|
|
File: filepath.Join(t.TempDir(), "test.db"),
|
|
|
|
},
|
2021-06-19 06:37:16 +00:00
|
|
|
Server: &configServer{
|
|
|
|
PublicAddress: "https://example.com",
|
|
|
|
},
|
|
|
|
Blogs: map[string]*configBlog{
|
|
|
|
"en": {
|
|
|
|
Lang: "en",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
DefaultBlog: "en",
|
|
|
|
User: &configUser{},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2021-07-14 13:44:57 +00:00
|
|
|
_ = app.initDatabase(false)
|
2021-07-30 13:43:13 +00:00
|
|
|
app.initComponents()
|
2021-06-19 06:37:16 +00:00
|
|
|
|
|
|
|
h := app.captchaMiddleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2021-06-23 17:20:50 +00:00
|
|
|
_, _ = rw.Write([]byte("ABC Test"))
|
2021-06-19 06:37:16 +00:00
|
|
|
}))
|
|
|
|
|
|
|
|
t.Run("Default", func(t *testing.T) {
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/abc", nil)
|
|
|
|
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
|
|
|
|
h.ServeHTTP(rec, req)
|
|
|
|
|
|
|
|
res := rec.Result()
|
|
|
|
resBody, _ := io.ReadAll(res.Body)
|
|
|
|
_ = res.Body.Close()
|
|
|
|
resString := string(resBody)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
|
|
|
|
assert.Contains(t, res.Header.Get("Content-Type"), contenttype.HTML)
|
|
|
|
assert.Contains(t, resString, "name=captchamethod value=POST")
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Captcha session", func(t *testing.T) {
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/abc", nil)
|
|
|
|
rec1 := httptest.NewRecorder()
|
|
|
|
|
|
|
|
session, _ := app.captchaSessions.Get(req, "c")
|
|
|
|
session.Values["captcha"] = true
|
2021-06-23 17:20:50 +00:00
|
|
|
_ = session.Save(req, rec1)
|
2021-06-19 06:37:16 +00:00
|
|
|
|
|
|
|
for _, cookie := range rec1.Result().Cookies() {
|
|
|
|
req.AddCookie(cookie)
|
|
|
|
}
|
|
|
|
|
|
|
|
rec2 := httptest.NewRecorder()
|
|
|
|
|
|
|
|
h.ServeHTTP(rec2, req)
|
|
|
|
|
|
|
|
res := rec2.Result()
|
|
|
|
resBody, _ := io.ReadAll(res.Body)
|
|
|
|
_ = res.Body.Close()
|
|
|
|
resString := string(resBody)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusOK, res.StatusCode)
|
|
|
|
assert.Contains(t, resString, "ABC Test")
|
|
|
|
})
|
|
|
|
}
|