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