From a71afaf6b9cbe335dc1bfb41631f0ef3044bd399 Mon Sep 17 00:00:00 2001 From: Jan Bader Date: Tue, 20 Dec 2016 15:26:31 +0100 Subject: [PATCH] Implement registration --- bcrypt/verifier.go | 12 ++++++++++++ http/http.go | 28 ++++++++++++++++++++++++++++ templates/register.html | 2 +- user.go | 1 + 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/bcrypt/verifier.go b/bcrypt/verifier.go index e6cf07e..51c84fd 100644 --- a/bcrypt/verifier.go +++ b/bcrypt/verifier.go @@ -1,6 +1,8 @@ package bcrypt import ( + "bytes" + "golang.org/x/crypto/bcrypt" ) @@ -13,3 +15,13 @@ type Verifier struct { func (bv *Verifier) Verify(password string, hashOnDb string) error { return bcrypt.CompareHashAndPassword([]byte(hashOnDb), []byte(password)) } + +// Hash calculates a hash to be stored on the database +func (bv *Verifier) Hash(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bv.cost) + if err != nil { + return "", err + } + idx := bytes.IndexByte(hash, 0) + return string(hash[:idx]), nil +} diff --git a/http/http.go b/http/http.go index 4e07811..7be6299 100644 --- a/http/http.go +++ b/http/http.go @@ -36,6 +36,7 @@ func (h *Handler) Serve() { api.GET("/logout", logout) api.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") }) api.POST("/login", h.loginPost) + api.POST("/register", h.registerPost) // Unauthenticated routes api.GET("/check", func(c *gin.Context) { c.String(http.StatusOK, "Accessible") }) @@ -131,3 +132,30 @@ func (h *Handler) loginPost(c *gin.Context) { "token": t, }) } + +func (h *Handler) registerPost(c *gin.Context) { + username, _ := c.GetPostForm("username") + password, _ := c.GetPostForm("password") + name, _ := c.GetPostForm("name") + + user, err := h.UserService.UserByUsername(username) + if err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + hash, err := h.CredentialsVerifier.Hash(password) + if err != nil { + c.AbortWithStatus(http.StatusUnauthorized) + } + + user = &budgeteer.User{ + Name: name, + Password: hash, + Email: username, + } + err = h.UserService.CreateUser(user) + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + } +} diff --git a/templates/register.html b/templates/register.html index 7272dc0..e0706cc 100644 --- a/templates/register.html +++ b/templates/register.html @@ -47,7 +47,7 @@ Budgeteer
-
+
diff --git a/user.go b/user.go index 7cd5a11..5bf20c3 100644 --- a/user.go +++ b/user.go @@ -20,4 +20,5 @@ type UserService interface { // CredentialVerifier verifies the provided credentials type CredentialVerifier interface { Verify(password string, hashOnDb string) error + Hash(password string) (string, error) }