Skip to content

Commit

Permalink
Add light url validation and sanitization with tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
chrishalbert committed Jan 20, 2024
1 parent 0d3b4b8 commit fb4127e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
13 changes: 10 additions & 3 deletions google/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import (
"encoding/gob"
"encoding/json"
"fmt"

"net/http"
"net/url"
"os"
"strings"

"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
Expand Down Expand Up @@ -116,8 +117,14 @@ func GetLoginURL(state string) string {
return conf.AuthCodeURL(state)
}

func WithLoginURL(url string) {
loginURL = url
func WithLoginURL(s string) error {
s = strings.TrimSpace(s)
url, err := url.ParseRequestURI(s)
if err != nil {
return err
}
loginURL = url.String()
return nil
}

// Auth is the google authorization middleware. You can use them to protect a routergroup.
Expand Down
41 changes: 34 additions & 7 deletions google/google_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,38 @@ func TestSetupFromString(t *testing.T) {
}

func TestWithLoginURL(t *testing.T) {
t.Run("should assign the login url", func(t *testing.T) {
loginURL = ""
url := "http://fake.fake"
WithLoginURL(url)
assert.NotEmpty(t, url)
assert.Equal(t, url, loginURL)
})

var testCases = []struct {
description string
urlParm string
expectUrlLogin string
isErrNil bool
}{
{
description: "should assign a valid url without error",
urlParm: "http://fake.fake",
expectUrlLogin: "http://fake.fake",
isErrNil: true,
},
{
description: "should assign a sanitizable url without error",
urlParm: " http://fake.fake ",
expectUrlLogin: "http://fake.fake",
isErrNil: true,
},
{
description: "should not assign an invalid url without error",
urlParm: "not a parseable url",
expectUrlLogin: "",
isErrNil: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
loginURL = ""
err := WithLoginURL(testCase.urlParm)
assert.Equal(t, testCase.expectUrlLogin, loginURL)
assert.Equal(t, testCase.isErrNil, err == nil)
})
}
}

0 comments on commit fb4127e

Please sign in to comment.