Added auth to the container.

This commit is contained in:
mikestefanello 2021-12-15 09:29:43 -05:00
parent c9d50cb3d4
commit a33a76f8bc
9 changed files with 81 additions and 32 deletions

View file

@ -3,6 +3,8 @@ package routes
import (
"goweb/context"
"goweb/controller"
"goweb/ent"
"goweb/ent/user"
"goweb/msg"
"github.com/labstack/echo/v4"
@ -39,6 +41,11 @@ func (f *ForgotPassword) Post(c echo.Context) error {
return f.Get(c)
}
succeed := func() error {
msg.Success(c, "An email containing a link to reset your password will be sent to this address if it exists in our system.")
return f.Get(c)
}
// Parse the form values
form := new(ForgotPasswordForm)
if err := c.Bind(form); err != nil {
@ -52,7 +59,25 @@ func (f *ForgotPassword) Post(c echo.Context) error {
return f.Get(c)
}
// Attempt to load the user
u, err := f.Container.ORM.User.
Query().
Where(user.Email(form.Email)).
First(c.Request().Context())
if err != nil {
switch err.(type) {
case *ent.NotFoundError:
return succeed()
default:
return fail("error querying user during forgot password", err)
}
}
// TODO: generate and email a token
if u != nil {
}
return f.Redirect(c, "home")
}

View file

@ -3,7 +3,6 @@ package routes
import (
"fmt"
"goweb/auth"
"goweb/context"
"goweb/controller"
"goweb/ent"
@ -75,14 +74,14 @@ func (l *Login) Post(c echo.Context) error {
}
// Check if the password is correct
err = auth.CheckPassword(form.Password, u.Password)
err = l.Container.Auth.CheckPassword(form.Password, u.Password)
if err != nil {
msg.Danger(c, "Invalid credentials. Please try again.")
return l.Get(c)
}
// Log the user in
err = auth.Login(c, u.ID)
err = l.Container.Auth.Login(c, u.ID)
if err != nil {
return fail("unable to log in user", err)
}

View file

@ -1,7 +1,6 @@
package routes
import (
"goweb/auth"
"goweb/controller"
"goweb/msg"
@ -13,7 +12,7 @@ type Logout struct {
}
func (l *Logout) Get(c echo.Context) error {
if err := auth.Logout(c); err == nil {
if err := l.Container.Auth.Logout(c); err == nil {
msg.Success(c, "You have been logged out successfully.")
}
return l.Redirect(c, "home")

View file

@ -1,7 +1,6 @@
package routes
import (
"goweb/auth"
"goweb/context"
"goweb/controller"
"goweb/msg"
@ -57,7 +56,7 @@ func (r *Register) Post(c echo.Context) error {
}
// Hash the password
pwHash, err := auth.HashPassword(form.Password)
pwHash, err := r.Container.Auth.HashPassword(form.Password)
if err != nil {
return fail("unable to hash password", err)
}
@ -76,7 +75,7 @@ func (r *Register) Post(c echo.Context) error {
c.Logger().Infof("user created: %s", u.Name)
err = auth.Login(c, u.ID)
err = r.Container.Auth.Login(c, u.ID)
if err != nil {
c.Logger().Errorf("unable to log in: %v", err)
msg.Info(c, "Your account has been created.")

View file

@ -57,7 +57,7 @@ func BuildRouter(c *container.Container) {
echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf",
}),
middleware.LoadAuthenticatedUser(c.ORM),
middleware.LoadAuthenticatedUser(c.Auth),
)
// Base controller