summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2020-04-11 16:28:40 +0530
committerAndinus <andinus@nand.sh>2020-04-11 16:28:40 +0530
commit0ef35cae1a385f26f3d5a0ad6306b09d1fed3abd (patch)
treee757df8dd534fb9852a2a16a7a0f6e55438af8fe
parenta9de3eef47cac76791574444380d3cd993d34e1e (diff)
downloadorion-0ef35cae1a385f26f3d5a0ad6306b09d1fed3abd.tar.gz
Return better errors in hibp package
-rw-r--r--hibp/hash.go4
-rw-r--r--hibp/req.go39
2 files changed, 32 insertions, 11 deletions
diff --git a/hibp/hash.go b/hibp/hash.go
index 25249ed..9b8d35c 100644
--- a/hibp/hash.go
+++ b/hibp/hash.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 )
 
-// GetHsh takes a string as an input & returns SHA-1 Hash
-func GetHsh(pass string) string {
+// GetSHA1Hash takes a string as an input & returns SHA-1 Hash
+func GetSHA1Hash(pass string) string {
 	alg := sha1.New()
 	alg.Write([]byte(pass))
 
diff --git a/hibp/req.go b/hibp/req.go
index a3085da..8081d3c 100644
--- a/hibp/req.go
+++ b/hibp/req.go
@@ -4,32 +4,53 @@ import (
 	"fmt"
 	"io/ioutil"
 	"net/http"
+	"time"
 )
 
-func reqHIBP(reqApi string) (string, error) {
+func reqHIBP(reqApi string) (body string, err error) {
+	c := http.Client{
+		// TODO: timeout should be configurable by the user
+		Timeout: time.Second * 64,
+	}
+
 	req, err := http.NewRequest(http.MethodGet, reqApi, nil)
 	if err != nil {
-		return "", fmt.Errorf("request init failed\n%s",
+		err = fmt.Errorf("hibp/req.go: Failed to create request\n%s",
 			err.Error())
+		return
 	}
 
-	c := http.Client{}
+	// User-Agent should be passed with every request to
+	// make work easier for the server handler. Include contact
+	// information along with the project name so they could reach
+	// you if required.
+	req.Header.Set("User-Agent",
+		"Andinus / Orion - https://andinus.nand.sh/orion")
+
 	res, err := c.Do(req)
 	if err != nil {
-		return "", fmt.Errorf("request failed\n%s",
+		err = fmt.Errorf("hibp/req.go: Failed to get response\n%s",
 			err.Error())
+		return
 	}
 	defer res.Body.Close()
 
 	if res.StatusCode != 200 {
-		return "", fmt.Errorf("Unexpected response status code received: %d %s",
-			res.StatusCode, http.StatusText(res.StatusCode))
+		fmt.Errorf("hibp/req.go: Unexpected response status code received: %d %s",
+			res.StatusCode,
+			http.StatusText(res.StatusCode))
+		return
 	}
 
-	body, err := ioutil.ReadAll(res.Body)
+	// This will read everything to memory and is okay to use here
+	// because the response is expected to be small.
+	out, err := ioutil.ReadAll(res.Body)
 	if err != nil {
-		return "", fmt.Errorf("reading res.Body failed\n%s",
+		fmt.Errorf("hibp/req.go: Failed to read res.Body\n%s",
 			err.Error())
+		return
 	}
-	return string(body), err
+
+	body = string(out)
+	return
 }