Skip to content

Commit

Permalink
Fix url validation
Browse files Browse the repository at this point in the history
  • Loading branch information
richardhallett committed Jul 25, 2023
1 parent 75e1a65 commit d71037c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
15 changes: 12 additions & 3 deletions internal/app/event/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,19 @@ func checkDoiExistsInDataCite(doi string, url string, dataciteApiUrl string, cli
}

// Compare the result with the url but ignore the protocol
if validateDoiUrl(result.Url, url) {
if !validateDoiUrl(result.Url, url) {
return errors.New("This DOI doesn't match this URL")
}

return nil
}

func validateDoiUrl(doiUrl string, urlCompare string) bool {
// Print stripScheme(doiUrl)
fmt.Println(stripScheme(doiUrl))
// Print stripScheme(urlCompare)
fmt.Println(stripScheme(urlCompare))

// Compare the result with the url but ignore the protocol
if stripScheme(doiUrl) != stripScheme(urlCompare) {
return false
Expand All @@ -152,8 +157,12 @@ func validateDoiUrl(doiUrl string, urlCompare string) bool {

// Function to strip the scheme from a URL
func stripScheme(urlToStrip string) string {
parsedUrl, _ := url.Parse(urlToStrip)
return parsedUrl.Host + parsedUrl.Path + "?" + parsedUrl.RawQuery + parsedUrl.Fragment
parsedUrl, _ := url.ParseRequestURI(urlToStrip)
parsedUrl.Scheme = ""
// Strip trailing slash from path
parsedUrl.Path = strings.TrimSuffix(parsedUrl.Path, "/")

return parsedUrl.String()
}

func CreateMockEvent(metricName string, repoId string, doi string, userId uint64, timestamp time.Time) Event {
Expand Down
18 changes: 16 additions & 2 deletions internal/app/event/service_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
package event

import (
"net/http"
"testing"
)

// Test checkDoiExistsInDataCite
func TestValidateDoiUrl(t *testing.T) {
if(!validateDoiUrl("http://www.example.com/url?foo=bar&foo=baz#this_is_fragment", "https://www.example.com/url?foo=bar&foo=baz#this_is_fragment")) {
if(!validateDoiUrl("http://www.example.com/url/?foo=bar&foo=baz#this_is_fragment", "https://www.example.com/url?foo=bar&foo=baz#this_is_fragment")) {
t.Errorf("validateDoiUrl should return false")
}
}

// Test checkDoiExistsInDataCite
func TestCheckDoiExistsInDataCite(t *testing.T) {
client := &http.Client{}

// Check if the DOI exists in DataCite
err := checkDoiExistsInDataCite("10.70102/mdc.jeopardy", "https://demorepo.stage.datacite.org/datasets/10.70102/mdc.jeopardy", "https://api.stage.datacite.org", client)


// Check if the error is nil
if err != nil {
t.Errorf("checkDoiExistsInDataCite should return nil")
}
}

0 comments on commit d71037c

Please sign in to comment.