def grant_role(db, entity, role, managed=False, commit=True):
    """Adds a role for users, services, groups or tokens"""
    if isinstance(entity, orm.APIToken):
        entity_repr = entity
    else:
        entity_repr = entity.name

    if role not in entity.roles:
        enitity_name = type(entity).__name__.lower()
        entity.roles.append(role)
        if managed:
            association_class = orm._role_associations[enitity_name]
            association = (
                db.query(association_class)
                .filter(
                    (getattr(association_class, f'{enitity_name}_id') == entity.id)
                    & (association_class.role_id == role.id)
                )
                .one()
            )
            association.managed_by_auth = True
        app_log.info(
            'Adding role %s for %s: %s',
            role.name,
            type(entity).__name__,
            entity_repr,
        )
        if commit:
            db.commit()
Adds a role for users, services, groups or tokens
jupyterhub/roles.py