Skip to content

Commit

Permalink
fix escaping issue (#123)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhammer authored May 11, 2024
1 parent c68a73c commit 6a1b552
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
3 changes: 2 additions & 1 deletion cmd/site/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package site

import (
"fmt"
"html"
"html/template"
"net/http"
"strings"
Expand Down Expand Up @@ -54,7 +55,7 @@ func (v ViewData) Add(a int, b int) int {
}

func (v ViewData) NewLineify(str string) template.HTML {
return template.HTML(strings.ReplaceAll(str, "\n", "<br>"))
return template.HTML(strings.ReplaceAll(html.EscapeString(str), "\n", "<br>"))
}

func (v ViewData) Replace(original string, pattern string, replacement string) string {
Expand Down
63 changes: 63 additions & 0 deletions cmd/site/template_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package site_test

import (
"scribly/cmd/site"
"scribly/embed"
"scribly/internal"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestStoryTemplate(t *testing.T) {
userZach := internal.User{
ID: 1,
Username: "zach",
}
userGabe := internal.User{
ID: 2,
Username: "gabe",
}
userStory := internal.UserStory{
UserID: userZach.ID,
Story: internal.Story{
ID: 1,
Title: "Test Story",
CurrentWriter: &userZach,
State: internal.StoryStateInProgress,
Cowriters: []internal.StoryCowriter{
{
User: userZach,
},
{
User: userGabe,
},
},
Turns: []internal.Turn{
{
TakenByID: userZach.ID,
Action: internal.TurnActionWrite,
Text: "There was a car\nwow",
},
{
TakenByID: userGabe.ID,
Action: internal.TurnActionWrite,
Text: "And there was a <horse>",
},
},
},
}

// make a buffer writer for testing output
var buff strings.Builder

err := embed.WebTemplates.ExecuteTemplate(&buff, "story.tmpl", site.ViewData{
Data: &userStory,
})
assert.NoError(t, err)
assert.Contains(t, buff.String(), "There was a car<br>wow")
// test that <horse> was escaped, by showing what it would be escaped to
assert.Contains(t, buff.String(), "&lt;horse&gt;")

}

0 comments on commit 6a1b552

Please sign in to comment.