Renamed container package services.

This commit is contained in:
mikestefanello 2021-12-18 10:07:12 -05:00
parent 195d572036
commit 1fe906a6f9
9 changed files with 42 additions and 43 deletions

View file

@ -12,10 +12,10 @@ import (
"sync" "sync"
"goweb/config" "goweb/config"
"goweb/container"
"goweb/funcmap" "goweb/funcmap"
"goweb/middleware" "goweb/middleware"
"goweb/msg" "goweb/msg"
"goweb/services"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
@ -37,10 +37,10 @@ var (
) )
type Controller struct { type Controller struct {
Container *container.Container Container *services.Container
} }
func NewController(c *container.Container) Controller { func NewController(c *services.Container) Controller {
return Controller{ return Controller{
Container: c, Container: c,
} }

View file

@ -8,12 +8,12 @@ import (
"os/signal" "os/signal"
"time" "time"
"goweb/container"
"goweb/routes" "goweb/routes"
"goweb/services"
) )
func main() { func main() {
c := container.NewContainer() c := services.NewContainer()
// Build the router // Build the router
routes.BuildRouter(c) routes.BuildRouter(c)

View file

@ -3,22 +3,22 @@ package middleware
import ( import (
"net/http" "net/http"
"goweb/container"
"goweb/context" "goweb/context"
"goweb/ent" "goweb/ent"
"goweb/msg" "goweb/msg"
"goweb/services"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
func LoadAuthenticatedUser(authClient *container.AuthClient) echo.MiddlewareFunc { func LoadAuthenticatedUser(authClient *services.AuthClient) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
u, err := authClient.GetAuthenticatedUser(c) u, err := authClient.GetAuthenticatedUser(c)
switch err.(type) { switch err.(type) {
case *ent.NotFoundError: case *ent.NotFoundError:
c.Logger().Debug("auth user not found") c.Logger().Debug("auth user not found")
case container.NotAuthenticatedError: case services.NotAuthenticatedError:
case nil: case nil:
c.Set(context.AuthenticatedUserKey, u) c.Set(context.AuthenticatedUserKey, u)
c.Logger().Info("auth user loaded in to context: %d", u.ID) c.Logger().Info("auth user loaded in to context: %d", u.ID)
@ -31,7 +31,7 @@ func LoadAuthenticatedUser(authClient *container.AuthClient) echo.MiddlewareFunc
} }
} }
func LoadValidPasswordToken(authClient *container.AuthClient) echo.MiddlewareFunc { func LoadValidPasswordToken(authClient *services.AuthClient) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
var usr *ent.User var usr *ent.User
@ -46,7 +46,7 @@ func LoadValidPasswordToken(authClient *container.AuthClient) echo.MiddlewareFun
switch err.(type) { switch err.(type) {
case nil: case nil:
case container.InvalidTokenError: case services.InvalidPasswordTokenError:
msg.Warning(c, "The link is either invalid or has expired. Please request a new one.") msg.Warning(c, "The link is either invalid or has expired. Please request a new one.")
return c.Redirect(http.StatusFound, c.Echo().Reverse("forgot_password")) return c.Redirect(http.StatusFound, c.Echo().Reverse("forgot_password"))
default: default:

View file

@ -6,6 +6,7 @@ import (
"goweb/config" "goweb/config"
"goweb/controller" "goweb/controller"
"goweb/middleware" "goweb/middleware"
"goweb/services"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
@ -14,8 +15,6 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
echomw "github.com/labstack/echo/v4/middleware" echomw "github.com/labstack/echo/v4/middleware"
"goweb/container"
) )
type Validator struct { type Validator struct {
@ -31,7 +30,7 @@ func (v *Validator) Validate(i interface{}) error {
// TODO: This is doing more than building the router // TODO: This is doing more than building the router
func BuildRouter(c *container.Container) { func BuildRouter(c *services.Container) {
// Static files with proper cache control // 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 // funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
// after each server restart // after each server restart
@ -75,7 +74,7 @@ func BuildRouter(c *container.Container) {
userRoutes(c, g, ctr) userRoutes(c, g, ctr)
} }
func navRoutes(c *container.Container, g *echo.Group, ctr controller.Controller) { func navRoutes(c *services.Container, g *echo.Group, ctr controller.Controller) {
home := Home{Controller: ctr} home := Home{Controller: ctr}
g.GET("/", home.Get).Name = "home" g.GET("/", home.Get).Name = "home"
@ -87,7 +86,7 @@ func navRoutes(c *container.Container, g *echo.Group, ctr controller.Controller)
g.POST("/contact", contact.Post).Name = "contact.post" g.POST("/contact", contact.Post).Name = "contact.post"
} }
func userRoutes(c *container.Container, g *echo.Group, ctr controller.Controller) { func userRoutes(c *services.Container, g *echo.Group, ctr controller.Controller) {
logout := Logout{Controller: ctr} logout := Logout{Controller: ctr}
g.GET("/logout", logout.Get, middleware.RequireAuthentication()).Name = "logout" g.GET("/logout", logout.Get, middleware.RequireAuthentication()).Name = "logout"

View file

@ -8,7 +8,7 @@ import (
"testing" "testing"
"goweb/config" "goweb/config"
"goweb/container" "goweb/services"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -18,7 +18,7 @@ import (
var ( var (
srv *httptest.Server srv *httptest.Server
c *container.Container c *services.Container
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
@ -26,7 +26,7 @@ func TestMain(m *testing.M) {
config.SwitchEnvironment(config.EnvTest) config.SwitchEnvironment(config.EnvTest)
// Start a test HTTP server // Start a test HTTP server
c = container.NewContainer() c = services.NewContainer()
BuildRouter(c) BuildRouter(c)
srv = httptest.NewServer(c.Web) srv = httptest.NewServer(c.Web)

View file

@ -1,4 +1,4 @@
package container package services
import ( import (
"crypto/rand" "crypto/rand"
@ -16,14 +16,14 @@ import (
) )
const ( const (
// sessionName stores the name of the session which contains authentication data // authSessionName stores the name of the session which contains authentication data
sessionName = "ua" authSessionName = "ua"
// sessionKeyUserID stores the key used to store the user ID in the session // authSessionKeyUserID stores the key used to store the user ID in the session
sessionKeyUserID = "user_id" authSessionKeyUserID = "user_id"
// sessionKeyAuthenticated stores the key used to store the authentication status in the session // authSessionKeyAuthenticated stores the key used to store the authentication status in the session
sessionKeyAuthenticated = "authenticated" authSessionKeyAuthenticated = "authenticated"
) )
// NotAuthenticatedError is an error returned when a user is not authenticated // NotAuthenticatedError is an error returned when a user is not authenticated
@ -34,21 +34,21 @@ func (e NotAuthenticatedError) Error() string {
return "user not authenticated" return "user not authenticated"
} }
// InvalidTokenError is an error returned when an invalid token is provided // InvalidPasswordTokenError is an error returned when an invalid token is provided
type InvalidTokenError struct{} type InvalidPasswordTokenError struct{}
// Error implements the error interface. // Error implements the error interface.
func (e InvalidTokenError) Error() string { func (e InvalidPasswordTokenError) Error() string {
return "invalid token" return "invalid password token"
} }
// AuthClient is the AuthClient that handles authentication requests // AuthClient is the client that handles authentication requests
type AuthClient struct { type AuthClient struct {
config *config.Config config *config.Config
orm *ent.Client orm *ent.Client
} }
// NewAuthClient creates a new authentication AuthClient // NewAuthClient creates a new authentication client
func NewAuthClient(cfg *config.Config, orm *ent.Client) *AuthClient { func NewAuthClient(cfg *config.Config, orm *ent.Client) *AuthClient {
return &AuthClient{ return &AuthClient{
config: cfg, config: cfg,
@ -58,34 +58,34 @@ func NewAuthClient(cfg *config.Config, orm *ent.Client) *AuthClient {
// Login logs in a user of a given ID // Login logs in a user of a given ID
func (c *AuthClient) Login(ctx echo.Context, userID int) error { func (c *AuthClient) Login(ctx echo.Context, userID int) error {
sess, err := session.Get(sessionName, ctx) sess, err := session.Get(authSessionName, ctx)
if err != nil { if err != nil {
return err return err
} }
sess.Values[sessionKeyUserID] = userID sess.Values[authSessionKeyUserID] = userID
sess.Values[sessionKeyAuthenticated] = true sess.Values[authSessionKeyAuthenticated] = true
return sess.Save(ctx.Request(), ctx.Response()) return sess.Save(ctx.Request(), ctx.Response())
} }
// Logout logs the requesting user out // Logout logs the requesting user out
func (c *AuthClient) Logout(ctx echo.Context) error { func (c *AuthClient) Logout(ctx echo.Context) error {
sess, err := session.Get(sessionName, ctx) sess, err := session.Get(authSessionName, ctx)
if err != nil { if err != nil {
return err return err
} }
sess.Values[sessionKeyAuthenticated] = false sess.Values[authSessionKeyAuthenticated] = false
return sess.Save(ctx.Request(), ctx.Response()) return sess.Save(ctx.Request(), ctx.Response())
} }
// GetAuthenticatedUserID returns the authenticated user's ID, if the user is logged in // GetAuthenticatedUserID returns the authenticated user's ID, if the user is logged in
func (c *AuthClient) GetAuthenticatedUserID(ctx echo.Context) (int, error) { func (c *AuthClient) GetAuthenticatedUserID(ctx echo.Context) (int, error) {
sess, err := session.Get(sessionName, ctx) sess, err := session.Get(authSessionName, ctx)
if err != nil { if err != nil {
return 0, err return 0, err
} }
if sess.Values[sessionKeyAuthenticated] == true { if sess.Values[authSessionKeyAuthenticated] == true {
return sess.Values[sessionKeyUserID].(int), nil return sess.Values[authSessionKeyUserID].(int), nil
} }
return 0, NotAuthenticatedError{} return 0, NotAuthenticatedError{}
@ -171,7 +171,7 @@ func (c *AuthClient) GetValidPasswordToken(ctx echo.Context, token string, userI
} }
} }
return nil, InvalidTokenError{} return nil, InvalidPasswordTokenError{}
} }
// DeletePasswordTokens deletes all password tokens in the database for a belonging to a given user. // DeletePasswordTokens deletes all password tokens in the database for a belonging to a given user.

View file

@ -1,4 +1,4 @@
package container package services
import ( import (
"context" "context"

View file

@ -1,4 +1,4 @@
package container package services
import ( import (
"context" "context"

View file

@ -1,4 +1,4 @@
package container package services
import ( import (
"context" "context"