Skip to content

Commit

Permalink
Merge pull request #850 from SuzukiRyuichiro/current-user-for-rails-8…
Browse files Browse the repository at this point in the history
…-auth

Add documentation to provide a guide for how to use pundit with rails 8's built-in authentication generator
  • Loading branch information
Burgestrand authored Mar 3, 2025
2 parents 5507430 + b117d41 commit 51ce6a9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Add `Pundit::Authorization#pundit_reset!` hook to reset the policy and policy scope cache. (#830)
- Add links to gemspec. (#845)
- Register policies directories for Rails 8 code statistics (#833)
- Added an example for how to use pundit with Rails 8 authentication generator (#850)

## Changed

Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,17 @@ def pundit_user
User.find_by_other_means
end
```

For instance, Rails 8 includes a built-in [authentication generator](https://github.com/rails/rails/tree/8-0-stable/railties/lib/rails/generators/rails/authentication). If you choose to use it, the currently logged-in user is accessed via `Current.user` instead of `current_user`.

To ensure compatibility with Pundit, define a `pundit_user` method in `application_controller.rb` (or another suitable location) as follows:

```ruby
def pundit_user
Current.user
end
```

### Handling User Switching in Pundit

When switching users in your application, it's important to reset the Pundit user context to ensure that authorization policies are applied correctly for the new user. Pundit caches the user context, so failing to reset it could result in incorrect permissions being applied.
Expand Down

0 comments on commit 51ce6a9

Please sign in to comment.