RephiWeb.Auth.AuthorizationHelpers (Rephi v0.0.2)
View SourceHelper functions for authorization checks in controllers and views.
These helpers provide a convenient way to check user permissions and roles within controller actions and view templates. They automatically handle cases where no user is authenticated.
Usage in Controllers
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller # Automatically imports these helpers
def show(conn, %{"id" => id}) do
if can?(conn, "users:view") do
# User can view users
user = Accounts.get_user!(id)
render(conn, :show, user: user)
else
# Handle unauthorized access
conn |> put_status(:forbidden) |> json(%{error: "Forbidden"})
end
end
end
Usage in Views/Templates
# In a template (EEx)
<%= if can?(@conn, "users:edit") do %>
<button>Edit User</button>
<% end %>
<%= if has_role?(@conn, "admin") do %>
<div class="admin-panel">Admin Tools</div>
<% end %>
Safe Defaults
All functions return false
when no user is authenticated, making them
safe to use without additional nil checks.
Summary
Functions
Authorize action with flexible options.
Checks if the current user has a specific permission.
Checks if the current user has all of the given permissions.
Checks if the current user has any of the given permissions.
Returns the current user or nil.
Gets the current user's permissions.
Gets the current user's roles.
Checks if the current user has a specific role.
Functions
Authorize action with flexible options.
Examples
authorize(conn, permission: "users:edit")
authorize(conn, role: "admin")
authorize(conn, any_permission: ["users:edit", "users:create"])
Checks if the current user has a specific permission.
Returns false
if no user is authenticated or if the user lacks the permission.
Parameters
conn
- The Plug.Conn struct containing user informationpermission_slug
- The permission slug to check (e.g., "users:edit")
Examples
# In a controller action
if can?(conn, "users:edit") do
# User can edit users
end
# In a view template
<%= if can?(@conn, "roles:create") do %>
<a href="/roles/new">Create Role</a>
<% end %>
Returns
true
- User is authenticated and has the permissionfalse
- User is not authenticated or lacks the permission
Checks if the current user has all of the given permissions.
Checks if the current user has any of the given permissions.
Returns the current user or nil.
Gets the current user's permissions.
Gets the current user's roles.
Checks if the current user has a specific role.
Returns false
if no user is authenticated or if the user doesn't have the role.
Parameters
conn
- The Plug.Conn struct containing user informationrole_slug
- The role slug to check (e.g., "admin", "manager")
Examples
# In a controller action
if has_role?(conn, "admin") do
# User is an admin
end
# In a view template
<%= if has_role?(@conn, "manager") do %>
<div class="manager-tools">Manager Dashboard</div>
<% end %>
Returns
true
- User is authenticated and has the rolefalse
- User is not authenticated or doesn't have the role