Switch from routes to self-registering handlers to group related routes.
This commit is contained in:
parent
8ca11c90e1
commit
59c10f1874
19 changed files with 719 additions and 717 deletions
451
pkg/handlers/auth.go
Normal file
451
pkg/handlers/auth.go
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/ent/user"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
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
|
||||
controller.Controller
|
||||
}
|
||||
|
||||
forgotPasswordForm struct {
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
Submission controller.FormSubmission
|
||||
}
|
||||
|
||||
loginForm struct {
|
||||
Email string `form:"email" validate:"required,email"`
|
||||
Password string `form:"password" validate:"required"`
|
||||
Submission controller.FormSubmission
|
||||
}
|
||||
|
||||
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"`
|
||||
Submission controller.FormSubmission
|
||||
}
|
||||
|
||||
resetPasswordForm struct {
|
||||
Password string `form:"password" validate:"required"`
|
||||
ConfirmPassword string `form:"password-confirm" validate:"required,eqfield=Password"`
|
||||
Submission controller.FormSubmission
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register(new(Auth))
|
||||
}
|
||||
|
||||
func (c *Auth) Init(ct *services.Container) error {
|
||||
c.Controller = controller.NewController(ct)
|
||||
c.orm = ct.ORM
|
||||
c.auth = ct.Auth
|
||||
c.mail = ct.Mail
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Auth) Routes(g *echo.Group) {
|
||||
g.GET("/logout", c.Logout, middleware.RequireAuthentication()).Name = routeNameLogout
|
||||
g.GET("/email/verify/:token", c.VerifyEmail).Name = routeNameVerifyEmail
|
||||
|
||||
noAuth := g.Group("/user", middleware.RequireNoAuthentication())
|
||||
noAuth.GET("/login", c.LoginPage).Name = routeNameLogin
|
||||
noAuth.POST("/login", c.LoginSubmit).Name = routeNameLoginSubmit
|
||||
noAuth.GET("/register", c.RegisterPage).Name = routeNameRegister
|
||||
noAuth.POST("/register", c.RegisterSubmit).Name = routeNameRegisterSubmit
|
||||
noAuth.GET("/password", c.ForgotPasswordPage).Name = routeNameForgotPassword
|
||||
noAuth.POST("/password", c.ForgotPasswordSubmit).Name = routeNameForgotPasswordSubmit
|
||||
|
||||
resetGroup := noAuth.Group("/password/reset",
|
||||
middleware.LoadUser(c.orm),
|
||||
middleware.LoadValidPasswordToken(c.auth),
|
||||
)
|
||||
resetGroup.GET("/token/:user/:password_token/:token", c.ResetPasswordPage).Name = routeNameResetPassword
|
||||
resetGroup.POST("/token/:user/:password_token/:token", c.ResetPasswordSubmit).Name = routeNameResetPasswordSubmit
|
||||
}
|
||||
|
||||
func (c *Auth) ForgotPasswordPage(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutAuth
|
||||
page.Name = templates.PageForgotPassword
|
||||
page.Title = "Forgot password"
|
||||
page.Form = forgotPasswordForm{}
|
||||
|
||||
if form := ctx.Get(context.FormKey); form != nil {
|
||||
page.Form = form.(*forgotPasswordForm)
|
||||
}
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
func (c *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
||||
var form forgotPasswordForm
|
||||
ctx.Set(context.FormKey, &form)
|
||||
|
||||
succeed := func() error {
|
||||
ctx.Set(context.FormKey, nil)
|
||||
msg.Success(ctx, "An email containing a link to reset your password will be sent to this address if it exists in our system.")
|
||||
return c.ForgotPasswordPage(ctx)
|
||||
}
|
||||
|
||||
// Parse the form values
|
||||
if err := ctx.Bind(&form); err != nil {
|
||||
return c.Fail(err, "unable to parse forgot password form")
|
||||
}
|
||||
|
||||
if err := form.Submission.Process(ctx, form); err != nil {
|
||||
return c.Fail(err, "unable to process form submission")
|
||||
}
|
||||
|
||||
if form.Submission.HasErrors() {
|
||||
return c.ForgotPasswordPage(ctx)
|
||||
}
|
||||
|
||||
// Attempt to load the user
|
||||
u, err := c.orm.User.
|
||||
Query().
|
||||
Where(user.Email(strings.ToLower(form.Email))).
|
||||
Only(ctx.Request().Context())
|
||||
|
||||
switch err.(type) {
|
||||
case *ent.NotFoundError:
|
||||
return succeed()
|
||||
case nil:
|
||||
default:
|
||||
return c.Fail(err, "error querying user during forgot password")
|
||||
}
|
||||
|
||||
// Generate the token
|
||||
token, pt, err := c.auth.GeneratePasswordResetToken(ctx, u.ID)
|
||||
if err != nil {
|
||||
return c.Fail(err, "error generating password reset token")
|
||||
}
|
||||
|
||||
ctx.Logger().Infof("generated password reset token for user %d", u.ID)
|
||||
|
||||
// Email the user
|
||||
url := ctx.Echo().Reverse(routeNameResetPassword, u.ID, pt.ID, token)
|
||||
err = c.mail.
|
||||
Compose().
|
||||
To(u.Email).
|
||||
Subject("Reset your password").
|
||||
Body(fmt.Sprintf("Go here to reset your password: %s", url)).
|
||||
Send(ctx)
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "error sending password reset email")
|
||||
}
|
||||
|
||||
return succeed()
|
||||
}
|
||||
|
||||
func (c *Auth) LoginPage(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutAuth
|
||||
page.Name = templates.PageLogin
|
||||
page.Title = "Log in"
|
||||
page.Form = loginForm{}
|
||||
|
||||
if form := ctx.Get(context.FormKey); form != nil {
|
||||
page.Form = form.(*loginForm)
|
||||
}
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
func (c *Auth) LoginSubmit(ctx echo.Context) error {
|
||||
var form loginForm
|
||||
ctx.Set(context.FormKey, &form)
|
||||
|
||||
authFailed := func() error {
|
||||
form.Submission.SetFieldError("Email", "")
|
||||
form.Submission.SetFieldError("Password", "")
|
||||
msg.Danger(ctx, "Invalid credentials. Please try again.")
|
||||
return c.LoginPage(ctx)
|
||||
}
|
||||
|
||||
// Parse the form values
|
||||
if err := ctx.Bind(&form); err != nil {
|
||||
return c.Fail(err, "unable to parse login form")
|
||||
}
|
||||
|
||||
if err := form.Submission.Process(ctx, form); err != nil {
|
||||
return c.Fail(err, "unable to process form submission")
|
||||
}
|
||||
|
||||
if form.Submission.HasErrors() {
|
||||
return c.LoginPage(ctx)
|
||||
}
|
||||
|
||||
// Attempt to load the user
|
||||
u, err := c.orm.User.
|
||||
Query().
|
||||
Where(user.Email(strings.ToLower(form.Email))).
|
||||
Only(ctx.Request().Context())
|
||||
|
||||
switch err.(type) {
|
||||
case *ent.NotFoundError:
|
||||
return authFailed()
|
||||
case nil:
|
||||
default:
|
||||
return c.Fail(err, "error querying user during login")
|
||||
}
|
||||
|
||||
// Check if the password is correct
|
||||
err = c.auth.CheckPassword(form.Password, u.Password)
|
||||
if err != nil {
|
||||
return authFailed()
|
||||
}
|
||||
|
||||
// Log the user in
|
||||
err = c.auth.Login(ctx, u.ID)
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to log in user")
|
||||
}
|
||||
|
||||
msg.Success(ctx, fmt.Sprintf("Welcome back, <strong>%s</strong>. You are now logged in.", u.Name))
|
||||
return c.Redirect(ctx, routeNameHome)
|
||||
}
|
||||
|
||||
func (c *Auth) Logout(ctx echo.Context) error {
|
||||
if err := c.auth.Logout(ctx); err == nil {
|
||||
msg.Success(ctx, "You have been logged out successfully.")
|
||||
} else {
|
||||
msg.Danger(ctx, "An error occurred. Please try again.")
|
||||
}
|
||||
return c.Redirect(ctx, routeNameHome)
|
||||
}
|
||||
|
||||
func (c *Auth) RegisterPage(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutAuth
|
||||
page.Name = templates.PageRegister
|
||||
page.Title = "Register"
|
||||
page.Form = registerForm{}
|
||||
|
||||
if form := ctx.Get(context.FormKey); form != nil {
|
||||
page.Form = form.(*registerForm)
|
||||
}
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
func (c *Auth) RegisterSubmit(ctx echo.Context) error {
|
||||
var form registerForm
|
||||
ctx.Set(context.FormKey, &form)
|
||||
|
||||
// Parse the form values
|
||||
if err := ctx.Bind(&form); err != nil {
|
||||
return c.Fail(err, "unable to parse register form")
|
||||
}
|
||||
|
||||
if err := form.Submission.Process(ctx, form); err != nil {
|
||||
return c.Fail(err, "unable to process form submission")
|
||||
}
|
||||
|
||||
if form.Submission.HasErrors() {
|
||||
return c.RegisterPage(ctx)
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
pwHash, err := c.auth.HashPassword(form.Password)
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to hash password")
|
||||
}
|
||||
|
||||
// Attempt creating the user
|
||||
u, err := c.orm.User.
|
||||
Create().
|
||||
SetName(form.Name).
|
||||
SetEmail(form.Email).
|
||||
SetPassword(pwHash).
|
||||
Save(ctx.Request().Context())
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
ctx.Logger().Infof("user created: %s", u.Name)
|
||||
case *ent.ConstraintError:
|
||||
msg.Warning(ctx, "A user with this email address already exists. Please log in.")
|
||||
return c.Redirect(ctx, routeNameLogin)
|
||||
default:
|
||||
return c.Fail(err, "unable to create user")
|
||||
}
|
||||
|
||||
// Log the user in
|
||||
err = c.auth.Login(ctx, u.ID)
|
||||
if err != nil {
|
||||
ctx.Logger().Errorf("unable to log in: %v", err)
|
||||
msg.Info(ctx, "Your account has been created.")
|
||||
return c.Redirect(ctx, routeNameLogin)
|
||||
}
|
||||
|
||||
msg.Success(ctx, "Your account has been created. You are now logged in.")
|
||||
|
||||
// Send the verification email
|
||||
c.sendVerificationEmail(ctx, u)
|
||||
|
||||
return c.Redirect(ctx, routeNameHome)
|
||||
}
|
||||
|
||||
func (c *Auth) sendVerificationEmail(ctx echo.Context, usr *ent.User) {
|
||||
// Generate a token
|
||||
token, err := c.auth.GenerateEmailVerificationToken(usr.Email)
|
||||
if err != nil {
|
||||
ctx.Logger().Errorf("unable to generate email verification token: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Send the email
|
||||
url := ctx.Echo().Reverse(routeNameVerifyEmail, token)
|
||||
err = c.mail.
|
||||
Compose().
|
||||
To(usr.Email).
|
||||
Subject("Confirm your email address").
|
||||
Body(fmt.Sprintf("Click here to confirm your email address: %s", url)).
|
||||
Send(ctx)
|
||||
|
||||
if err != nil {
|
||||
ctx.Logger().Errorf("unable to send email verification link: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
msg.Info(ctx, "An email was sent to you to verify your email address.")
|
||||
}
|
||||
|
||||
func (c *Auth) ResetPasswordPage(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutAuth
|
||||
page.Name = templates.PageResetPassword
|
||||
page.Title = "Reset password"
|
||||
page.Form = resetPasswordForm{}
|
||||
|
||||
if form := ctx.Get(context.FormKey); form != nil {
|
||||
page.Form = form.(*resetPasswordForm)
|
||||
}
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
func (c *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
||||
var form resetPasswordForm
|
||||
ctx.Set(context.FormKey, &form)
|
||||
|
||||
// Parse the form values
|
||||
if err := ctx.Bind(&form); err != nil {
|
||||
return c.Fail(err, "unable to parse password reset form")
|
||||
}
|
||||
|
||||
if err := form.Submission.Process(ctx, form); err != nil {
|
||||
return c.Fail(err, "unable to process form submission")
|
||||
}
|
||||
|
||||
if form.Submission.HasErrors() {
|
||||
return c.ResetPasswordPage(ctx)
|
||||
}
|
||||
|
||||
// Hash the new password
|
||||
hash, err := c.auth.HashPassword(form.Password)
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to hash password")
|
||||
}
|
||||
|
||||
// Get the requesting user
|
||||
usr := ctx.Get(context.UserKey).(*ent.User)
|
||||
|
||||
// Update the user
|
||||
_, err = usr.
|
||||
Update().
|
||||
SetPassword(hash).
|
||||
Save(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to update password")
|
||||
}
|
||||
|
||||
// Delete all password tokens for this user
|
||||
err = c.auth.DeletePasswordTokens(ctx, usr.ID)
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to delete password tokens")
|
||||
}
|
||||
|
||||
msg.Success(ctx, "Your password has been updated.")
|
||||
return c.Redirect(ctx, routeNameLogin)
|
||||
}
|
||||
|
||||
func (c *Auth) VerifyEmail(ctx echo.Context) error {
|
||||
var usr *ent.User
|
||||
|
||||
// Validate the token
|
||||
token := ctx.Param("token")
|
||||
email, err := c.auth.ValidateEmailVerificationToken(token)
|
||||
if err != nil {
|
||||
msg.Warning(ctx, "The link is either invalid or has expired.")
|
||||
return c.Redirect(ctx, routeNameHome)
|
||||
}
|
||||
|
||||
// Check if it matches the authenticated user
|
||||
if u := ctx.Get(context.AuthenticatedUserKey); u != nil {
|
||||
authUser := u.(*ent.User)
|
||||
|
||||
if authUser.Email == email {
|
||||
usr = authUser
|
||||
}
|
||||
}
|
||||
|
||||
// Query to find a matching user, if needed
|
||||
if usr == nil {
|
||||
usr, err = c.orm.User.
|
||||
Query().
|
||||
Where(user.Email(email)).
|
||||
Only(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "query failed loading email verification token user")
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the user, if needed
|
||||
if !usr.Verified {
|
||||
usr, err = usr.
|
||||
Update().
|
||||
SetVerified(true).
|
||||
Save(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "failed to set user as verified")
|
||||
}
|
||||
}
|
||||
|
||||
msg.Success(ctx, "Your email has been successfully verified.")
|
||||
return c.Redirect(ctx, routeNameHome)
|
||||
}
|
||||
88
pkg/handlers/contact.go
Normal file
88
pkg/handlers/contact.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameContact = "contact"
|
||||
routeNameContactSubmit = "contact.submit"
|
||||
)
|
||||
|
||||
type (
|
||||
Contact struct {
|
||||
mail *services.MailClient
|
||||
controller.Controller
|
||||
}
|
||||
|
||||
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"`
|
||||
Submission controller.FormSubmission
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register(new(Contact))
|
||||
}
|
||||
|
||||
func (c *Contact) Init(ct *services.Container) error {
|
||||
c.Controller = controller.NewController(ct)
|
||||
c.mail = ct.Mail
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Contact) Routes(g *echo.Group) {
|
||||
g.GET("/contact", c.Page).Name = routeNameContact
|
||||
g.POST("/contact", c.Submit).Name = routeNameContactSubmit
|
||||
}
|
||||
|
||||
func (c *Contact) Page(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutMain
|
||||
page.Name = templates.PageContact
|
||||
page.Title = "Contact us"
|
||||
page.Form = contactForm{}
|
||||
|
||||
if form := ctx.Get(context.FormKey); form != nil {
|
||||
page.Form = form.(*contactForm)
|
||||
}
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
func (c *Contact) Submit(ctx echo.Context) error {
|
||||
var form contactForm
|
||||
ctx.Set(context.FormKey, &form)
|
||||
|
||||
// Parse the form values
|
||||
if err := ctx.Bind(&form); err != nil {
|
||||
return c.Fail(err, "unable to bind form")
|
||||
}
|
||||
|
||||
if err := form.Submission.Process(ctx, form); err != nil {
|
||||
return c.Fail(err, "unable to process form submission")
|
||||
}
|
||||
|
||||
if !form.Submission.HasErrors() {
|
||||
err := c.mail.
|
||||
Compose().
|
||||
To(form.Email).
|
||||
Subject("Contact form submitted").
|
||||
Body(fmt.Sprintf("The message is: %s", form.Message)).
|
||||
Send(ctx)
|
||||
|
||||
if err != nil {
|
||||
return c.Fail(err, "unable to send email")
|
||||
}
|
||||
}
|
||||
|
||||
return c.Page(ctx)
|
||||
}
|
||||
42
pkg/handlers/error.go
Normal file
42
pkg/handlers/error.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
controller.Controller
|
||||
}
|
||||
|
||||
func (e *Error) Page(err error, ctx echo.Context) {
|
||||
if ctx.Response().Committed || context.IsCanceledError(err) {
|
||||
return
|
||||
}
|
||||
|
||||
code := http.StatusInternalServerError
|
||||
if he, ok := err.(*echo.HTTPError); ok {
|
||||
code = he.Code
|
||||
}
|
||||
|
||||
if code >= 500 {
|
||||
ctx.Logger().Error(err)
|
||||
} else {
|
||||
ctx.Logger().Info(err)
|
||||
}
|
||||
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutMain
|
||||
page.Name = templates.PageError
|
||||
page.Title = http.StatusText(code)
|
||||
page.StatusCode = code
|
||||
page.HTMX.Request.Enabled = false
|
||||
|
||||
if err = e.RenderPage(ctx, page); err != nil {
|
||||
ctx.Logger().Error(err)
|
||||
}
|
||||
}
|
||||
27
pkg/handlers/handlers.go
Normal file
27
pkg/handlers/handlers.go
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
)
|
||||
|
||||
var handlers []Handler
|
||||
|
||||
// Handler handles one or more HTTP routes
|
||||
type Handler interface {
|
||||
// Routes allows for self-registration of HTTP routes on the router
|
||||
Routes(g *echo.Group)
|
||||
|
||||
// Init provides the service container to initialize
|
||||
Init(*services.Container) error
|
||||
}
|
||||
|
||||
// Register registers a handler
|
||||
func Register(h Handler) {
|
||||
handlers = append(handlers, h)
|
||||
}
|
||||
|
||||
// GetHandlers returns all handlers
|
||||
func GetHandlers() []Handler {
|
||||
return handlers
|
||||
}
|
||||
121
pkg/handlers/pages.go
Normal file
121
pkg/handlers/pages.go
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
const (
|
||||
routeNameAbout = "about"
|
||||
routeNameHome = "home"
|
||||
)
|
||||
|
||||
type (
|
||||
Pages struct {
|
||||
controller.Controller
|
||||
}
|
||||
|
||||
post struct {
|
||||
Title string
|
||||
Body string
|
||||
}
|
||||
|
||||
aboutData struct {
|
||||
ShowCacheWarning bool
|
||||
FrontendTabs []aboutTab
|
||||
BackendTabs []aboutTab
|
||||
}
|
||||
|
||||
aboutTab struct {
|
||||
Title string
|
||||
Body template.HTML
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register(new(Pages))
|
||||
}
|
||||
|
||||
func (c *Pages) Init(ct *services.Container) error {
|
||||
c.Controller = controller.NewController(ct)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Pages) Routes(g *echo.Group) {
|
||||
g.GET("/", c.Home).Name = routeNameHome
|
||||
g.GET("/about", c.About).Name = routeNameAbout
|
||||
}
|
||||
|
||||
func (c *Pages) Home(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutMain
|
||||
page.Name = templates.PageHome
|
||||
page.Metatags.Description = "Welcome to the homepage."
|
||||
page.Metatags.Keywords = []string{"Go", "MVC", "Web", "Software"}
|
||||
page.Pager = controller.NewPager(ctx, 4)
|
||||
page.Data = c.fetchPosts(&page.Pager)
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
|
||||
// fetchPosts is an mock example of fetching posts to illustrate how paging works
|
||||
func (c *Pages) fetchPosts(pager *controller.Pager) []post {
|
||||
pager.SetItems(20)
|
||||
posts := make([]post, 20)
|
||||
|
||||
for k := range posts {
|
||||
posts[k] = 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),
|
||||
}
|
||||
}
|
||||
return posts[pager.GetOffset() : pager.GetOffset()+pager.ItemsPerPage]
|
||||
}
|
||||
|
||||
func (c *Pages) About(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutMain
|
||||
page.Name = templates.PageAbout
|
||||
page.Title = "About"
|
||||
|
||||
// This page will be cached!
|
||||
page.Cache.Enabled = true
|
||||
page.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
|
||||
page.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 c.RenderPage(ctx, page)
|
||||
}
|
||||
23
pkg/handlers/pages_test.go
Normal file
23
pkg/handlers/pages_test.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Simple example of how to test routes and their markup using the test HTTP server spun up within
|
||||
// this test package
|
||||
func TestPages__About(t *testing.T) {
|
||||
doc := request(t).
|
||||
setRoute(routeNameAbout).
|
||||
get().
|
||||
assertStatusCode(http.StatusOK).
|
||||
toDoc()
|
||||
|
||||
// Goquery is an excellent package to use for testing HTML markup
|
||||
h1 := doc.Find("h1.title")
|
||||
assert.Len(t, h1.Nodes, 1)
|
||||
assert.Equal(t, "About", h1.Text())
|
||||
}
|
||||
66
pkg/handlers/router.go
Normal file
66
pkg/handlers/router.go
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
echomw "github.com/labstack/echo/v4/middleware"
|
||||
"github.com/mikestefanello/pagoda/config"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/pkg/middleware"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
)
|
||||
|
||||
// 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
|
||||
c.Web.Group("", middleware.CacheControl(c.Config.Cache.Expiration.StaticFile)).
|
||||
Static(config.StaticPrefix, config.StaticDir)
|
||||
|
||||
// Non-static file route group
|
||||
g := c.Web.Group("")
|
||||
|
||||
// Force HTTPS, if enabled
|
||||
if c.Config.HTTP.TLS.Enabled {
|
||||
g.Use(echomw.HTTPSRedirect())
|
||||
}
|
||||
|
||||
g.Use(
|
||||
echomw.RemoveTrailingSlashWithConfig(echomw.TrailingSlashConfig{
|
||||
RedirectCode: http.StatusMovedPermanently,
|
||||
}),
|
||||
echomw.Recover(),
|
||||
echomw.Secure(),
|
||||
echomw.RequestID(),
|
||||
echomw.Gzip(),
|
||||
echomw.Logger(),
|
||||
middleware.LogRequestID(),
|
||||
echomw.TimeoutWithConfig(echomw.TimeoutConfig{
|
||||
Timeout: c.Config.App.Timeout,
|
||||
}),
|
||||
session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))),
|
||||
middleware.LoadAuthenticatedUser(c.Auth),
|
||||
middleware.ServeCachedPage(c.Cache),
|
||||
echomw.CSRFWithConfig(echomw.CSRFConfig{
|
||||
TokenLookup: "form:csrf",
|
||||
}),
|
||||
)
|
||||
|
||||
// Error handler
|
||||
err := Error{Controller: controller.NewController(c)}
|
||||
c.Web.HTTPErrorHandler = err.Page
|
||||
|
||||
// Initialize and register all handlers
|
||||
for _, h := range GetHandlers() {
|
||||
if err := h.Init(c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
h.Routes(g)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
138
pkg/handlers/router_test.go
Normal file
138
pkg/handlers/router_test.go
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/mikestefanello/pagoda/config"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var (
|
||||
srv *httptest.Server
|
||||
c *services.Container
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Set the environment to test
|
||||
config.SwitchEnvironment(config.EnvTest)
|
||||
|
||||
// Start a new container
|
||||
c = services.NewContainer()
|
||||
|
||||
// Start a test HTTP server
|
||||
if err := BuildRouter(c); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
srv = httptest.NewServer(c.Web)
|
||||
|
||||
// Run tests
|
||||
exitVal := m.Run()
|
||||
|
||||
// Shutdown the container and test server
|
||||
if err := c.Shutdown(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
srv.Close()
|
||||
|
||||
os.Exit(exitVal)
|
||||
}
|
||||
|
||||
type httpRequest struct {
|
||||
route string
|
||||
client http.Client
|
||||
body url.Values
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func request(t *testing.T) *httpRequest {
|
||||
jar, err := cookiejar.New(nil)
|
||||
require.NoError(t, err)
|
||||
r := httpRequest{
|
||||
t: t,
|
||||
body: url.Values{},
|
||||
client: http.Client{
|
||||
Jar: jar,
|
||||
},
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
func (h *httpRequest) setClient(client http.Client) *httpRequest {
|
||||
h.client = client
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *httpRequest) setRoute(route string, params ...any) *httpRequest {
|
||||
h.route = srv.URL + c.Web.Reverse(route, params)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *httpRequest) setBody(body url.Values) *httpRequest {
|
||||
h.body = body
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *httpRequest) get() *httpResponse {
|
||||
resp, err := h.client.Get(h.route)
|
||||
require.NoError(h.t, err)
|
||||
r := httpResponse{
|
||||
t: h.t,
|
||||
Response: resp,
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
func (h *httpRequest) post() *httpResponse {
|
||||
// Make a get request to get the CSRF token
|
||||
doc := h.get().
|
||||
assertStatusCode(http.StatusOK).
|
||||
toDoc()
|
||||
|
||||
// Extract the CSRF and include it in the POST request body
|
||||
csrf := doc.Find(`input[name="csrf"]`).First()
|
||||
token, exists := csrf.Attr("value")
|
||||
assert.True(h.t, exists)
|
||||
h.body["csrf"] = []string{token}
|
||||
|
||||
// Make the POST requests
|
||||
resp, err := h.client.PostForm(h.route, h.body)
|
||||
require.NoError(h.t, err)
|
||||
r := httpResponse{
|
||||
t: h.t,
|
||||
Response: resp,
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
type httpResponse struct {
|
||||
*http.Response
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func (h *httpResponse) assertStatusCode(code int) *httpResponse {
|
||||
assert.Equal(h.t, code, h.Response.StatusCode)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *httpResponse) assertRedirect(t *testing.T, route string, params ...any) *httpResponse {
|
||||
assert.Equal(t, c.Web.Reverse(route, params), h.Header.Get("Location"))
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *httpResponse) toDoc() *goquery.Document {
|
||||
doc, err := goquery.NewDocumentFromReader(h.Body)
|
||||
require.NoError(h.t, err)
|
||||
err = h.Body.Close()
|
||||
assert.NoError(h.t, err)
|
||||
return doc
|
||||
}
|
||||
60
pkg/handlers/search.go
Normal file
60
pkg/handlers/search.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mikestefanello/pagoda/pkg/controller"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
)
|
||||
|
||||
const routeNameSearch = "search"
|
||||
|
||||
type (
|
||||
Search struct {
|
||||
controller.Controller
|
||||
}
|
||||
|
||||
searchResult struct {
|
||||
Title string
|
||||
URL string
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register(new(Search))
|
||||
}
|
||||
|
||||
func (c *Search) Init(ct *services.Container) error {
|
||||
c.Controller = controller.NewController(ct)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Search) Routes(g *echo.Group) {
|
||||
g.GET("/search", c.Page).Name = routeNameSearch
|
||||
}
|
||||
|
||||
func (c *Search) Page(ctx echo.Context) error {
|
||||
page := controller.NewPage(ctx)
|
||||
page.Layout = templates.LayoutMain
|
||||
page.Name = templates.PageSearch
|
||||
|
||||
// Fake search results
|
||||
var results []searchResult
|
||||
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{
|
||||
Title: title,
|
||||
URL: fmt.Sprintf("https://www.%s.com", search),
|
||||
})
|
||||
}
|
||||
}
|
||||
page.Data = results
|
||||
|
||||
return c.RenderPage(ctx, page)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue