Lesson 4 — Wiring current_user into the app
current_user in components
With the Authentication concern in ApplicationController,
current_user is available in controllers and ERB views via
helper_method. In Phlex components it needs to be explicitly made
available.
The correct Phlex v2 approach is to include it as a helper:
|
|
helpers is available in any Phlex component rendered within a Rails
request context — it gives access to all helper_method declarations
including current_user.
Updating AppLayout nav
Add sign out and user context to the nav:
|
|
Scoping boards to current_user
Update BoardsController to use the real current_user and scope
boards to what the user owns:
|
|
current_user.owned_boards.find scopes the lookup to the current
user’s boards — a user can’t access another user’s board by guessing
the id. A non-existent or unauthorised board raises ActiveRecord::RecordNotFound
which Rails handles as a 404.
Membership on board creation
When a user creates a board via owned_boards, a Membership record
should also be created so the owner appears in the members list and
current_user.boards (the through association) includes the new board.
Add a callback to Board:
|
|
This ensures every board has its creator as an admin member from the
start. The role: :admin assumes a role column on Membership —
if your membership model doesn’t have roles yet, use
find_or_create_by!(user: user) and add roles in the companion
auth tutorial.
Securing card and column controllers
Cards and columns should only be accessible to the board owner for now.
Add a before_action to verify ownership:
|
|
|
|