Openmaize v0.11.0 Openmaize.AccessControl
Function plugs to handle authorization.
The functions in this module need to be run after the Openmaize.Authenticate
plug, as they use the current_user
value in conn.assigns
.
Current user and authorization
The following notes apply to all the functions in this module.
If the current user’s role is in the list of allowed roles, the connection will be allowed to proceed.
If there is a current user, but the role is not in the list of allowed roles,
the user will be redirected to that user’s role’s redirect page, or the user
will be sent a 403 error message, depending on whether the redirects
option
is true or false.
If the current user is nil, the user will be redirected to the login page, or just sent a 401 error message.
Summary
Functions
Verify that the user is authorized to access the requested page / resource
Verify that the user, based on the user id, is authorized to access the requested page / resource
Functions
Verify that the user is authorized to access the requested page / resource.
This check is based on user role.
This function has two options:
- roles - a list of permitted roles
- redirects - if true, which is the default, redirect if there is an error
Examples with Phoenix
In the relevant controller.ex
file, first import this module:
import Openmaize.AccessControl
In each of the following examples, the plug
command needs to be added
to the top of the file, just below the imports.
To only allow users with the role “admin” to access the pages in that module:
plug :authorize, roles: ["admin"]
To only allow users with the role “admin” to access the create and update pages (this means that the other pages are unprotected):
plug :authorize, [roles: ["admin"]] when action in [:create, :update]
To allow users with the role “admin” or “user” to access pages, and set redirects to false (this example protects every page except the index page):
plug :authorize, [roles: ["admin", "user"], redirects: false] when not action in [:index]
To allow users with the role “admin” or “user” to access the index, but only allow those users with the role “admin” to access the other pages.
plug :authorize, [roles: ["admin", "user"]] when action in [:index]
plug :authorize, [roles: ["admin"]] when not action in [:index]
Verify that the user, based on the user id, is authorized to access the requested page / resource.
This check only performs a check to see if the user id is correct. You will
need to use the authorize
plug to verify the user’s role.
This function has one option:
- redirects - if true, which is the default, redirect if there is an error