From 3b721b88a854dc9229655c95014fcfe376b8fff1 Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Mon, 10 Sep 2018 09:26:15 +0200 Subject: [PATCH] sanitize email address before saving to datastore --- pkg/api/auth.go | 6 ++++++ pkg/api/auth_test.go | 15 +++++++++++++++ pkg/models/user.go | 7 ++++++- 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 pkg/api/auth_test.go diff --git a/pkg/api/auth.go b/pkg/api/auth.go index 062e1bc..1921c8c 100644 --- a/pkg/api/auth.go +++ b/pkg/api/auth.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "net/http" + "strings" gcontext "github.com/gorilla/context" "github.com/usefathom/fathom/pkg/datastore" @@ -20,6 +21,10 @@ type login struct { Password string `json:"password"` } +func (l *login) Sanitize() { + l.Email = strings.ToLower(strings.TrimSpace(l.Email)) +} + // URL: POST /api/session func (api *API) LoginHandler(w http.ResponseWriter, r *http.Request) error { // check login creds @@ -28,6 +33,7 @@ func (api *API) LoginHandler(w http.ResponseWriter, r *http.Request) error { if err != nil { return err } + l.Sanitize() // find user with given email u, err := api.database.GetUserByEmail(l.Email) diff --git a/pkg/api/auth_test.go b/pkg/api/auth_test.go new file mode 100644 index 0000000..aa6e0bf --- /dev/null +++ b/pkg/api/auth_test.go @@ -0,0 +1,15 @@ +package api + +import "testing" + +func TestLoginSanitize(t *testing.T) { + rawEmail := "Foo@foobar.com " + l := &login{ + Email: rawEmail, + } + + l.Sanitize() + if l.Email != "foo@foobar.com" { + t.Errorf("Expected normalized email address, got %s", l.Email) + } +} diff --git a/pkg/models/user.go b/pkg/models/user.go index 9347052..5bc2ec9 100644 --- a/pkg/models/user.go +++ b/pkg/models/user.go @@ -1,6 +1,8 @@ package models import ( + "strings" + "golang.org/x/crypto/bcrypt" ) @@ -10,19 +12,22 @@ type User struct { Password string `json:"-"` } +// NewUser creates a new User with the given email and password func NewUser(e string, pwd string) User { u := User{ - Email: e, + Email: strings.ToLower(strings.TrimSpace(e)), } u.SetPassword(pwd) return u } +// SetPassword sets a brcrypt encrypted password from the given plaintext pwd func (u *User) SetPassword(pwd string) { hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) u.Password = string(hash) } +// ComparePassword returns true when the given plaintext password matches the encrypted pwd func (u *User) ComparePassword(pwd string) error { return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pwd)) }