Open markerdmann opened 4 months ago
The recent updates to the authboss
package introduce enhancements to the Authboss
struct, including new fields for template management and rendering. Significant refactoring has been done across various files to improve session handling, context usage, and error management. Additionally, new methods for handling user authentication, email responses, and redirects have been added, along with extensive updates to test files to reflect these changes.
File(s) | Change Summary |
---|---|
authboss.go , authboss_test.go |
Added fields templateNames and renderer to Authboss struct. Updated Init method and tests to initialize renderer . |
callbacks.go , callbacks_test.go |
Refactored map initialization in Callbacks struct. Removed unused imports and logging. Updated tests accordingly. |
client_storer.go , client_storer_test.go |
Updated ClientStoreMaker interface documentation and method calls to use Make . Adjusted tests to match. |
confirm/confirm.go |
Renamed ConfirmStorer to ConfirmStoreLoader . Added new methods and updated signatures to use context.Context . |
context.go , context_test.go |
Introduced functions for managing user authentication and session handling. Added corresponding tests. |
errors.go , errors_test.go |
Removed AttributeErr and ErrAndRedirect structs. Updated error message format in RenderErr . Adjusted tests. |
expire.go , expire_test.go |
Updated method calls to use Make for session creation. Adjusted tests with defer statements and newMockClientStoreMaker . |
internal/mocks/mocks.go |
Added context import. Renamed fields and updated methods in MockUser struct. Introduced MockStoreLoader and updated MockFailStorer . |
internal/response/response.go |
Restructured template handling logic. Commented out template loading and redirection functionality. |
mailer_test.go |
Updated expected return value in TestBoundary . |
mocks_test.go |
Added mockClientStoreMaker , mockRenderLoader , and mockRenderer types for testing. |
module.go , module_test.go |
Added Templates method to Modularizer interface. Updated loadModule function. Adjusted tests. |
renderer.go |
Updated RenderLoader and Renderer interfaces to handle arrays and template names respectively. |
response.go |
Added functionality for handling HTTP responses, including rendering templates, sending emails, and redirects. |
router.go |
Renamed contextRoute to abHandler . Updated ServeHTTP method and added isAPIRequest function. |
storer_test.go |
Removed code related to attributes and binding. Focused on testing casing style conversions. |
In the realm of code where changes bloom,
TheAuthboss
struct found its room.
With templates and renderers, new paths to tread,
Context and sessions, smoothly led.
Errors refined, methods anew,
A rabbit's joy in code review.
🌸🐇✨
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?
@coderabbitai review
@coderabbitai add tests
[!TIP] For best results, initiate chat on the files or code changes.
@markerdmann, I'll add unit tests for several key components affected by the changes in this PR. Here are some examples for the Authboss
struct in authboss.go
. You can extend these tests similarly for other components.
package authboss_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/markerdmann/authboss"
"context"
)
func TestAuthboss_Init(t *testing.T) {
ab := authboss.Authboss{}
err := ab.Init("module1", "module2")
assert.NoError(t, err)
assert.NotNil(t, ab.Renderer)
assert.Equal(t, []string{"template1", "template2"}, ab.TemplateNames)
}
func TestAuthboss_FlashSuccess(t *testing.T) {
ab := authboss.Authboss{}
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
result := ab.FlashSuccess(w, r)
assert.Equal(t, "success", result)
}
func TestAuthboss_FlashError(t *testing.T) {
ab := authboss.Authboss{}
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
result := ab.FlashError(w, r)
assert.Equal(t, "error", result)
}
These tests check the initialization of the Authboss
struct and its methods for flashing success and error messages. You can add similar tests for other modified methods and new functionalities. If you need tests for specific methods or files, please let me know!
Authors of pull request: @aarondl
This pull request enhanced the Authboss
library by adding template management and rendering capabilities, improving user session handling, and refactoring various components for better maintainability and functionality.
The Authboss
struct was updated to include templateNames
and renderer
fields, enabling it to manage and render templates. The Init
method now initializes the renderer with the specified template names. The UpdatePassword
method was refactored to use the Storer
interface for user interactions and simplified by removing reflection logic.
New context-related functions were added in context.go
to handle user sessions more effectively, including methods to load the current user and user ID into the request context. Corresponding tests were added in context_test.go
to ensure these functions work correctly.
The ConfirmStorer
interface was split into ConfirmStoreLoader
and ConfirmStorer
to separate user loading and confirmation attribute management, improving code clarity. The callbacks.go
file was cleaned up by removing unused imports and logging statements, and the NewCallbacks
function was updated for better readability.
The RenderLoader
and Renderer
interfaces were modified to handle multiple template names and include content type in the render output. The response.go
file introduced new methods for handling HTTP responses and emails, centralizing response logic and improving maintainability.
Finally, various tests were updated or added to ensure the new functionalities and refactored components work as expected, including changes in authboss_test.go
, router_test.go
, and storer_test.go
.
UpdatePassword
method remains non-functional as it returns a "not implemented" error, which could lead to runtime errors if this method is called.TestAuthbossUpdatePassword
and TestAuthbossUpdatePasswordFail
functions are marked as skipped, which means the functionality they are supposed to test is not being verified.FireAfter
method means that errors occurring during callback execution will no longer be logged, potentially reducing the amount of diagnostic information available during error handling.TestCallbacksAfterErrors
means the test no longer checks if error messages are correctly logged, potentially missing issues with logging.ctx *authboss.Context
parameter in the confirmHandler
function may lead to issues accessing context-specific data, as it no longer directly receives the authboss.Context
.LoadCurrentUserID
method modifies the request context but does not handle potential errors from context.WithValue
, which could lead to context corruption.CurrentUserID
method in context.go
.CurrentUserIDP
is redundant because an identical function with the same name and functionality already exists in the codebase.CurrentUser
method, which already performs the same tasks.CurrentUserP
is redundant because an identical function with the same name and functionality already exists in the codebase.currentUser
method in context.go
already performs the same tasks and serves the same purpose.LoadCurrentUserID
is redundant because its functionality is already covered by the existing LoadCurrentUserID
function in the codebase.LoadCurrentUserIDP
is redundant as its functionality is already covered by the existing LoadCurrentUserIDP
method in context.go
.LoadCurrentUser
method.LoadCurrentUserP
is redundant as it duplicates the functionality of the existing LoadCurrentUserP
method.recover
function in TestCurrentUserIDP
, TestCurrentUserP
, TestLoadCurrentUserIDP
, and TestLoadCurrentUserP
uses t.Failed()
instead of t.Fail()
or t.Fatalf()
, which does not stop the test execution immediately.AttributeErr
and its methods eliminates the ability to handle and report specific attribute retrieval and type mismatch errors, which could lead to less informative error handling and debugging.ErrAndRedirect
and its methods removes the capability to handle errors that require a redirect response, potentially affecting error management and user experience.a.SessionStoreMaker.Make(w, r)
assumes that SessionStoreMaker
is always an object with a Make
method, which could cause runtime errors if SessionStoreMaker
is not properly initialized or if the Make
method does not exist.nowTime
to its original state is necessary to prevent side effects on other tests, but if nowTime
is used in other tests without similar precautions, it could lead to inconsistent test results.MockStorer
and its methods without providing equivalent functionality in MockStoreLoader
may lead to missing functionality for creating, updating, and retrieving user data and tokens.ErrTemplateNotFound
variable will cause runtime errors in the reactivated functions that reference this variable for error handling.boundary
method has not been updated to generate the new expected string "fe3fhpsm69lx8jvnrnju0wr".Templates
method in the Modularizer
interface is not checked for nil or empty slices, which could lead to potential issues if a module returns nil or an empty slice.Render
method signature in the Renderer
interface may break existing implementations that do not expect the additional name
parameter and the new return value contentType
.redirectAPI
method does not set a default status code if ro.Code
is zero, potentially causing issues with clients expecting a status code.Respond
method in response.go
.Email
function in response.go
and RenderEmail
function in internal/response/response.go
.Redirect
function in response.go
already performs the same tasks and operations.redirectAPI
method in the response.go
file, which already handles the same functionality.redirectNonAPI
is redundant because an identical function with the same name and functionality already exists in the response.go
file at line 149.redirectIfLoggedIn
function may cause issues if any routes previously relied on this logic to redirect logged-in users appropriately.ServeHTTP
method in abHandler
does not initialize a context, which may lead to issues if any handlers rely on context initialization.LoadCurrentUserID
function call in the new ServeHTTP
method may fail and cause a 500 error if the user ID cannot be loaded, potentially affecting all routes.TestRouter_Redirect
function eliminates the automated test coverage for redirect scenarios, potentially allowing redirect-related bugs to go undetected.Templates
method in both testRouterModule
and testModule
already provides the same functionality.DataType
type and its related constants and methods could break any existing functionality that relies on these definitions for handling specific data types.Sweep is unsure if these are issues, but they might be worth checking out.
us := userStruct.(*mockUser)
to us := userStruct.(mockStoredUser)
may cause a runtime panic if userStruct
is not of type mockStoredUser
.*authboss.Context
to context.Context
in the afterRegister
function may cause issues with accessing ctx.User
and other context-related operations that rely on authboss.Context
.CurrentUserID
method does not handle the case where session.Get(SessionKey)
returns an error, which could lead to unexpected behavior.LoadCurrentUserIDP
and LoadCurrentUserP
methods panic on error, which could lead to application crashes if not handled properly.recover()
function in TestCurrentUserIDP
, TestCurrentUserP
, TestLoadCurrentUserIDP
, and TestLoadCurrentUserP
does not check if the recovered value is nil, which could cause a panic when trying to assert it as an error.Respond
method does not handle the case where a.renderer.Render
returns an empty mime
type, potentially leading to incorrect content type headers.
Summary by CodeRabbit
New Features
ConfirmStoreLoader
andConfirmStorer
interfaces for better token and confirmation management.Improvements
SessionStoreMaker
usage withMake
method.Bug Fixes
Refactor
ConfirmStorer
toConfirmStoreLoader
.context.Context
.Tests
Documentation
ClientStoreMaker
interface documentation for better clarity on security considerations.