saasitone/controllers/register.go

73 lines
1.5 KiB
Go
Raw Normal View History

2021-12-03 13:35:11 -08:00
package controllers
import (
"goweb/msg"
"golang.org/x/crypto/bcrypt"
2021-12-03 13:35:11 -08:00
"github.com/labstack/echo/v4"
)
type (
Register struct {
Controller
form RegisterForm
}
RegisterForm struct {
Username string `form:"username" validate:"required"`
Password string `form:"password" validate:"required"`
}
)
2021-12-03 13:35:11 -08:00
func (r *Register) Get(c echo.Context) error {
p := NewPage(c)
p.Layout = "auth"
p.Name = "register"
p.Title = "Register"
p.Data = r.form
2021-12-03 13:35:11 -08:00
return r.RenderPage(c, p)
}
func (r *Register) Post(c echo.Context) error {
fail := func(message string, err error) error {
c.Logger().Errorf("%s: %v", message, err)
msg.Danger(c, "An error occurred. Please try again.")
return r.Get(c)
}
// Parse the form values
form := new(RegisterForm)
if err := c.Bind(form); err != nil {
return fail("unable to parse form values", err)
}
r.form = *form
// Validate the form
if err := c.Validate(form); err != nil {
msg.Danger(c, "All fields are required.")
return r.Get(c)
}
// Hash the password
pwHash, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)
if err != nil {
return fail("unable to hash password", err)
}
// Attempt creating the user
2021-12-11 10:18:32 -08:00
u, err := r.Container.ORM.User.
2021-12-10 17:44:23 -08:00
Create().
SetUsername(form.Username).
SetPassword(string(pwHash)).
2021-12-10 17:44:23 -08:00
Save(c.Request().Context())
if err != nil {
return fail("unable to create user", err)
2021-12-10 17:44:23 -08:00
}
c.Logger().Infof("user created: %s", u.Username)
msg.Info(c, "Your account has been created. You are now logged in.")
return r.Redirect(c, "home")
2021-12-03 13:35:11 -08:00
}