newsbox/actions/users.go
Adriano Caloiaro 8ae801ae5f
Initial commit
2023-02-15 08:57:48 -08:00

102 lines
2.4 KiB
Go

package actions
import (
"encoding/json"
"fmt"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop/v6"
"github.com/pkg/errors"
"newsbox/internal"
"newsbox/mill"
"newsbox/models"
"newsbox/workers"
)
// UsersNew renders the users form
func UsersNew(c buffalo.Context) error {
u := models.User{}
c.Set("user", u)
return c.Render(200, r.HTML("users/new.plush.html"))
}
// UsersCreate registers a new user with the application.
func UsersCreate(c buffalo.Context) error {
u := &models.User{}
if err := c.Bind(u); err != nil {
return errors.WithStack(err)
}
tx := c.Value("tx").(*pop.Connection)
verrs, err := u.Create(tx)
if err != nil {
return errors.WithStack(err)
}
if verrs.HasAny() {
c.Set("user", u)
c.Set("errors", verrs)
return c.Render(200, r.HTML("users/new.plush.html"))
}
uev := &models.UserEmailVerification{OwnerID: u.ID}
err = tx.Save(uev)
if err != nil {
return errors.WithStack(err)
}
invitationAddr := u.Email.Interface().(string)
params := mill.WelcomeEmailJob{
Recipient: invitationAddr,
VerificationURL: fmt.Sprintf("%s/users/email_verification/%s", internal.BaseUrl(), uev.ID),
}
paramsJSON, _ := json.Marshal(params)
_, err = workers.W.EnqueueJob("welcome_emails", paramsJSON)
if err != nil {
c.Redirect(302, "/")
return err
}
c.Flash().Add("success", fmt.Sprintf("Email verification sent to: %s", invitationAddr))
return c.Redirect(302, "/")
}
// SetCurrentUser attempts to find a user based on the current_user_id
// in the session. If one is found it is set on the context.
func SetCurrentUser(next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
if uid := c.Session().Get("current_user_id"); uid != nil {
u := &models.User{}
tx := c.Value("tx").(*pop.Connection)
err := tx.Find(u, uid)
if err != nil {
c.Session().Set("current_user_id", nil)
return next(c)
} else {
c.Set("current_user", u)
}
}
return next(c)
}
}
// Authorize require a user be logged in before accessing a route
func Authorize(next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
if uid := c.Session().Get("current_user_id"); uid == nil {
c.Session().Set("redirectURL", c.Request().URL.String())
err := c.Session().Save()
if err != nil {
return errors.WithStack(err)
}
c.Flash().Add("danger", "You must be authorized to see that page")
return c.Redirect(302, "/login")
}
return next(c)
}
}