Python flask_principal.UserNeed() Examples
The following are 20
code examples of flask_principal.UserNeed().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask_principal
, or try the search function
.
Example #1
Source File: permissions.py From gitmark with GNU General Public License v2.0 | 8 votes |
def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'username'): identity.provides.add(UserNeed(current_user.username)) # Assuming the User model has a list of roles, update the # identity with the roles that the user provides if hasattr(current_user, 'role'): # for role in current_user.roles: identity.provides.add(RoleNeed(current_user.role)) # if current_user.is_superuser: if hasattr(current_user, 'is_superuser') and current_user.is_superuser: identity.provides.add(su_need) # return current_user.role identity.allow_su = su_permission.allows(identity) identity.allow_admin = admin_permission.allows(identity) identity.allow_edit = editor_permission.allows(identity) identity.allow_general = general_permission.allows(identity)
Example #2
Source File: security.py From flask-unchained with MIT License | 5 votes |
def _on_identity_loaded(self, sender, identity: Identity) -> None: """ Callback that runs whenever a new identity has been loaded. """ if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) for role in getattr(current_user, 'roles', []): identity.provides.add(RoleNeed(role.name)) identity.user = current_user
Example #3
Source File: permissions.py From training with MIT License | 5 votes |
def owner_manager_permission_factory(record=None): """Returns permission for managers group.""" return Permission(UserNeed(record["owner"]), RoleNeed('managers'))
Example #4
Source File: permissions.py From training with MIT License | 5 votes |
def owner_permission_factory(record=None): """Permission factory with owner access.""" return Permission(UserNeed(record["owner"]))
Example #5
Source File: permissions.py From training with MIT License | 5 votes |
def owner_permission_factory(record=None): """Permission factory with owner access.""" return Permission(UserNeed(record["owner"]))
Example #6
Source File: view_admin.py From flicket with MIT License | 5 votes |
def on_identity_loaded(sender, identity): # set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) # Assuming the User model has a list of groups, update the # identity with the groups that the user provides if hasattr(current_user, 'flicket_groups'): the_user = FlicketUser.query.filter_by(id=current_user.id).first() for g in the_user.flicket_groups: identity.provides.add(RoleNeed('{}'.format(g.group_name)))
Example #7
Source File: decorators.py From flask-react-spa with MIT License | 5 votes |
def auth_required_same_user(*args, **kwargs): """Decorator for requiring an authenticated user to be the same as the user in the URL parameters. By default the user url parameter name to lookup is 'id', but this can be customized by passing an argument: @auth_require_same_user('user_id') @bp.route('/users/<int:user_id>/foo/<int:id>') def get(user_id, id): # do stuff Any keyword arguments are passed along to the @auth_required decorator, so roles can also be specified in the same was as it, eg: @auth_required_same_user('user_id', role='ROLE_ADMIN') Aborts with HTTP 403: Forbidden if the user-check fails """ auth_kwargs = {} user_id_parameter_name = 'id' if not was_decorated_without_parenthesis(args): auth_kwargs = kwargs if args and isinstance(args[0], str): user_id_parameter_name = args[0] def wrapper(fn): @wraps(fn) @auth_required(**auth_kwargs) def decorated(*args, **kwargs): try: user_id = request.view_args[user_id_parameter_name] except KeyError: raise KeyError('Unable to find the user lookup parameter ' f'{user_id_parameter_name} in the url args') if not Permission(UserNeed(user_id)).can(): abort(HTTPStatus.FORBIDDEN) return fn(*args, **kwargs) return decorated if was_decorated_without_parenthesis(args): return wrapper(args[0]) return wrapper
Example #8
Source File: main.py From FlowKit with Mozilla Public License 2.0 | 5 votes |
def on_identity_loaded(sender, identity): """Helper for flask-principal.""" # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, "id"): identity.provides.add(UserNeed(current_user.id)) try: if current_user.is_admin: identity.provides.add(RoleNeed("admin")) except AttributeError: pass # Definitely not an admin
Example #9
Source File: app.py From maple-bbs with GNU General Public License v3.0 | 5 votes |
def init_app(app): @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): '''基础权限''' identity.user = current_user if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, 'is_superuser'): if current_user.is_superuser: identity.provides.add(RoleNeed('super')) if hasattr(current_user, 'is_confirmed'): if current_user.is_confirmed: identity.provides.add(RoleNeed('confirmed')) if hasattr(current_user, 'is_authenticated'): if current_user.is_authenticated: identity.provides.add(RoleNeed('auth')) else: identity.provides.add(RoleNeed('guest')) if hasattr(current_user, 'topics'): for topic in current_user.topics: identity.provides.add(TopicNeed(topic.id)) if hasattr(current_user, 'replies'): for reply in current_user.replies: identity.provides.add(ReplyNeed(reply.id)) if hasattr(current_user, 'collects'): for collect in current_user.collects: identity.provides.add(CollectNeed(collect.id))
Example #10
Source File: auth.py From knowledge-repo with Apache License 2.0 | 5 votes |
def populate_identity_roles(identity, user=None): identity.user = user if user is None or user.is_anonymous: if current_app.config['POLICY_ANONYMOUS_VIEW_INDEX']: identity.provides.add(roles.index_view) if current_app.config['POLICY_ANONYMOUS_VIEW_POST']: identity.provides.add(roles.post_view) if current_app.config['POLICY_ANONYMOUS_VIEW_STATS']: identity.provides.add(roles.stats_view) if current_app.config['POLICY_ANONYMOUS_VIEW_TAGS']: identity.provides.add(roles.tags_view) if current_app.config['POLICY_ANONYMOUS_DOWNLOADS']: identity.provides.add(roles.post_download) else: identity.provides.add(UserNeed(user.identifier)) identity.provides.add(roles.index_view) identity.provides.add(roles.post_view) identity.provides.add(roles.post_edit) identity.provides.add(roles.post_comment) identity.provides.add(roles.post_download) identity.provides.add(roles.stats_view) identity.provides.add(roles.tags_view) # TODO: Populate group permissions, and port existing group admin # code to roles. return identity
Example #11
Source File: __init__.py From AstroBox with GNU Affero General Public License v3.0 | 5 votes |
def on_identity_loaded(sender, identity): user = load_user(identity.id) if user is None: return identity.provides.add(UserNeed(user.get_name())) if user.is_user(): identity.provides.add(RoleNeed("user")) if user.is_admin(): identity.provides.add(RoleNeed("admin"))
Example #12
Source File: service.py From lemur with Apache License 2.0 | 5 votes |
def on_identity_loaded(sender, identity): """ Sets the identity of a given option, assigns additional permissions based on the role that the user is a part of. :param sender: :param identity: """ # load the user user = user_service.get(identity.id) # add the UserNeed to the identity identity.provides.add(UserNeed(identity.id)) # identity with the roles that the user provides if hasattr(user, "roles"): for role in user.roles: identity.provides.add(RoleNeed(role.name)) identity.provides.add(RoleMemberNeed(role.id)) # apply ownership for authorities if hasattr(user, "authorities"): for authority in user.authorities: identity.provides.add(AuthorityCreatorNeed(authority.id)) g.user = user
Example #13
Source File: __init__.py From flaskapp with MIT License | 5 votes |
def on_identity_loaded(sender, identity): """Method for Flask Principal identity load listener """ # set the identity user object identity.user = current_user if current_user.is_authenticated: # add UserNeed to identity identity.provides.add(UserNeed(current_user.id))
Example #14
Source File: core.py From flask-security with MIT License | 5 votes |
def _on_identity_loaded(sender, identity): if hasattr(current_user, "fs_uniquifier"): identity.provides.add(UserNeed(current_user.fs_uniquifier)) for role in getattr(current_user, "roles", []): identity.provides.add(RoleNeed(role.name)) for fsperm in role.get_permissions(): identity.provides.add(FsPermNeed(fsperm)) identity.user = current_user
Example #15
Source File: permissions.py From invenio-app-ils with MIT License | 5 votes |
def record_needs(self): """Create needs of the record.""" needs = [] for access_entity in self.record_explicit_restrictions(): try: if isinstance(access_entity, string_types): needs.append(UserNeed(int(access_entity))) elif isinstance(access_entity, int): needs.append(UserNeed(access_entity)) except ValueError: needs.append(RoleNeed(access_entity.lower())) return needs
Example #16
Source File: permissions.py From invenio-app-ils with MIT License | 5 votes |
def __init__(self, record): """Constructor.""" super(PatronOwnerPermission, self).__init__( UserNeed(int(record["patron_pid"])), backoffice_access_action )
Example #17
Source File: permissions.py From invenio-app-ils with MIT License | 5 votes |
def patron_permission(patron_pid): """Return a permission for the given patron.""" return Permission(UserNeed(int(patron_pid)), backoffice_access_action)
Example #18
Source File: test_loan_checkout.py From invenio-app-ils with MIT License | 4 votes |
def test_force_checkout_specific_permissions( app, client, json_headers, users, testdata ): """Test that only allowed users can perform a force checkout.""" default_factory = app.config["ILS_VIEWS_PERMISSIONS_FACTORY"] librarian2 = users["librarian2"] # override default permission factory to require specific permission for # force-checkout action def custom_views_permissions_factory(action): if action == "circulation-loan-force-checkout": # fake permission for a specific user return Permission(UserNeed(librarian2.id)) else: return default_factory(action) app.config[ "ILS_VIEWS_PERMISSIONS_FACTORY" ] = custom_views_permissions_factory # prepare request url = url_for("invenio_app_ils_circulation.loan_checkout") params = deepcopy(NEW_LOAN) params["force"] = True params["item_pid"] = dict(type="pitmid", value="itemid-MISSING") params["transaction_user_pid"] = str(librarian2.id) # force-checkout as librarian should fail user_login(client, "librarian", users) res = client.post(url, headers=json_headers, data=json.dumps(params)) assert res.status_code == 403 # force-checkout as librarian2 should succeed user_login(client, "librarian2", users) res = client.post(url, headers=json_headers, data=json.dumps(params)) assert res.status_code == 202 loan = res.get_json()["metadata"] assert loan["state"] == "ITEM_ON_LOAN" assert loan["item_pid"] == params["item_pid"] assert loan["document_pid"] == params["document_pid"] assert loan["patron_pid"] == params["patron_pid"] # restore default config app.config["ILS_VIEWS_PERMISSIONS_FACTORY"] = default_factory
Example #19
Source File: auth_required_same_user.py From flask-unchained with MIT License | 4 votes |
def auth_required_same_user(*args, **kwargs): """ Decorator for requiring an authenticated user to be the same as the user in the URL parameters. By default the user url parameter name to lookup is ``id``, but this can be customized by passing an argument:: @auth_require_same_user('user_id') @bp.route('/users/<int:user_id>/foo/<int:id>') def get(user_id, id): # do stuff Any keyword arguments are passed along to the @auth_required decorator, so roles can also be specified in the same was as it, eg:: @auth_required_same_user('user_id', role='ROLE_ADMIN') Aborts with ``HTTP 403: Forbidden`` if the user-check fails. """ auth_kwargs = {} user_id_parameter_name = 'id' if not (args and callable(args[0])): auth_kwargs = kwargs if args and isinstance(args[0], str): user_id_parameter_name = args[0] def wrapper(fn): @wraps(fn) @auth_required(**auth_kwargs) def decorated(*args, **kwargs): try: user_id = request.view_args[user_id_parameter_name] except KeyError: raise KeyError('Unable to find the user lookup parameter ' f'{user_id_parameter_name} in the url args') if not Permission(UserNeed(user_id)).can(): abort(HTTPStatus.FORBIDDEN) return fn(*args, **kwargs) return decorated if args and callable(args[0]): return wrapper(args[0]) return wrapper
Example #20
Source File: __init__.py From incepiton-mysql with MIT License | 4 votes |
def create_app(config_name): """ application initialization :param config_name: :return: """ app = Flask(__name__) app.config.from_object(config[config_name]) mail.init_app(app) db.init_app(app) login_manager.init_app(app) ldap.init_app(app) # flask_principal principals.init_app(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, 'role'): identity.provides.add(RoleNeed(current_user.role)) # celery celery.init_app(app) # register blue_print from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint) from .audit import audit as audit_blueprint app.register_blueprint(audit_blueprint) from .dev import dev as dev_blueprint app.register_blueprint(dev_blueprint) return app