Python check authorization

25 Python code examples are found related to " check authorization". 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.
Example 1
Source File: github.py    From aegea with Apache License 2.0 6 votes vote down vote up
def check_authorization(self, access_token):
        """OAuth applications can use this method to check token validity
        without hitting normal rate limits because of failed login attempts.
        If the token is valid, it will return True, otherwise it will return
        False.

        :returns: bool
        """
        p = self._session.params
        auth = (p.get('client_id'), p.get('client_secret'))
        if access_token and auth:
            url = self._build_url('applications', str(auth[0]), 'tokens',
                                  str(access_token))
            resp = self._get(url, auth=auth, params={
                'client_id': None, 'client_secret': None
            })
            return self._boolean(resp, 200, 404)
        return False 
Example 2
Source File: server.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_authorization(self):
		# don't require authentication for non-RPC requests
		cmd = self.command
		if cmd == 'GET':
			# check if the GET request is to open a web socket
			if 'upgrade' not in self.headers:
				return True
		elif cmd != 'RPC':
			return True

		if not ipaddress.ip_address(self.client_address[0]).is_loopback:
			return False

		# the only two RPC methods that do not require authentication
		if self.path in ('/login', '/version'):
			return True
		self.rpc_session = self.server.session_manager.get(self.rpc_session_id)
		if not isinstance(self.rpc_session, aaa.AuthenticatedSession):
			self.logger.warning("request authorization failed (RPC session id is {0})".format('None' if self.rpc_session_id is None else 'invalid'))
			return False
		return True 
Example 3
Source File: generic_views.py    From kqueen with MIT License 6 votes vote down vote up
def check_authorization(self):
        # get user data
        if current_identity:
            user = current_identity.get_dict()
        else:
            return False

        policy_value = self.get_policy_value()
        if not policy_value:
            return False

        if isinstance(self.obj, list):
            allowed = []
            for obj in self.obj:
                if is_authorized(user, policy_value, resource=obj):
                    allowed.append(obj)
            self.obj = allowed
        # if there is single object raise if user doesn't have access to it
        else:
            if not is_authorized(user, policy_value, resource=self.obj):
                raise JWTError('Insufficient permissions',
                               'Your user account is lacking the necessary '
                               'permissions to perform this operation') 
Example 4
Source File: ibflask.py    From InfraBox with Apache License 2.0 6 votes vote down vote up
def check_request_authorization():
    try:
        # Assemble Input Data for Open Policy Agent
        opa_input = {
            "input": {
                "method": request.method,
                "path": get_path_array(request.path),
                "token": g.token,
            }
        }

        original_method = dict(request.headers).get('X-Original-Method', None)
        if original_method is not None:
            opa_input["input"]["original_method"] = original_method

        from pyinfraboxutils.ibopa import opa_do_auth
        is_authorized = opa_do_auth(opa_input)

        if not is_authorized:
            logger.info("Rejected unauthorized request")
            abort(401, 'Unauthorized')

    except requests.exceptions.RequestException as e:
        logger.error(e)
        abort(500, 'Authorization failed') 
Example 5
Source File: handlers.py    From go-links with Apache License 2.0 6 votes vote down vote up
def check_authorization(self):
    if not self.user_email:
      request_data = {
        'origin': self.request.headers.get('Origin'),
        'method': self.request.method,
        'path': self.request.path,
        'body': self.request.body
      }

      if 'slack' in self.request.path_url:
        self.abort(400)  # Guard against leaking Slack token or other sensitive data in response

      self.redirect_to = '%s/play_queued_request?r=%s' % (self.request.path_url.rstrip('/'),
                                                          base64.urlsafe_b64encode(json.dumps(request_data)))

    if (not env.current_env_is_local()
        and self.request.method not in ['GET', 'OPTIONS']
        and self.request.headers.get('X-CSRF') != self.session.get('csrf_token')):
      self.abort(401) 
Example 6
Source File: user.py    From hydrus with MIT License 5 votes vote down vote up
def check_authorization(request: LocalProxy, session: Session) -> bool:
    """Check if the request object has the correct authorization."""
    auth = request.authorization
    if check_nonce(request, session):
        return authenticate_user(auth.username, auth.password, session)
    return False 
Example 7
Source File: manager.py    From manager with GNU General Public License v3.0 5 votes vote down vote up
def check_authorization_wrapper(permission_needed=None, permission_object_type=None):

    def callable_function(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            result = jsonify({"access_allowed": False}), 403
            if permission_object_type == "pruning":
                if check_authorized(permission_needed={"pruning": permission_needed},
                                    permission_object_type=permission_object_type) is True:
                    result = func(*args, **kwargs)
            elif permission_object_type == "apps":
                if check_authorized(permission_needed={kwargs['app_name']: permission_needed},
                                    permission_object_type=permission_object_type) is True:
                    result = func(*args, **kwargs)
            elif permission_object_type == "device_groups":
                if check_authorized(permission_needed={kwargs['device_group']: permission_needed},
                                    permission_object_type=permission_object_type) is True:
                    result = func(*args, **kwargs)
            elif permission_object_type == "cron_jobs":
                if check_authorized(permission_needed={kwargs['cron_job']: permission_needed},
                                    permission_object_type=permission_object_type) is True:
                    result = func(*args, **kwargs)
            elif permission_object_type == "admin":
                if check_authorized(permission_needed={"admin": permission_needed},
                                    permission_object_type=permission_object_type) is True:
                    result = func(*args, **kwargs)
            return result
        return wrapped

    return callable_function


# read config file at startup 
Example 8
Source File: actor.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def check_authorization_decision(self):
        """Check if authorization decision is still valid"""
        if self.authorization_checks:
            if any(isinstance(elem, list) for elem in self.authorization_checks):
                # If list of lists, True must be found in each list.
                for plugin_list in self.authorization_checks:
                    if not check_authorization_plugin_list(plugin_list):
                        return False
                return True
            else:
                return check_authorization_plugin_list(self.authorization_checks)
        return True 
Example 9
Source File: __init__.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def check_authorization_plugin_list(plugin_list):
    authorization_results = []
    for plugin in plugin_list:
        try:
            authorization_results.append(authz_plugins[plugin["id"]].authorization_check(**plugin["attributes"]))
        except Exception:
            return False
    # At least one of the authorization checks for the plugins must return True.
    return True in authorization_results 
Example 10
Source File: __init__.py    From mautrix-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_authorization(self, request: web.Request) -> Optional[web.Response]:
        auth = request.headers.get("Authorization", "")
        if auth != f"Bearer {self.secret}":
            return self.get_error_response(error="Shared secret is not valid.",
                                           errcode="shared_secret_invalid",
                                           status=401)
        return None 
Example 11
Source File: transaction.py    From pypaystack with MIT License 5 votes vote down vote up
def check_authorization(self, **kwargs):
        """
        :data:{
            authorization_code,
            email,
            amount
        }"""
        path = "/transaction/check_authorization"
        json_data = {
            'authorization_code': kwargs['authorization_code'],
            'email': kwargs['email'],
            'amount': kwargs['amount'] * 100
        }
        response = self.make_request('POST', path, json=json_data)
        return self.result_format(response) 
Example 12
Source File: utils.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def check_authorization(request):
    """ Check if authed """
    if request.token:
        encoded = request.token.split(' ')[1]
        authentication = base64.b64decode(encoded).decode('utf-8')

        login = authentication.split(':')[0]
        password = authentication.split(':')[1]

        if login == CONFIG['application']['username'] and password == CONFIG['application']['password']:
            return True

    return False 
Example 13
Source File: userauth.py    From confidant with Apache License 2.0 5 votes vote down vote up
def check_authorization(self):
        email = self.current_email()

        if not self.passes_email_suffix(email):
            msg = 'User {!r} does not have email suffix {!r}'.format(
                email, self.allowed_email_suffix)
            raise errors.NotAuthorized(msg)

        if not self.passes_email_whitelist(email):
            msg = 'User not in whitelist: {!r}'.format(
                email, self.allowed_email_whitelist)
            raise errors.NotAuthorized(msg)

        return True 
Example 14
Source File: flask_bouncer.py    From flask-bouncer with MIT License 5 votes vote down vote up
def check_authorization(self, response):
        """checks that an authorization call has been made during the request"""
        if not hasattr(request, '_authorized'):
            raise Forbidden
        elif not request._authorized:
            raise Forbidden
        return response 
Example 15
Source File: scheduler.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def checkAuthorization(self):
        # Must have an authenticated user
        if not self.internal_request and self.originator_uid == None:
            log.error(
                "Unauthenticated originators not allowed: {o}",
                o=self.originator,
            )
            raise HTTPError(self.errorResponse(
                responsecode.FORBIDDEN,
                self.errorElements["originator-denied"],
                "Invalid originator",
            )) 
Example 16
Source File: indexd.py    From fence with Apache License 2.0 5 votes vote down vote up
def check_authorization(self, action):
        # if we have a data file upload without corresponding metadata, the record can
        # have just the `uploader` field and no ACLs. in this just check that the
        # current user's username matches the uploader field
        if self.index_document.get("uploader"):
            logger.info("Checking access using `uploader` value")
            username = None
            if flask.g.token:
                username = flask.g.token["context"]["user"]["name"]
            else:
                username = flask.g.user.username
            return self.index_document.get("uploader") == username

        try:
            action_to_method = {"upload": "write-storage", "download": "read-storage"}
            method = action_to_method[action]
            # action should be upload or download
            # return bool for authorization
            return self.check_authz(method)
        except ValueError:
            # this is ok; we'll default to ACL field (previous behavior)
            # may want to deprecate in future
            logger.info(
                "Couldn't find `authz` field on indexd record, falling back to `acl`."
            )

        given_acls = set(filter_auth_ids(action, flask.g.user.project_access))

        return len(self.set_acls & given_acls) > 0 
Example 17
Source File: cluster_monitor.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def check_authorization(self, retry_count):
        if retry_count == 0:
            raise Exception('init k8s client failed! retry_count=' + str(retry_count))
        self.retry_count = retry_count - 1
        try:
            self.api_instance.list_node()
        except ApiException as e:
            if e.status == 401:
                self.push_token_to_redis()
            else:
                logger.error(msg='init k8s client failed ' + e.reason, exc_info=True) 
Example 18
Source File: auth_svc.py    From caldera with Apache License 2.0 5 votes vote down vote up
def check_authorization(func):
    """
    Authorization Decorator
    This requires that the calling class have `self.auth_svc` set to the authentication service.
    """
    async def process(func, *args, **params):
        return await func(*args, **params)

    async def helper(*args, **params):
        await args[0].auth_svc.check_permissions('app', args[1])
        result = await process(func, *args, **params)
        return result
    return helper 
Example 19
Source File: auth.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def check_edit_authorization(request, board, has_creator=None):
    """Raise a PermissionDenied exception if the user does not have edit rights for the resource.

    :param request: a Django request object
    :param board: the Board context
    :param has_creator: a model that has a creator member, or None
    """
    if not has_edit_authorization(request, board, has_creator=has_creator):
        raise PermissionDenied() 
Example 20
Source File: users.py    From jumpserver-python-sdk with GNU General Public License v2.0 5 votes vote down vote up
def check_user_with_authorization(self, authorization):
        try:
            headers = {"Authorization": authorization}
            resp = self.http.get('user-profile', headers=headers, use_auth=False)
        except (ResponseError, ResponseError):
            return None
        return User.from_json(resp.json()) 
Example 21
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 4 votes vote down vote up
def check_wildcard_dmarc_report_authorization(domain,
                                              nameservers=None,
                                              timeout=2.0):
    """
    Checks for a wildcard DMARC report authorization record, e.g.:

    ::

      *._report.example.com IN TXT "v=DMARC1"

    Args:
        domain (str): The domain to check
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        bool: An indicator of the existence of a valid wildcard DMARC report
        authorization record
    """
    wildcard_target = "*._report._dmarc.{0}".format(domain)
    dmarc_record_count = 0
    unrelated_records = []
    try:
        records = _query_dns(wildcard_target, "TXT",
                             nameservers=nameservers,
                             timeout=timeout)

        for record in records:
            if record.startswith("v=DMARC1"):
                dmarc_record_count += 1
            else:
                unrelated_records.append(record)

        if len(unrelated_records) > 0:
            raise UnrelatedTXTRecordFoundAtDMARC(
                "Unrelated TXT records were discovered. "
                "These should be removed, as some "
                "receivers may not expect to find unrelated TXT records "
                "at {0}\n\n{1}".format(wildcard_target,
                                       "\n\n".join(unrelated_records)))

        if dmarc_record_count < 1:
            return False
    except Exception:
        return False

    return True 
Example 22
Source File: util.py    From bot with GNU General Public License v3.0 4 votes vote down vote up
def check_authorization(browser, username, method, logger, notify=True):
    """ Check if user is NOW logged in """
    if notify is True:
        logger.info("Checking if '{}' is logged in...".format(username))

    # different methods can be added in future
    if method == "activity counts":

        # navigate to owner's profile page only if it is on an unusual page
        current_url = get_current_url(browser)
        if (
            not current_url
            or "https://www.instagram.com" not in current_url
            or "https://www.instagram.com/graphql/" in current_url
        ):
            profile_link = "https://www.instagram.com/{}/".format(username)
            web_address_navigator(browser, profile_link)

        # if user is not logged in, `activity_counts` will be `None`- JS `null`
        try:
            activity_counts = browser.execute_script(
                "return window._sharedData.activity_counts"
            )

        except WebDriverException:
            try:
                browser.execute_script("location.reload()")
                update_activity(browser, state=None)

                activity_counts = browser.execute_script(
                    "return window._sharedData.activity_counts"
                )

            except WebDriverException:
                activity_counts = None

        # if user is not logged in, `activity_counts_new` will be `None`- JS
        # `null`
        try:
            activity_counts_new = browser.execute_script(
                "return window._sharedData.config.viewer"
            )

        except WebDriverException:
            try:
                browser.execute_script("location.reload()")
                activity_counts_new = browser.execute_script(
                    "return window._sharedData.config.viewer"
                )

            except WebDriverException:
                activity_counts_new = None

        if activity_counts is None and activity_counts_new is None:
            if notify is True:
                logger.critical("--> '{}' is not logged in!\n".format(username))
            return False

    return True 
Example 23
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 4 votes vote down vote up
def check_wildcard_dmarc_report_authorization(domain,
                                              nameservers=None,
                                              timeout=2.0):
    """
    Checks for a wildcard DMARC report authorization record, e.g.:

    ::

      *._report.example.com IN TXT "v=DMARC1"

    Args:
        domain (str): The domain to check
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        bool: An indicator of the existence of a valid wildcard DMARC report
        authorization record
    """
    wildcard_target = "*._report._dmarc.{0}".format(domain)
    dmarc_record_count = 0
    unrelated_records = []
    try:
        records = _query_dns(wildcard_target, "TXT",
                             nameservers=nameservers)

        for record in records:
            if record.startswith("v=DMARC1"):
                dmarc_record_count += 1
            else:
                unrelated_records.append(record)

        if len(unrelated_records) > 0:
            raise UnrelatedTXTRecordFoundAtDMARC(
                "Unrelated TXT records were discovered. "
                "These should be removed, as some "
                "receivers may not expect to find unrelated TXT records "
                "at {0}\n\n{1}".format(wildcard_target,
                                       "\n\n".join(unrelated_records)))

        if dmarc_record_count < 1:
            return False
    except Exception:
        return False

    return True 
Example 24
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def check_authorization(self):
		"""
		Check for the presence of a basic auth Authorization header and
		if the credentials contained within in are valid.

		:return: Whether or not the credentials are valid.
		:rtype: bool
		"""
		try:
			store = self.__config.get('basic_auth')
			if store is None:
				return True
			auth_info = self.headers.get('Authorization')
			if not auth_info:
				return False
			auth_info = auth_info.split()
			if len(auth_info) != 2 or auth_info[0] != 'Basic':
				return False
			auth_info = base64.b64decode(auth_info[1]).decode(sys.getdefaultencoding())
			username = auth_info.split(':')[0]
			password = ':'.join(auth_info.split(':')[1:])
			password_bytes = password.encode(sys.getdefaultencoding())
			if hasattr(self, 'custom_authentication'):
				if self.custom_authentication(username, password):
					self.basic_auth_user = username
					return True
				return False
			if not username in store:
				self.server.logger.warning('received invalid username: ' + username)
				return False
			password_data = store[username]

			if password_data['type'] == 'plain':
				if password == password_data['value']:
					self.basic_auth_user = username
					return True
			elif hashlib.new(password_data['type'], password_bytes).digest() == password_data['value']:
				self.basic_auth_user = username
				return True
			self.server.logger.warning('received invalid password from user: ' + username)
		except Exception:
			pass
		return False 
Example 25
Source File: client.py    From sewer with MIT License 4 votes vote down vote up
def check_authorization_status(self, authorization_url, desired_status=None):
        """
        https://tools.ietf.org/html/draft-ietf-acme-acme#section-7.5.1
        To check on the status of an authorization, the client sends a GET(polling)
        request to the authorization URL, and the server responds with the
        current authorization object.

        https://tools.ietf.org/html/draft-ietf-acme-acme#section-8.2
        Clients SHOULD NOT respond to challenges until they believe that the
        server's queries will succeed. If a server's initial validation
        query fails, the server SHOULD retry[intended to address things like propagation delays in
        HTTP/DNS provisioning] the query after some time.
        The server MUST provide information about its retry state to the
        client via the "errors" field in the challenge and the Retry-After
        """
        self.logger.info("check_authorization_status")
        desired_status = desired_status or ["pending", "valid"]
        number_of_checks = 0
        while True:
            time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD)
            check_authorization_status_response = self.make_signed_acme_request(
                authorization_url, payload=""
            )
            authorization_status = check_authorization_status_response.json()["status"]
            number_of_checks = number_of_checks + 1
            self.logger.debug(
                "check_authorization_status_response. status_code={0}. response={1}".format(
                    check_authorization_status_response.status_code,
                    log_response(check_authorization_status_response),
                )
            )
            if authorization_status in desired_status:
                break
            if number_of_checks == self.ACME_AUTH_STATUS_MAX_CHECKS:
                raise StopIteration(
                    "Checks done={0}. Max checks allowed={1}. Interval between checks={2}seconds.".format(
                        number_of_checks,
                        self.ACME_AUTH_STATUS_MAX_CHECKS,
                        self.ACME_AUTH_STATUS_WAIT_PERIOD,
                    )
                )

        self.logger.info("check_authorization_status_success")
        return check_authorization_status_response