newsbox/actions/users.go
2023-02-15 11:51:54 -08:00

103 lines
2.4 KiB
Go

package actions
import (
"fmt"
"github.com/acaloiaro/neoq"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop/v6"
"github.com/pkg/errors"
"newsbox/internal"
"newsbox/models"
)
// 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)
welcomeEmailJob := neoq.Job{
Queue: "welcome_emails",
Payload: map[string]any{
"recipient": invitationAddr,
"verification_url": fmt.Sprintf("%s/users/email_verification/%s", internal.BaseUrl(), uev.ID),
},
}
nq, _ := neoq.New(internal.DatabaseUrl())
_, err = nq.Enqueue(welcomeEmailJob)
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)
}
}