Reorganized directories and packages.

This commit is contained in:
mikestefanello 2022-11-02 19:23:26 -04:00
parent 965fb540c7
commit dceb232cb2
61 changed files with 83 additions and 83 deletions

69
pkg/routes/about.go Normal file
View file

@ -0,0 +1,69 @@
package routes
import (
"html/template"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/labstack/echo/v4"
)
type (
about struct {
controller.Controller
}
aboutData struct {
ShowCacheWarning bool
FrontendTabs []aboutTab
BackendTabs []aboutTab
}
aboutTab struct {
Title string
Body template.HTML
}
)
func (c *about) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "main"
page.Name = "about"
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/routes/about_test.go Normal file
View file

@ -0,0 +1,23 @@
package routes
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 TestAbout_Get(t *testing.T) {
doc := request(t).
setRoute("about").
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())
}

65
pkg/routes/contact.go Normal file
View file

@ -0,0 +1,65 @@
package routes
import (
"fmt"
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/labstack/echo/v4"
)
type (
contact struct {
controller.Controller
}
contactForm struct {
Email string `form:"email" validate:"required,email"`
Message string `form:"message" validate:"required"`
Submission controller.FormSubmission
}
)
func (c *contact) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "main"
page.Name = "contact"
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) Post(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.Container.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.Get(ctx)
}

42
pkg/routes/error.go Normal file
View file

@ -0,0 +1,42 @@
package routes
import (
"net/http"
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/labstack/echo/v4"
)
type errorHandler struct {
controller.Controller
}
func (e *errorHandler) Get(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 = "main"
page.Title = http.StatusText(code)
page.Name = "error"
page.StatusCode = code
page.HTMX.Request.Enabled = false
if err = e.RenderPage(ctx, page); err != nil {
ctx.Logger().Error(err)
}
}

View file

@ -0,0 +1,100 @@
package routes
import (
"fmt"
"strings"
"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/msg"
"github.com/labstack/echo/v4"
)
type (
forgotPassword struct {
controller.Controller
}
forgotPasswordForm struct {
Email string `form:"email" validate:"required,email"`
Submission controller.FormSubmission
}
)
func (c *forgotPassword) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "auth"
page.Name = "forgot-password"
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 *forgotPassword) Post(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.Get(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.Get(ctx)
}
// Attempt to load the user
u, err := c.Container.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.Container.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("reset_password", u.ID, pt.ID, token)
err = c.Container.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()
}

46
pkg/routes/home.go Normal file
View file

@ -0,0 +1,46 @@
package routes
import (
"fmt"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/labstack/echo/v4"
)
type (
home struct {
controller.Controller
}
post struct {
Title string
Body string
}
)
func (c *home) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "main"
page.Name = "home"
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 *home) 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]
}

94
pkg/routes/login.go Normal file
View file

@ -0,0 +1,94 @@
package routes
import (
"fmt"
"strings"
"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/msg"
"github.com/labstack/echo/v4"
)
type (
login struct {
controller.Controller
}
loginForm struct {
Email string `form:"email" validate:"required,email"`
Password string `form:"password" validate:"required"`
Submission controller.FormSubmission
}
)
func (c *login) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "auth"
page.Name = "login"
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 *login) Post(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.Get(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.Get(ctx)
}
// Attempt to load the user
u, err := c.Container.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.Container.Auth.CheckPassword(form.Password, u.Password)
if err != nil {
return authFailed()
}
// Log the user in
err = c.Container.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, "home")
}

21
pkg/routes/logout.go Normal file
View file

@ -0,0 +1,21 @@
package routes
import (
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/mikestefanello/pagoda/pkg/msg"
"github.com/labstack/echo/v4"
)
type logout struct {
controller.Controller
}
func (l *logout) Get(c echo.Context) error {
if err := l.Container.Auth.Logout(c); err == nil {
msg.Success(c, "You have been logged out successfully.")
} else {
msg.Danger(c, "An error occurred. Please try again.")
}
return l.Redirect(c, "home")
}

122
pkg/routes/register.go Normal file
View file

@ -0,0 +1,122 @@
package routes
import (
"fmt"
"github.com/mikestefanello/pagoda/ent"
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/mikestefanello/pagoda/pkg/msg"
"github.com/labstack/echo/v4"
)
type (
register struct {
controller.Controller
}
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
}
)
func (c *register) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "auth"
page.Name = "register"
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 *register) Post(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.Get(ctx)
}
// Hash the password
pwHash, err := c.Container.Auth.HashPassword(form.Password)
if err != nil {
return c.Fail(err, "unable to hash password")
}
// Attempt creating the user
u, err := c.Container.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, "login")
default:
return c.Fail(err, "unable to create user")
}
// Log the user in
err = c.Container.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, "login")
}
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, "home")
}
func (c *register) sendVerificationEmail(ctx echo.Context, usr *ent.User) {
// Generate a token
token, err := c.Container.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("verify_email", token)
err = c.Container.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.")
}

View file

@ -0,0 +1,82 @@
package routes
import (
"github.com/mikestefanello/pagoda/ent"
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/mikestefanello/pagoda/pkg/msg"
"github.com/labstack/echo/v4"
)
type (
resetPassword struct {
controller.Controller
}
resetPasswordForm struct {
Password string `form:"password" validate:"required"`
ConfirmPassword string `form:"password-confirm" validate:"required,eqfield=Password"`
Submission controller.FormSubmission
}
)
func (c *resetPassword) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "auth"
page.Name = "reset-password"
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 *resetPassword) Post(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.Get(ctx)
}
// Hash the new password
hash, err := c.Container.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.Container.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, "login")
}

109
pkg/routes/router.go Normal file
View file

@ -0,0 +1,109 @@
package routes
import (
"net/http"
"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/mikestefanello/pagoda/pkg/middleware"
"github.com/mikestefanello/pagoda/pkg/services"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
echomw "github.com/labstack/echo/v4/middleware"
)
// BuildRouter builds the router
func BuildRouter(c *services.Container) {
// 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",
}),
)
// Base controller
ctr := controller.NewController(c)
// Error handler
err := errorHandler{Controller: ctr}
c.Web.HTTPErrorHandler = err.Get
// Example routes
navRoutes(c, g, ctr)
userRoutes(c, g, ctr)
}
func navRoutes(c *services.Container, g *echo.Group, ctr controller.Controller) {
home := home{Controller: ctr}
g.GET("/", home.Get).Name = "home"
search := search{Controller: ctr}
g.GET("/search", search.Get).Name = "search"
about := about{Controller: ctr}
g.GET("/about", about.Get).Name = "about"
contact := contact{Controller: ctr}
g.GET("/contact", contact.Get).Name = "contact"
g.POST("/contact", contact.Post).Name = "contact.post"
}
func userRoutes(c *services.Container, g *echo.Group, ctr controller.Controller) {
logout := logout{Controller: ctr}
g.GET("/logout", logout.Get, middleware.RequireAuthentication()).Name = "logout"
verifyEmail := verifyEmail{Controller: ctr}
g.GET("/email/verify/:token", verifyEmail.Get).Name = "verify_email"
noAuth := g.Group("/user", middleware.RequireNoAuthentication())
login := login{Controller: ctr}
noAuth.GET("/login", login.Get).Name = "login"
noAuth.POST("/login", login.Post).Name = "login.post"
register := register{Controller: ctr}
noAuth.GET("/register", register.Get).Name = "register"
noAuth.POST("/register", register.Post).Name = "register.post"
forgot := forgotPassword{Controller: ctr}
noAuth.GET("/password", forgot.Get).Name = "forgot_password"
noAuth.POST("/password", forgot.Post).Name = "forgot_password.post"
resetGroup := noAuth.Group("/password/reset",
middleware.LoadUser(c.ORM),
middleware.LoadValidPasswordToken(c.Auth),
)
reset := resetPassword{Controller: ctr}
resetGroup.GET("/token/:user/:password_token/:token", reset.Get).Name = "reset_password"
resetGroup.POST("/token/:user/:password_token/:token", reset.Post).Name = "reset_password.post"
}

136
pkg/routes/routes_test.go Normal file
View file

@ -0,0 +1,136 @@
package routes
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
BuildRouter(c)
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 ...interface{}) *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 ...interface{}) *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
}

44
pkg/routes/search.go Normal file
View file

@ -0,0 +1,44 @@
package routes
import (
"fmt"
"math/rand"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/labstack/echo/v4"
)
type (
search struct {
controller.Controller
}
searchResult struct {
Title string
URL string
}
)
func (c *search) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Layout = "main"
page.Name = "search"
// 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)
}

View file

@ -0,0 +1,62 @@
package routes
import (
"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/msg"
)
type verifyEmail struct {
controller.Controller
}
func (c *verifyEmail) Get(ctx echo.Context) error {
var usr *ent.User
// Validate the token
token := ctx.Param("token")
email, err := c.Container.Auth.ValidateEmailVerificationToken(token)
if err != nil {
msg.Warning(ctx, "The link is either invalid or has expired.")
return c.Redirect(ctx, "home")
}
// 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.Container.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, "home")
}