Migrate from templates to Gomponents (#103)
This commit is contained in:
parent
0bf9ab7189
commit
051d032038
104 changed files with 2768 additions and 2824 deletions
|
|
@ -13,65 +13,25 @@ import (
|
|||
"github.com/mikestefanello/pagoda/pkg/log"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/redirect"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/emails"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/forms"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameForgotPassword = "forgot_password"
|
||||
routeNameForgotPasswordSubmit = "forgot_password.submit"
|
||||
routeNameLogin = "login"
|
||||
routeNameLoginSubmit = "login.submit"
|
||||
routeNameLogout = "logout"
|
||||
routeNameRegister = "register"
|
||||
routeNameRegisterSubmit = "register.submit"
|
||||
routeNameResetPassword = "reset_password"
|
||||
routeNameResetPasswordSubmit = "reset_password.submit"
|
||||
routeNameVerifyEmail = "verify_email"
|
||||
)
|
||||
|
||||
type (
|
||||
Auth struct {
|
||||
auth *services.AuthClient
|
||||
mail *services.MailClient
|
||||
orm *ent.Client
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
forgotPasswordForm struct {
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
form.Submission
|
||||
}
|
||||
|
||||
loginForm struct {
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
Password string `form:"password" validate:"required"`
|
||||
form.Submission
|
||||
}
|
||||
|
||||
registerForm struct {
|
||||
Name string `form:"name" validate:"required"`
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
Password string `form:"password" validate:"required"`
|
||||
ConfirmPassword string `form:"password-confirm" validate:"required,eqfield=Password"`
|
||||
form.Submission
|
||||
}
|
||||
|
||||
resetPasswordForm struct {
|
||||
Password string `form:"password" validate:"required"`
|
||||
ConfirmPassword string `form:"password-confirm" validate:"required,eqfield=Password"`
|
||||
form.Submission
|
||||
}
|
||||
)
|
||||
type Auth struct {
|
||||
auth *services.AuthClient
|
||||
mail *services.MailClient
|
||||
orm *ent.Client
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(new(Auth))
|
||||
}
|
||||
|
||||
func (h *Auth) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
h.orm = c.ORM
|
||||
h.auth = c.Auth
|
||||
h.mail = c.Mail
|
||||
|
|
@ -79,37 +39,31 @@ func (h *Auth) Init(c *services.Container) error {
|
|||
}
|
||||
|
||||
func (h *Auth) Routes(g *echo.Group) {
|
||||
g.GET("/logout", h.Logout, middleware.RequireAuthentication()).Name = routeNameLogout
|
||||
g.GET("/email/verify/:token", h.VerifyEmail).Name = routeNameVerifyEmail
|
||||
g.GET("/logout", h.Logout, middleware.RequireAuthentication()).Name = routenames.Logout
|
||||
g.GET("/email/verify/:token", h.VerifyEmail).Name = routenames.VerifyEmail
|
||||
|
||||
noAuth := g.Group("/user", middleware.RequireNoAuthentication())
|
||||
noAuth.GET("/login", h.LoginPage).Name = routeNameLogin
|
||||
noAuth.POST("/login", h.LoginSubmit).Name = routeNameLoginSubmit
|
||||
noAuth.GET("/register", h.RegisterPage).Name = routeNameRegister
|
||||
noAuth.POST("/register", h.RegisterSubmit).Name = routeNameRegisterSubmit
|
||||
noAuth.GET("/password", h.ForgotPasswordPage).Name = routeNameForgotPassword
|
||||
noAuth.POST("/password", h.ForgotPasswordSubmit).Name = routeNameForgotPasswordSubmit
|
||||
noAuth.GET("/login", h.LoginPage).Name = routenames.Login
|
||||
noAuth.POST("/login", h.LoginSubmit).Name = routenames.LoginSubmit
|
||||
noAuth.GET("/register", h.RegisterPage).Name = routenames.Register
|
||||
noAuth.POST("/register", h.RegisterSubmit).Name = routenames.RegisterSubmit
|
||||
noAuth.GET("/password", h.ForgotPasswordPage).Name = routenames.ForgotPassword
|
||||
noAuth.POST("/password", h.ForgotPasswordSubmit).Name = routenames.ForgotPasswordSubmit
|
||||
|
||||
resetGroup := noAuth.Group("/password/reset",
|
||||
middleware.LoadUser(h.orm),
|
||||
middleware.LoadValidPasswordToken(h.auth),
|
||||
)
|
||||
resetGroup.GET("/token/:user/:password_token/:token", h.ResetPasswordPage).Name = routeNameResetPassword
|
||||
resetGroup.POST("/token/:user/:password_token/:token", h.ResetPasswordSubmit).Name = routeNameResetPasswordSubmit
|
||||
resetGroup.GET("/token/:user/:password_token/:token", h.ResetPasswordPage).Name = routenames.ResetPassword
|
||||
resetGroup.POST("/token/:user/:password_token/:token", h.ResetPasswordSubmit).Name = routenames.ResetPasswordSubmit
|
||||
}
|
||||
|
||||
func (h *Auth) ForgotPasswordPage(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutAuth
|
||||
p.Name = templates.PageForgotPassword
|
||||
p.Title = "Forgot password"
|
||||
p.Form = form.Get[forgotPasswordForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.ForgotPassword(ctx, form.Get[forms.ForgotPassword](ctx))
|
||||
}
|
||||
|
||||
func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
||||
var input forgotPasswordForm
|
||||
var input forms.ForgotPassword
|
||||
|
||||
succeed := func() error {
|
||||
form.Clear(ctx)
|
||||
|
|
@ -127,7 +81,7 @@ func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Attempt to load the user
|
||||
// Attempt to load the user.
|
||||
u, err := h.orm.User.
|
||||
Query().
|
||||
Where(user.Email(strings.ToLower(input.Email))).
|
||||
|
|
@ -141,7 +95,7 @@ func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
|||
return fail(err, "error querying user during forgot password")
|
||||
}
|
||||
|
||||
// Generate the token
|
||||
// Generate the token.
|
||||
token, pt, err := h.auth.GeneratePasswordResetToken(ctx, u.ID)
|
||||
if err != nil {
|
||||
return fail(err, "error generating password reset token")
|
||||
|
|
@ -151,8 +105,8 @@ func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
|||
"user_id", u.ID,
|
||||
)
|
||||
|
||||
// Email the user
|
||||
url := ctx.Echo().Reverse(routeNameResetPassword, u.ID, pt.ID, token)
|
||||
// Email the user.
|
||||
url := ctx.Echo().Reverse(routenames.ResetPassword, u.ID, pt.ID, token)
|
||||
err = h.mail.
|
||||
Compose().
|
||||
To(u.Email).
|
||||
|
|
@ -168,17 +122,11 @@ func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
|||
}
|
||||
|
||||
func (h *Auth) LoginPage(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutAuth
|
||||
p.Name = templates.PageLogin
|
||||
p.Title = "Log in"
|
||||
p.Form = form.Get[loginForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.Login(ctx, form.Get[forms.Login](ctx))
|
||||
}
|
||||
|
||||
func (h *Auth) LoginSubmit(ctx echo.Context) error {
|
||||
var input loginForm
|
||||
var input forms.Login
|
||||
|
||||
authFailed := func() error {
|
||||
input.SetFieldError("Email", "")
|
||||
|
|
@ -197,7 +145,7 @@ func (h *Auth) LoginSubmit(ctx echo.Context) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Attempt to load the user
|
||||
// Attempt to load the user.
|
||||
u, err := h.orm.User.
|
||||
Query().
|
||||
Where(user.Email(strings.ToLower(input.Email))).
|
||||
|
|
@ -211,22 +159,22 @@ func (h *Auth) LoginSubmit(ctx echo.Context) error {
|
|||
return fail(err, "error querying user during login")
|
||||
}
|
||||
|
||||
// Check if the password is correct
|
||||
// Check if the password is correct.
|
||||
err = h.auth.CheckPassword(input.Password, u.Password)
|
||||
if err != nil {
|
||||
return authFailed()
|
||||
}
|
||||
|
||||
// Log the user in
|
||||
// Log the user in.
|
||||
err = h.auth.Login(ctx, u.ID)
|
||||
if err != nil {
|
||||
return fail(err, "unable to log in user")
|
||||
}
|
||||
|
||||
msg.Success(ctx, fmt.Sprintf("Welcome back, <strong>%s</strong>. You are now logged in.", u.Name))
|
||||
msg.Success(ctx, fmt.Sprintf("Welcome back, %s. You are now logged in.", u.Name))
|
||||
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameHome).
|
||||
Route(routenames.Home).
|
||||
Go()
|
||||
}
|
||||
|
||||
|
|
@ -237,22 +185,16 @@ func (h *Auth) Logout(ctx echo.Context) error {
|
|||
msg.Danger(ctx, "An error occurred. Please try again.")
|
||||
}
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameHome).
|
||||
Route(routenames.Home).
|
||||
Go()
|
||||
}
|
||||
|
||||
func (h *Auth) RegisterPage(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutAuth
|
||||
p.Name = templates.PageRegister
|
||||
p.Title = "Register"
|
||||
p.Form = form.Get[registerForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.Register(ctx, form.Get[forms.Register](ctx))
|
||||
}
|
||||
|
||||
func (h *Auth) RegisterSubmit(ctx echo.Context) error {
|
||||
var input registerForm
|
||||
var input forms.Register
|
||||
|
||||
err := form.Submit(ctx, &input)
|
||||
|
||||
|
|
@ -264,13 +206,13 @@ func (h *Auth) RegisterSubmit(ctx echo.Context) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
// Hash the password.
|
||||
pwHash, err := h.auth.HashPassword(input.Password)
|
||||
if err != nil {
|
||||
return fail(err, "unable to hash password")
|
||||
}
|
||||
|
||||
// Attempt creating the user
|
||||
// Attempt creating the user.
|
||||
u, err := h.orm.User.
|
||||
Create().
|
||||
SetName(input.Name).
|
||||
|
|
@ -287,13 +229,13 @@ func (h *Auth) RegisterSubmit(ctx echo.Context) error {
|
|||
case *ent.ConstraintError:
|
||||
msg.Warning(ctx, "A user with this email address already exists. Please log in.")
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameLogin).
|
||||
Route(routenames.Login).
|
||||
Go()
|
||||
default:
|
||||
return fail(err, "unable to create user")
|
||||
}
|
||||
|
||||
// Log the user in
|
||||
// Log the user in.
|
||||
err = h.auth.Login(ctx, u.ID)
|
||||
if err != nil {
|
||||
log.Ctx(ctx).Error("unable to log user in",
|
||||
|
|
@ -302,22 +244,22 @@ func (h *Auth) RegisterSubmit(ctx echo.Context) error {
|
|||
)
|
||||
msg.Info(ctx, "Your account has been created.")
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameLogin).
|
||||
Route(routenames.Login).
|
||||
Go()
|
||||
}
|
||||
|
||||
msg.Success(ctx, "Your account has been created. You are now logged in.")
|
||||
|
||||
// Send the verification email
|
||||
// Send the verification email.
|
||||
h.sendVerificationEmail(ctx, u)
|
||||
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameHome).
|
||||
Route(routenames.Home).
|
||||
Go()
|
||||
}
|
||||
|
||||
func (h *Auth) sendVerificationEmail(ctx echo.Context, usr *ent.User) {
|
||||
// Generate a token
|
||||
// Generate a token.
|
||||
token, err := h.auth.GenerateEmailVerificationToken(usr.Email)
|
||||
if err != nil {
|
||||
log.Ctx(ctx).Error("unable to generate email verification token",
|
||||
|
|
@ -327,13 +269,12 @@ func (h *Auth) sendVerificationEmail(ctx echo.Context, usr *ent.User) {
|
|||
return
|
||||
}
|
||||
|
||||
// Send the email
|
||||
url := ctx.Echo().Reverse(routeNameVerifyEmail, token)
|
||||
// Send the email.
|
||||
err = h.mail.
|
||||
Compose().
|
||||
To(usr.Email).
|
||||
Subject("Confirm your email address").
|
||||
Body(fmt.Sprintf("Click here to confirm your email address: %s", url)).
|
||||
Component(emails.ConfirmEmailAddress(ctx, usr.Name, token)).
|
||||
Send(ctx)
|
||||
|
||||
if err != nil {
|
||||
|
|
@ -348,17 +289,11 @@ func (h *Auth) sendVerificationEmail(ctx echo.Context, usr *ent.User) {
|
|||
}
|
||||
|
||||
func (h *Auth) ResetPasswordPage(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutAuth
|
||||
p.Name = templates.PageResetPassword
|
||||
p.Title = "Reset password"
|
||||
p.Form = form.Get[resetPasswordForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.ResetPassword(ctx, form.Get[forms.ResetPassword](ctx))
|
||||
}
|
||||
|
||||
func (h *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
||||
var input resetPasswordForm
|
||||
var input forms.ResetPassword
|
||||
|
||||
err := form.Submit(ctx, &input)
|
||||
|
||||
|
|
@ -370,16 +305,16 @@ func (h *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Hash the new password
|
||||
// Hash the new password.
|
||||
hash, err := h.auth.HashPassword(input.Password)
|
||||
if err != nil {
|
||||
return fail(err, "unable to hash password")
|
||||
}
|
||||
|
||||
// Get the requesting user
|
||||
// Get the requesting user.
|
||||
usr := ctx.Get(context.UserKey).(*ent.User)
|
||||
|
||||
// Update the user
|
||||
// Update the user.
|
||||
_, err = usr.
|
||||
Update().
|
||||
SetPassword(hash).
|
||||
|
|
@ -389,7 +324,7 @@ func (h *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
|||
return fail(err, "unable to update password")
|
||||
}
|
||||
|
||||
// Delete all password tokens for this user
|
||||
// Delete all password tokens for this user.
|
||||
err = h.auth.DeletePasswordTokens(ctx, usr.ID)
|
||||
if err != nil {
|
||||
return fail(err, "unable to delete password tokens")
|
||||
|
|
@ -397,24 +332,24 @@ func (h *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
|||
|
||||
msg.Success(ctx, "Your password has been updated.")
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameLogin).
|
||||
Route(routenames.Login).
|
||||
Go()
|
||||
}
|
||||
|
||||
func (h *Auth) VerifyEmail(ctx echo.Context) error {
|
||||
var usr *ent.User
|
||||
|
||||
// Validate the token
|
||||
// Validate the token.
|
||||
token := ctx.Param("token")
|
||||
email, err := h.auth.ValidateEmailVerificationToken(token)
|
||||
if err != nil {
|
||||
msg.Warning(ctx, "The link is either invalid or has expired.")
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameHome).
|
||||
Route(routenames.Home).
|
||||
Go()
|
||||
}
|
||||
|
||||
// Check if it matches the authenticated user
|
||||
// Check if it matches the authenticated user.
|
||||
if u := ctx.Get(context.AuthenticatedUserKey); u != nil {
|
||||
authUser := u.(*ent.User)
|
||||
|
||||
|
|
@ -423,7 +358,7 @@ func (h *Auth) VerifyEmail(ctx echo.Context) error {
|
|||
}
|
||||
}
|
||||
|
||||
// Query to find a matching user, if needed
|
||||
// Query to find a matching user, if needed.
|
||||
if usr == nil {
|
||||
usr, err = h.orm.User.
|
||||
Query().
|
||||
|
|
@ -435,7 +370,7 @@ func (h *Auth) VerifyEmail(ctx echo.Context) error {
|
|||
}
|
||||
}
|
||||
|
||||
// Verify the user, if needed
|
||||
// Verify the user, if needed.
|
||||
if !usr.Verified {
|
||||
usr, err = usr.
|
||||
Update().
|
||||
|
|
@ -449,6 +384,6 @@ func (h *Auth) VerifyEmail(ctx echo.Context) error {
|
|||
|
||||
msg.Success(ctx, "Your email has been successfully verified.")
|
||||
return redirect.New(ctx).
|
||||
Route(routeNameHome).
|
||||
Route(routenames.Home).
|
||||
Go()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,79 +2,63 @@ package handlers
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/form"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"time"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/forms"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameCache = "cache"
|
||||
routeNameCacheSubmit = "cache.submit"
|
||||
)
|
||||
|
||||
type (
|
||||
Cache struct {
|
||||
cache *services.CacheClient
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
cacheForm struct {
|
||||
Value string `form:"value"`
|
||||
form.Submission
|
||||
}
|
||||
)
|
||||
type Cache struct {
|
||||
cache *services.CacheClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(new(Cache))
|
||||
}
|
||||
|
||||
func (h *Cache) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
h.cache = c.Cache
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Cache) Routes(g *echo.Group) {
|
||||
g.GET("/cache", h.Page).Name = routeNameCache
|
||||
g.POST("/cache", h.Submit).Name = routeNameCacheSubmit
|
||||
g.GET("/cache", h.Page).Name = routenames.Cache
|
||||
g.POST("/cache", h.Submit).Name = routenames.CacheSubmit
|
||||
}
|
||||
|
||||
func (h *Cache) Page(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageCache
|
||||
p.Title = "Set a cache entry"
|
||||
p.Form = form.Get[cacheForm](ctx)
|
||||
f := form.Get[forms.Cache](ctx)
|
||||
|
||||
// Fetch the value from the cache
|
||||
// Fetch the value from the cache.
|
||||
value, err := h.cache.
|
||||
Get().
|
||||
Key("page_cache_example").
|
||||
Fetch(ctx.Request().Context())
|
||||
|
||||
// Store the value in the page, so it can be rendered, if found
|
||||
// Store the value in the form, so it can be rendered, if found.
|
||||
switch {
|
||||
case err == nil:
|
||||
p.Data = value.(string)
|
||||
f.CurrentValue = value.(string)
|
||||
case errors.Is(err, services.ErrCacheMiss):
|
||||
default:
|
||||
return fail(err, "failed to fetch from cache")
|
||||
}
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.UpdateCache(ctx, f)
|
||||
}
|
||||
|
||||
func (h *Cache) Submit(ctx echo.Context) error {
|
||||
var input cacheForm
|
||||
var input forms.Cache
|
||||
|
||||
if err := form.Submit(ctx, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Set the cache
|
||||
// Set the cache.
|
||||
err := h.cache.
|
||||
Set().
|
||||
Key("page_cache_example").
|
||||
|
|
|
|||
|
|
@ -2,60 +2,40 @@ package handlers
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/form"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/forms"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameContact = "contact"
|
||||
routeNameContactSubmit = "contact.submit"
|
||||
)
|
||||
|
||||
type (
|
||||
Contact struct {
|
||||
mail *services.MailClient
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
contactForm struct {
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
Department string `form:"department" validate:"required,oneof=sales marketing hr"`
|
||||
Message string `form:"message" validate:"required"`
|
||||
form.Submission
|
||||
}
|
||||
)
|
||||
type Contact struct {
|
||||
mail *services.MailClient
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(new(Contact))
|
||||
}
|
||||
|
||||
func (h *Contact) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
h.mail = c.Mail
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Contact) Routes(g *echo.Group) {
|
||||
g.GET("/contact", h.Page).Name = routeNameContact
|
||||
g.POST("/contact", h.Submit).Name = routeNameContactSubmit
|
||||
g.GET("/contact", h.Page).Name = routenames.Contact
|
||||
g.POST("/contact", h.Submit).Name = routenames.ContactSubmit
|
||||
}
|
||||
|
||||
func (h *Contact) Page(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageContact
|
||||
p.Title = "Contact us"
|
||||
p.Form = form.Get[contactForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.ContactUs(ctx, form.Get[forms.Contact](ctx))
|
||||
}
|
||||
|
||||
func (h *Contact) Submit(ctx echo.Context) error {
|
||||
var input contactForm
|
||||
var input forms.Contact
|
||||
|
||||
err := form.Submit(ctx, &input)
|
||||
|
||||
|
|
|
|||
|
|
@ -6,27 +6,23 @@ import (
|
|||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/log"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
type Error struct{}
|
||||
|
||||
func (e *Error) Page(err error, ctx echo.Context) {
|
||||
if ctx.Response().Committed || context.IsCanceledError(err) {
|
||||
return
|
||||
}
|
||||
|
||||
// Determine the error status code
|
||||
// Determine the error status code.
|
||||
code := http.StatusInternalServerError
|
||||
if he, ok := err.(*echo.HTTPError); ok {
|
||||
code = he.Code
|
||||
}
|
||||
|
||||
// Log the error
|
||||
// Log the error.
|
||||
logger := log.Ctx(ctx)
|
||||
switch {
|
||||
case code >= 500:
|
||||
|
|
@ -35,15 +31,11 @@ func (e *Error) Page(err error, ctx echo.Context) {
|
|||
logger.Warn(err.Error())
|
||||
}
|
||||
|
||||
// Render the error page
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageError
|
||||
p.Title = http.StatusText(code)
|
||||
p.StatusCode = code
|
||||
p.HTMX.Request.Enabled = false
|
||||
// Set the status code.
|
||||
ctx.Response().Status = code
|
||||
|
||||
if err = e.RenderPage(ctx, p); err != nil {
|
||||
// Render the error page.
|
||||
if err = pages.Error(ctx, code); err != nil {
|
||||
log.Ctx(ctx).Error("failed to render error page",
|
||||
"error", err,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -7,69 +7,48 @@ import (
|
|||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/models"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameFiles = "files"
|
||||
routeNameFilesSubmit = "files.submit"
|
||||
)
|
||||
|
||||
type (
|
||||
Files struct {
|
||||
files afero.Fs
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
File struct {
|
||||
Name string
|
||||
Size int64
|
||||
Modified string
|
||||
}
|
||||
)
|
||||
type Files struct {
|
||||
files afero.Fs
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(new(Files))
|
||||
}
|
||||
|
||||
func (h *Files) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
h.files = c.Files
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Files) Routes(g *echo.Group) {
|
||||
g.GET("/files", h.Page).Name = routeNameFiles
|
||||
g.POST("/files", h.Submit).Name = routeNameFilesSubmit
|
||||
g.GET("/files", h.Page).Name = routenames.Files
|
||||
g.POST("/files", h.Submit).Name = routenames.FilesSubmit
|
||||
}
|
||||
|
||||
func (h *Files) Page(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageFiles
|
||||
p.Title = "Upload a file"
|
||||
|
||||
// Send a list of all uploaded files to the template to be rendered.
|
||||
// Compile a list of all uploaded files to be rendered.
|
||||
info, err := afero.ReadDir(h.files, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
files := make([]File, 0)
|
||||
files := make([]*models.File, 0)
|
||||
for _, file := range info {
|
||||
files = append(files, File{
|
||||
files = append(files, &models.File{
|
||||
Name: file.Name(),
|
||||
Size: file.Size(),
|
||||
Modified: file.ModTime().Format(time.DateTime),
|
||||
})
|
||||
}
|
||||
|
||||
p.Data = files
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.UploadFile(ctx, files)
|
||||
}
|
||||
|
||||
func (h *Files) Submit(ctx echo.Context) error {
|
||||
|
|
|
|||
|
|
@ -2,74 +2,46 @@ package handlers
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/pager"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/models"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameAbout = "about"
|
||||
routeNameHome = "home"
|
||||
)
|
||||
|
||||
type (
|
||||
Pages struct {
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
post struct {
|
||||
Title string
|
||||
Body string
|
||||
}
|
||||
|
||||
aboutData struct {
|
||||
ShowCacheWarning bool
|
||||
FrontendTabs []aboutTab
|
||||
BackendTabs []aboutTab
|
||||
}
|
||||
|
||||
aboutTab struct {
|
||||
Title string
|
||||
Body template.HTML
|
||||
}
|
||||
)
|
||||
type Pages struct{}
|
||||
|
||||
func init() {
|
||||
Register(new(Pages))
|
||||
}
|
||||
|
||||
func (h *Pages) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Pages) Routes(g *echo.Group) {
|
||||
g.GET("/", h.Home).Name = routeNameHome
|
||||
g.GET("/about", h.About).Name = routeNameAbout
|
||||
g.GET("/", h.Home).Name = routenames.Home
|
||||
g.GET("/about", h.About).Name = routenames.About
|
||||
}
|
||||
|
||||
func (h *Pages) Home(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageHome
|
||||
p.Metatags.Description = "Welcome to the homepage."
|
||||
p.Metatags.Keywords = []string{"Go", "MVC", "Web", "Software"}
|
||||
p.Pager = page.NewPager(ctx, 4)
|
||||
p.Data = h.fetchPosts(&p.Pager)
|
||||
pgr := pager.NewPager(ctx, 4)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.Home(ctx, &models.Posts{
|
||||
Posts: h.fetchPosts(&pgr),
|
||||
Pager: pgr,
|
||||
})
|
||||
}
|
||||
|
||||
// fetchPosts is an mock example of fetching posts to illustrate how paging works
|
||||
func (h *Pages) fetchPosts(pager *page.Pager) []post {
|
||||
// fetchPosts is a mock example of fetching posts to illustrate how paging works.
|
||||
func (h *Pages) fetchPosts(pager *pager.Pager) []models.Post {
|
||||
pager.SetItems(20)
|
||||
posts := make([]post, 20)
|
||||
posts := make([]models.Post, 20)
|
||||
|
||||
for k := range posts {
|
||||
posts[k] = post{
|
||||
posts[k] = models.Post{
|
||||
Title: fmt.Sprintf("Post example #%d", k+1),
|
||||
Body: fmt.Sprintf("Lorem ipsum example #%d ddolor sit amet, consectetur adipiscing elit. Nam elementum vulputate tristique.", k+1),
|
||||
}
|
||||
|
|
@ -78,44 +50,5 @@ func (h *Pages) fetchPosts(pager *page.Pager) []post {
|
|||
}
|
||||
|
||||
func (h *Pages) About(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageAbout
|
||||
p.Title = "About"
|
||||
|
||||
// This page will be cached!
|
||||
p.Cache.Enabled = true
|
||||
p.Cache.Tags = []string{"page_about", "page:list"}
|
||||
|
||||
// A simple example of how the Data field can contain anything you want to send to the templates
|
||||
// even though you wouldn't normally send markup like this
|
||||
p.Data = aboutData{
|
||||
ShowCacheWarning: true,
|
||||
FrontendTabs: []aboutTab{
|
||||
{
|
||||
Title: "HTMX",
|
||||
Body: template.HTML(`Completes HTML as a hypertext by providing attributes to AJAXify anything and much more. Visit <a href="https://htmx.org/">htmx.org</a> to learn more.`),
|
||||
},
|
||||
{
|
||||
Title: "Alpine.js",
|
||||
Body: template.HTML(`Drop-in, Vue-like functionality written directly in your markup. Visit <a href="https://alpinejs.dev/">alpinejs.dev</a> to learn more.`),
|
||||
},
|
||||
{
|
||||
Title: "Bulma",
|
||||
Body: template.HTML(`Ready-to-use frontend components that you can easily combine to build responsive web interfaces with no JavaScript requirements. Visit <a href="https://bulma.io/">bulma.io</a> to learn more.`),
|
||||
},
|
||||
},
|
||||
BackendTabs: []aboutTab{
|
||||
{
|
||||
Title: "Echo",
|
||||
Body: template.HTML(`High performance, extensible, minimalist Go web framework. Visit <a href="https://echo.labstack.com/">echo.labstack.com</a> to learn more.`),
|
||||
},
|
||||
{
|
||||
Title: "Ent",
|
||||
Body: template.HTML(`Simple, yet powerful ORM for modeling and querying data. Visit <a href="https://entgo.io/">entgo.io</a> to learn more.`),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.About(ctx)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
|
|
@ -11,7 +12,7 @@ import (
|
|||
// this test package
|
||||
func TestPages__About(t *testing.T) {
|
||||
doc := request(t).
|
||||
setRoute(routeNameAbout).
|
||||
setRoute(routenames.About).
|
||||
get().
|
||||
assertStatusCode(http.StatusOK).
|
||||
toDoc()
|
||||
|
|
|
|||
|
|
@ -6,27 +6,28 @@ import (
|
|||
"github.com/gorilla/sessions"
|
||||
echomw "github.com/labstack/echo/v4/middleware"
|
||||
"github.com/mikestefanello/pagoda/config"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
)
|
||||
|
||||
// BuildRouter builds the router
|
||||
// BuildRouter builds the router.
|
||||
func BuildRouter(c *services.Container) error {
|
||||
// Static files with proper cache control
|
||||
// funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
|
||||
// after each server restart
|
||||
// Static files with proper cache control.
|
||||
// ui.File() should be used in ui components to append a cache key to the URL in order to break cache
|
||||
// after each server restart.
|
||||
c.Web.Group("", middleware.CacheControl(c.Config.Cache.Expiration.StaticFile)).
|
||||
Static(config.StaticPrefix, config.StaticDir)
|
||||
|
||||
// Non-static file route group
|
||||
// Non-static file route group.
|
||||
g := c.Web.Group("")
|
||||
|
||||
// Force HTTPS, if enabled
|
||||
// Force HTTPS, if enabled.
|
||||
if c.Config.HTTP.TLS.Enabled {
|
||||
g.Use(echomw.HTTPSRedirect())
|
||||
}
|
||||
|
||||
// Create a cookie store for session data
|
||||
// Create a cookie store for session data.
|
||||
cookieStore := sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))
|
||||
cookieStore.Options.HttpOnly = true
|
||||
cookieStore.Options.Secure = true
|
||||
|
|
@ -45,22 +46,22 @@ func BuildRouter(c *services.Container) error {
|
|||
echomw.TimeoutWithConfig(echomw.TimeoutConfig{
|
||||
Timeout: c.Config.App.Timeout,
|
||||
}),
|
||||
middleware.Config(c.Config),
|
||||
middleware.Session(cookieStore),
|
||||
middleware.LoadAuthenticatedUser(c.Auth),
|
||||
middleware.ServeCachedPage(c.TemplateRenderer),
|
||||
echomw.CSRFWithConfig(echomw.CSRFConfig{
|
||||
TokenLookup: "form:csrf",
|
||||
CookieHTTPOnly: true,
|
||||
CookieSecure: true,
|
||||
CookieSameSite: http.SameSiteStrictMode,
|
||||
ContextKey: context.CSRFKey,
|
||||
}),
|
||||
)
|
||||
|
||||
// Error handler
|
||||
err := Error{c.TemplateRenderer}
|
||||
c.Web.HTTPErrorHandler = err.Page
|
||||
// Error handler.
|
||||
c.Web.HTTPErrorHandler = new(Error).Page
|
||||
|
||||
// Initialize and register all handlers
|
||||
// Initialize and register all handlers.
|
||||
for _, h := range GetHandlers() {
|
||||
if err := h.Init(c); err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -5,56 +5,40 @@ import (
|
|||
"math/rand"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/models"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
)
|
||||
|
||||
const routeNameSearch = "search"
|
||||
|
||||
type (
|
||||
Search struct {
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
searchResult struct {
|
||||
Title string
|
||||
URL string
|
||||
}
|
||||
)
|
||||
type Search struct{}
|
||||
|
||||
func init() {
|
||||
Register(new(Search))
|
||||
}
|
||||
|
||||
func (h *Search) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Search) Routes(g *echo.Group) {
|
||||
g.GET("/search", h.Page).Name = routeNameSearch
|
||||
g.GET("/search", h.Page).Name = routenames.Search
|
||||
}
|
||||
|
||||
func (h *Search) Page(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageSearch
|
||||
|
||||
// Fake search results
|
||||
var results []searchResult
|
||||
// Fake search results.
|
||||
results := make([]*models.SearchResult, 0, 5)
|
||||
if search := ctx.QueryParam("query"); search != "" {
|
||||
for i := 0; i < 5; i++ {
|
||||
title := "Lorem ipsum example ddolor sit amet"
|
||||
index := rand.Intn(len(title))
|
||||
title = title[:index] + search + title[index:]
|
||||
results = append(results, searchResult{
|
||||
results = append(results, &models.SearchResult{
|
||||
Title: title,
|
||||
URL: fmt.Sprintf("https://www.%s.com", search),
|
||||
})
|
||||
}
|
||||
}
|
||||
p.Data = results
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.SearchResults(ctx, results)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,64 +2,45 @@ package handlers
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/mikestefanello/backlite"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"time"
|
||||
"github.com/mikestefanello/pagoda/pkg/routenames"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/forms"
|
||||
"github.com/mikestefanello/pagoda/pkg/ui/pages"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/form"
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/pkg/tasks"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameTask = "task"
|
||||
routeNameTaskSubmit = "task.submit"
|
||||
)
|
||||
|
||||
type (
|
||||
Task struct {
|
||||
tasks *backlite.Client
|
||||
*services.TemplateRenderer
|
||||
}
|
||||
|
||||
taskForm struct {
|
||||
Delay int `form:"delay" validate:"gte=0"`
|
||||
Message string `form:"message" validate:"required"`
|
||||
form.Submission
|
||||
}
|
||||
)
|
||||
type Task struct {
|
||||
tasks *backlite.Client
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(new(Task))
|
||||
}
|
||||
|
||||
func (h *Task) Init(c *services.Container) error {
|
||||
h.TemplateRenderer = c.TemplateRenderer
|
||||
h.tasks = c.Tasks
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Task) Routes(g *echo.Group) {
|
||||
g.GET("/task", h.Page).Name = routeNameTask
|
||||
g.POST("/task", h.Submit).Name = routeNameTaskSubmit
|
||||
g.GET("/task", h.Page).Name = routenames.Task
|
||||
g.POST("/task", h.Submit).Name = routenames.TaskSubmit
|
||||
}
|
||||
|
||||
func (h *Task) Page(ctx echo.Context) error {
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutMain
|
||||
p.Name = templates.PageTask
|
||||
p.Title = "Create a task"
|
||||
p.Form = form.Get[taskForm](ctx)
|
||||
|
||||
return h.RenderPage(ctx, p)
|
||||
return pages.AddTask(ctx, form.Get[forms.Task](ctx))
|
||||
}
|
||||
|
||||
func (h *Task) Submit(ctx echo.Context) error {
|
||||
var input taskForm
|
||||
var input forms.Task
|
||||
|
||||
err := form.Submit(ctx, &input)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue