Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Helper Functions that Check for Role #1

Closed
2 tasks done
nelsonic opened this issue Jul 22, 2020 · 3 comments
Closed
2 tasks done

Create Helper Functions that Check for Role #1

nelsonic opened this issue Jul 22, 2020 · 3 comments
Assignees
Labels
enhancement New feature or request

Comments

@nelsonic
Copy link
Member

nelsonic commented Jul 22, 2020

Todo

  • Create helper functions that can be used in any app that uses auth_plug for auth,
    that check if the given person has a specific role e.g.
    • RBAC.has_role/2 - check if the person has the required role.
@nelsonic nelsonic added the enhancement New feature or request label Jul 22, 2020
@nelsonic nelsonic self-assigned this Jul 25, 2020
nelsonic added a commit that referenced this issue Sep 14, 2020
nelsonic added a commit that referenced this issue Sep 14, 2020
nelsonic added a commit that referenced this issue Sep 14, 2020
@nelsonic
Copy link
Member Author

I've got the has_role/2 function working: #7

rbac/lib/rbac.ex

Lines 117 to 126 in 0aa6124

def has_role(conn, role_name) do
role = get_role_from_cache(role_name)
person_roles =
conn.assigns.person.roles
|> String.split(",", trim: true)
|> Enum.map(&String.to_integer/1)
Enum.member?(person_roles, role.id)
end

Just need to document everything and can assign the PR. ⏳

@nelsonic nelsonic changed the title Create Helper Functions that Check for Roles and Permissions Create Helper Functions that Check for Role Sep 14, 2020
@nelsonic
Copy link
Member Author

Created has_role_any?/2 function to check for multiple roles at once:

rbac/lib/rbac.ex

Lines 135 to 152 in 7dcab44

def has_role_any?(conn, roles_list) do
list_ids = Enum.map(roles_list, fn role ->
r = get_role_from_cache(role)
r.id
end)
# list of integers
person_roles =
conn.assigns.person.roles
|> String.split(",", trim: true)
|> Enum.map(&String.to_integer/1)
# find the first occurence of a role by id:
found = Enum.find(person_roles, fn rid ->
Enum.member?(list_ids, rid)
end)
not is_nil(found)
end

I know this code isn't pretty.
Very happy for anyone else to refactor this.

@nelsonic
Copy link
Member Author

The helper functions are included in #7 :shipit:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant