Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

How we can manage roles and permissions using fast-API dynamically? #5676

Closed
9 tasks done
ghost opened this issue Nov 23, 2022 · 10 comments
Closed
9 tasks done

How we can manage roles and permissions using fast-API dynamically? #5676

ghost opened this issue Nov 23, 2022 · 10 comments

Comments

@ghost
Copy link

ghost commented Nov 23, 2022

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

class RoleChecker:
    def __init__(self, allowed_roles: List):
        self.allowed_roles = allowed_roles #utils.get_roles(Role)

    def __call__(self, user: User = Depends(oauth2.require_user)):
        print("user=======>", user)
        if user['role'] not in self.allowed_roles:
            logger.debug(f"User with role {user['role']} not in {self.allowed_roles}")
            raise HTTPException(status_code=403, detail="You have not a permission to performe action.")
        


allow_create_resource = RoleChecker(["admin"])
@router.post('/assign_roles', dependencies=[Depends(allow_create_resource)])
def assign_roles(assign_role: schemas.AssignRole ,user_id: str = Depends(oauth2.require_user)):
    
    roles = utils.get_roles(Role)
    
    
    email = assign_role.dict()['email']
    desired_role = assign_role.dict()['role']
    
    count = User.count_documents({"email": str(email)})
    
    role_count = Role.count_documents({"role": str(desired_role)})
    
    if count == 0:
        raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail=f"User for email {email} does not exist")
    
    if role_count == 0:
        raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail=f"please used only given roles => {','.join(role if role != 'admin' else '' for role in roles)} ")
    
    res = userResponseEntity(User.find_one({"email": str(email)}))
    
    user_id = user_id["id"]
    
    user = userResponseEntity(User.find_one(ObjectId(str(user_id))))
    
    if user['role'] != res['role']:
        dict = assign_role.dict(exclude_none=True)
        User.update_one(
            {'_id': ObjectId(str(res['id']))}, {'$set': dict})

        return {
            "message": f"user email {email} role {res['role']} updated to {desired_role}",
            "loged_in_user": user
        }
    
    return {
        "user": user
    }

Description

I research a lot but not find any good way to manage roles and permission dynamically using FastApi. if you guys have any idea please let me know.Thanks in advance

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.87.0

Python Version

3.10.8

Additional Context

No response

@ghost ghost added the question Question or problem label Nov 23, 2022
@pythonweb2
Copy link

pythonweb2 commented Nov 23, 2022

Can you please clarify what is wrong with the code snippet and what you are trying to accomplish, as well as what you mean by managing roles and permissions dynamically?

There is a section in the documentation about using oauth2.0 scopes (https://fastapi.tiangolo.com/advanced/security/oauth2-scopes) which is a way to manage permissions. As mentioned in the docs, you will want to have some way to persist the permissions for each user (using a database of some sort or using a predefined list of permissions).

You can also create a custom dependency to check permissions each time the user makes a request to your endpoints, which may be necessary if you need the ability to immediately revoke permissions for a user without invalidating their JWT.

@ghost
Copy link
Author

ghost commented Nov 23, 2022

@waderoberts123 I need Roles and permission for proper articles for good understanding. From the docs I cannot understand how we can work on that case. For example, users have 500 Roles and every role against different permissions so how do we handle dynamically without specifying specific roles e.g i use static roles and check if users have this role 'admin' or not. So I need the proper way of managing roles and permissions. For example, one user has posts.
we create 2 roles specify something for those roles if we add one role or more or edit existing role then our function not work fine because we change the role name but user have same role in user model role field so i need proper way for managing Role management and permission managements on the base of User.
I try one way is

create a table name Role
which have
user_id and role_name

and create another table name Permissions which have

role_id and different permissions
can_create: bool = False can_edit: bool = False can_add: bool = False can_update: bool = False can_delete: bool = False can_view: bool = False
so i want to manage all roles and permissions accordingly if you have any proper example please let me know because i already try no one example on google fit according to my needs.

@tacan
Copy link

tacan commented Nov 23, 2022

Hi Syed,
I think this is not (and should not be) a concern of the FastAPI framework. You should look into RBAC and ABAC, authorization models, enterprise design patterns, etc. There are whole libraries whose only concern is this one topic. I. suggest you take a look at OSO or Cerbos if you want a python based library. There is also Casbin and many others that have a python interface. I hope this helps.

@ghost
Copy link
Author

ghost commented Nov 23, 2022

@tacan these libraries we can use with fastAPI?

@tacan
Copy link

tacan commented Nov 23, 2022

Yes, of course. You just have to install them via pip (or any other tool you use) and then import and implement the access control logic in your path functions. Better yet, you can create helper functions or classes in external modules and just use them in your path functions.

@ghost
Copy link
Author

ghost commented Nov 24, 2022

@tacan please share with me any library link you recommend who fix my problem.

@yinziyan1206
Copy link

yinziyan1206 commented Nov 25, 2022

I use request.auth.scopes to check permissions and it is used in Starlette by @requires([any_scopes]). And you can create a dependency to authorize it

@hsluoyz
Copy link

hsluoyz commented Nov 26, 2022

@SyedKashifNaqvi PyCasbin (https://github.com/casbin/pycasbin) is a pure Python implementation for all RBAC and ABAC authorization (instead of just a client library that talks to an auth server via HTTP). It also provides a fastapi middleware: https://github.com/pycasbin/fastapi-authz for people to get started quickly. Maybe documentation can be added to let more people know.

@TheJumpyWizard
Copy link

@hsluoyz I hadn't seen fastapi-authz until now! Looks very useful/simple thanks for sharing

@EtceterisCDev
Copy link

Thanks a lot for sharing these information.

I will study this package in depth.
It could save us a lot of time.

Repository owner locked and limited conversation to collaborators Feb 28, 2023
@tiangolo tiangolo converted this issue into discussion #8413 Feb 28, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests

7 participants