You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> - We're simply showing any `active_session` associated with the `current_user`. By rendering the `user_agent`, `ip_address`, and `created_at` values we're giving the `current_user` all the information they need to know if there's any suspicious activity happening with their account. For example, if there's an `active_session` with a unfamiliar IP address or browser, this could indicate that the user's account has been compromised.
1484
1486
> - Note that we also instantiate `@active_sessions` in the `update` method. This is because the `update` method renders the `edit` method during failure cases.
1485
1487
1488
+
## Step 20: Allow User to Sign Out Specific Active Sessions
1489
+
1490
+
1. Generate the Active Sessions Controller and update routes.
> - We ensure only users who are logged in can access these endpoints by calling `before_action :authenticate_user!`.
1540
+
> - The `destroy` method simply looks for an `active_session` associated with the `current_user`. This ensures that a user can only delete sessions associated with their account.
1541
+
> - Once we destroy the `active_session` we then redirect back to the account page or to the homepage. This is because a user may not be deleting a session for the device or browser they're currently logged into. Note that we only call [reset_session](https://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-reset_session) if the user has deleted a session for the device or browser they're currently logged into, as this is the same as logging out.
1542
+
> - The `destroy_all` method is a [collection route](https://guides.rubyonrails.org/routing.html#adding-collection-routes) that will destroy all `active_session` records associated with the `current_user`. Note that we call `reset_session` because we will be logging out the `current_user` during this request.
1543
+
1544
+
2. Update views by adding buttons to destroy sessions.
1545
+
1546
+
```html+ruby
1547
+
<!-- app/views/users/edit.html.erb -->
1548
+
...
1549
+
<h2>Current Logins</h2>
1550
+
<% if @active_sessions.any? %>
1551
+
<%= button_to "Log out of all other sessions", destroy_all_active_sessions_path, method: :delete %>
> - This is a very subtle change, but we've added a [safe navigation operator](https://ruby-doc.org/core-2.6/doc/syntax/calling_methods_rdoc.html#label-Safe+navigation+operator) via the `&.user` call. This is because `ActiveSession.find_by(id: session[:current_active_session_id])` can now return `nil` since we're able to delete other `active_session` records.
0 commit comments