sanitize email address before saving to datastore

This commit is contained in:
Danny van Kooten 2018-09-10 09:26:15 +02:00
parent 20f79b5b97
commit 3b721b88a8
3 changed files with 27 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"net/http" "net/http"
"strings"
gcontext "github.com/gorilla/context" gcontext "github.com/gorilla/context"
"github.com/usefathom/fathom/pkg/datastore" "github.com/usefathom/fathom/pkg/datastore"
@ -20,6 +21,10 @@ type login struct {
Password string `json:"password"` Password string `json:"password"`
} }
func (l *login) Sanitize() {
l.Email = strings.ToLower(strings.TrimSpace(l.Email))
}
// URL: POST /api/session // URL: POST /api/session
func (api *API) LoginHandler(w http.ResponseWriter, r *http.Request) error { func (api *API) LoginHandler(w http.ResponseWriter, r *http.Request) error {
// check login creds // check login creds
@ -28,6 +33,7 @@ func (api *API) LoginHandler(w http.ResponseWriter, r *http.Request) error {
if err != nil { if err != nil {
return err return err
} }
l.Sanitize()
// find user with given email // find user with given email
u, err := api.database.GetUserByEmail(l.Email) u, err := api.database.GetUserByEmail(l.Email)

15
pkg/api/auth_test.go Normal file
View File

@ -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)
}
}

View File

@ -1,6 +1,8 @@
package models package models
import ( import (
"strings"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
@ -10,19 +12,22 @@ type User struct {
Password string `json:"-"` Password string `json:"-"`
} }
// NewUser creates a new User with the given email and password
func NewUser(e string, pwd string) User { func NewUser(e string, pwd string) User {
u := User{ u := User{
Email: e, Email: strings.ToLower(strings.TrimSpace(e)),
} }
u.SetPassword(pwd) u.SetPassword(pwd)
return u return u
} }
// SetPassword sets a brcrypt encrypted password from the given plaintext pwd
func (u *User) SetPassword(pwd string) { func (u *User) SetPassword(pwd string) {
hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
u.Password = string(hash) u.Password = string(hash)
} }
// ComparePassword returns true when the given plaintext password matches the encrypted pwd
func (u *User) ComparePassword(pwd string) error { func (u *User) ComparePassword(pwd string) error {
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pwd)) return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pwd))
} }