Python flask.current_app.testing() Examples

The following are 19 code examples of flask.current_app.testing(). 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.current_app , or try the search function .
Example #1
Source File: validators.py    From jbox with MIT License 8 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #2
Source File: application.py    From BhagavadGita with GNU General Public License v3.0 6 votes vote down vote up
def insecure_transport(self):
        """Creates a context to enable the oauthlib environment variable in
        order to debug with insecure transport.
        """
        origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT')
        if current_app.debug or current_app.testing:
            try:
                os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
                yield
            finally:
                if origin:
                    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin
                else:
                    os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None)
        else:
            if origin:
                warnings.warn(
                    'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ '
                    'but the app is not running in debug mode or testing mode.'
                    ' It may put you in danger of the Man-in-the-middle attack'
                    ' while using OAuth 2.', RuntimeWarning)
            yield 
Example #3
Source File: validators.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #4
Source File: ssl.py    From zeus with Apache License 2.0 6 votes vote down vote up
def redirect_to_ssl(self):
        """
        Redirect incoming requests to HTTPS.
        """
        criteria = [
            request.is_secure,
            current_app.debug,
            current_app.testing,
            request.headers.get("X-Forwarded-Proto", "http") == "https",
        ]

        if (
            request.headers.get("User-Agent", "")
            .lower()
            .startswith(self.exclude_user_agents)
        ):
            return

        if not any(criteria):
            if request.url.startswith("http://"):
                url = request.url.replace("http://", "https://", 1)
                r = redirect(url, code=301)
                return r 
Example #5
Source File: auth.py    From flask-base-api with MIT License 6 votes vote down vote up
def password_recovery():
    ''' creates a password_recovery_hash and sends email to user (assumes login=email)'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    email = post_data.get('email')
    if not email:
        raise InvalidPayload()

    # fetch the user data
    user = User.first_by(email=email)
    if user:
        token = user.encode_password_token()
        with session_scope(db.session):
            user.token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        if not current_app.testing:
            from project.api.common.utils.mails import send_password_recovery_email
            send_password_recovery_email(user, token.decode())  # send recovery email
        return {
            'status': 'success',
            'message': 'Successfully sent email with password recovery.',
        }
    else:
        raise NotFoundException(message='Login/email does not exist, please write a valid login/email') 
Example #6
Source File: email_validation.py    From flask-base-api with MIT License 6 votes vote down vote up
def email_verification(user_id):
    ''' creates a email_token_hash and sends email with token to user (assumes login=email), idempotent (could be use for resend)'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    email = post_data.get('email')
    if not email:
        raise InvalidPayload()

    # fetch the user data
    user = User.first_by(email=email)
    if user:
        token = user.encode_email_token()
        with session_scope(db.session):
            user.email_token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        if not current_app.testing:
            from project.api.common.utils.mails import send_email_verification_email
            send_email_verification_email(user, token.decode())  # send recovery email
        return {
            'status': 'success',
            'message': 'Successfully sent email with email verification.',
        }
    else:
        raise NotFoundException(message='Login/email does not exist, please write a valid login/email') 
Example #7
Source File: models.py    From kqueen with MIT License 5 votes vote down vote up
def save(self, check_status=True, **kwargs):
        # While used in async method, app context is not available by default
        # and needs to be imported
        from flask import current_app as app
        from kqueen.server import create_app
        try:
            if not app.testing:
                app = create_app()
        except RuntimeError:
            app = create_app()

        with app.app_context():
            if check_status:
                self.state = self.engine_status(save=False)
            self.verbose_name = getattr(self.get_engine_cls(), 'verbose_name', self.engine)
            return super().save(**kwargs)


#
# AUTHENTICATION
# 
Example #8
Source File: smtp_email_adapter.py    From Flask-User with MIT License 5 votes vote down vote up
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
        """ Send email message via Flask-Mail.

        Args:
            recipient: Email address or tuple of (Name, Email-address).
            subject: Subject line.
            html_message: The message body in HTML.
            text_message: The message body in plain text.
        """

        # Construct sender from sender_name and sender_email
        sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email

        # Send email via SMTP except when we're testing
        if not current_app.testing:  # pragma: no cover
            try:
                # Prepare email message
                from flask_mail import Message
                message = Message(
                    subject,
                    sender=sender,
                    recipients=[recipient],
                    html=html_message,
                    body=text_message)

                # Send email message
                self.mail.send(message)

            # Print helpful error messages on exceptions
            except (socket.gaierror, socket.error) as e:
                raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')
            except smtplib.SMTPAuthenticationError:
                raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.') 
Example #9
Source File: forms.py    From flask-unchained with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if app.testing:
            self.TIME_LIMIT = None
        super().__init__(*args, **kwargs) 
Example #10
Source File: tasks.py    From flask-unchained with MIT License 5 votes vote down vote up
def _send_mail_async(subject_or_message=None, to=None, template=None, **kwargs):
    subject_or_message = subject_or_message or kwargs.pop('subject')
    if current_app and current_app.testing:
        return async_mail_task.apply([subject_or_message, to, template], kwargs)
    return async_mail_task.delay(subject_or_message, to, template, **kwargs) 
Example #11
Source File: decorators.py    From commandment with MIT License 5 votes vote down vote up
def verify_mdm_signature(f):
    """Verify the signature supplied by the client in the request using the ``Mdm-Signature`` header.

    If the authenticity of the message has been verified,
    then the signer is attached to the **g** object as **g.signer**.

    In unit tests, this decorator is completely disabled by the presence of app.testing = True.
    You can also disable enforcement in dev by setting the flask setting DEBUG to true.

    :reqheader Mdm-Signature: BASE64-encoded CMS Detached Signature of the message. (if `SignMessage` was true)
    """
    @wraps(f)
    def decorator(*args, **kwargs):
        if current_app.testing:
            return f(*args, **kwargs)

        if 'Mdm-Signature' not in request.headers:
            raise TypeError('Client did not supply an Mdm-Signature header but signature is required.')

        detached_signature = b64decode(request.headers['Mdm-Signature'])

        try:
            signers, signed_data = _verify_cms_signers(detached_signature, detached=True)
            g.signers = signers
            g.signed_data = signed_data
        except InvalidSignature as e:
            current_app.logger.warn("Invalid Signature in Mdm-Signature header")
            if not current_app.config.get('DEBUG', False):
                return abort(403)

        return f(*args, **kwargs)

    return decorator 
Example #12
Source File: decorators.py    From commandment with MIT License 5 votes vote down vote up
def verify_cms_signers(f):
    """Verify the signers of a request containing a CMS/PKCS#7, DER encoded body.

    The certificate of each signer is placed on the global **g** variable as **g.signers** and the signed data is
    set as **g.signed_data**.

    In unit tests, this decorator is completely disabled by the presence of testing = True

    Raises:
          - TypeError if *Content-Type* header is not "application/pkcs7-signature"
          - SigningError if any signer on the CMS content is not valid.
    """
    @wraps(f)
    def decorator(*args, **kwargs):
        if current_app.testing:
            return f(*args, **kwargs)

        current_app.logger.debug('Verifying CMS Request Data for request to %s', request.url)

        if request.headers['Content-Type'] != "application/pkcs7-signature":
            raise TypeError("verify_cms_signers expects application/pkcs7-signature, got: {}".format(
                request.headers['Content-Type']))

        g.signers, g.signed_data = _verify_cms_signers(request.data)

        return f(*args, **kwargs)

    return decorator 
Example #13
Source File: phone_validation.py    From flask-base-api with MIT License 5 votes vote down vote up
def register_user_cellphone(user_id: int):
    ''' generates cellphone_validation_code, idempotent (could be used for resend cellphone_validation_code)
        allows just 1 user per cellphone validation!
    '''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    cellphone_number = post_data.get('cellphone_number')
    cellphone_cc = post_data.get('cellphone_cc')
    if not cellphone_number or not cellphone_cc:
        raise InvalidPayload()
    user = User.get(user_id)
    if user.cellphone_validation_date and user.cellphone_number == cellphone_number and user.cellphone_cc == cellphone_cc:
        raise BusinessException(message='Registered. You have already registered this cellphone number.')

    cellphone_validation_code, cellphone_validation_code_expiration = User.generate_cellphone_validation_code()
    with session_scope(db.session) as session:
        user.cellphone_number = cellphone_number
        user.cellphone_cc = cellphone_cc
        user.cellphone_validation_code = cellphone_validation_code
        user.cellphone_validation_code_expiration = cellphone_validation_code_expiration
        user.cellphone_validation_date = None

    if not current_app.testing:
        from project.api.common.utils.twilio import send_cellphone_verification_code
        send_cellphone_verification_code(user, cellphone_validation_code)

    return {
        'status': 'success',
        'message': 'Successfully sent validation code.'
    } 
Example #14
Source File: views.py    From DeepChatModels with MIT License 5 votes vote down vote up
def __init__(self, data_name):
        if ChatAPI.bot_name != data_name:
            ChatAPI.bot_name = data_name
            ChatAPI.bot = web_bot.FrozenBot(frozen_model_dir=data_name,
                                            is_testing=current_app.testing)
            config = ChatAPI.bot.config
            _ = get_database_model('Chatbot',
                                   filter=ChatAPI.bot_name,
                                   dataset=config['dataset'],
                                   **config['model_params'])
            db.session.commit()
            # TODO: delete this after refactor rest of file.
            session['data_name'] = data_name 
Example #15
Source File: forms.py    From flask-security with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if current_app.testing:
            self.TIME_LIMIT = None
        super().__init__(*args, **kwargs) 
Example #16
Source File: app.py    From flask-security with MIT License 5 votes vote down vote up
def create_users():
    if current_app.testing:
        return
    db.create_all()
    user_datastore.create_role(
        name="admin",
        permissions={"admin-read", "admin-write", "user-read", "user-write"},
    )
    user_datastore.create_role(name="monitor", permissions={"admin-read", "user-read"})
    user_datastore.create_role(name="user", permissions={"user-read", "user-write"})
    user_datastore.create_role(name="reader", permissions={"user-read"})

    user_datastore.create_user(
        email="admin@me.com", password=hash_password("password"), roles=["admin"]
    )
    user_datastore.create_user(
        email="ops@me.com", password=hash_password("password"), roles=["monitor"]
    )
    real_user = user_datastore.create_user(
        email="user@me.com", password=hash_password("password"), roles=["user"]
    )
    user_datastore.create_user(
        email="reader@me.com", password=hash_password("password"), roles=["reader"]
    )

    # create initial blog
    blog = app.blog_cls(text="my first blog", user=real_user)
    db.session.add(blog)
    db.session.commit()
    print(f"First blog id {blog.id}")


# Views
# Note that we always add @auth_required so that if a client isn't logged in
# we will get a proper '401' and redirected to login page. 
Example #17
Source File: kubernetes.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def fetch_data(gs, url):
  """Fetches a URL from Kubernetes (production) or reads it from a file (test).

  The file name is derived from the URL in the following way:
  The file name is 'testdata/' + last element of the URL + '.input.json'.

  For example, if the URL is 'https://host:port/api/v1beta3/path/to/resource',
  then the file name is 'testdata/resource.input.json'.

  The input is always JSON. It is converted to an internal representation
  by this routine.

  Args:
   gs: global state.
   url: the URL to fetch from Kubernetes in production.

  Returns:
    The contents of the URL (in production) or the contents of the file
    (in a test).

  Raises:
    IOError: if cannot open the test file.
    ValueError: if cannot convert the contents of the file to JSON.
    Other exceptions may be raised as the result of attempting to
    fetch the URL.
  """
  start_time = time.time()
  if app.testing:
    # Read the data from a file.
    url_elements = url.split('/')
    fname = 'testdata/' + url_elements[-1] + '.input.json'
    v = json.loads(open(fname, 'r').read())
    gs.add_elapsed(start_time, fname, time.time() - start_time)
    return v
  else:
    # Send the request to Kubernetes
    headers = get_kubernetes_headers()
    v = requests.get(url, headers=headers, verify=False).json()
    gs.add_elapsed(start_time, url, time.time() - start_time)
    return v 
Example #18
Source File: auth.py    From flask-base-api with MIT License 4 votes vote down vote up
def register_user():
    # get post data
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    username = post_data.get('username')
    email = post_data.get('email')
    password = post_data.get('password')
    if not password or not username or not email:
        raise InvalidPayload()
    # check for existing user
    user = User.first(or_(User.username == username, User.email == email))
    if not user:
        # add new user to db
        new_user = User(username=username, email=email, password=password)
        with session_scope(db.session) as session:
            session.add(new_user)

        # need another scope if not new_user does not exists yet
        with session_scope(db.session) as session:
            token = new_user.encode_email_token()
            new_user.email_token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()

        if not current_app.testing:
            from project.api.common.utils.mails import send_registration_email
            send_registration_email(new_user, token.decode())

        # save the device
        if all(x in request.headers for x in [Constants.HttpHeaders.DEVICE_ID, Constants.HttpHeaders.DEVICE_TYPE]):
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device_type = request.headers.get(Constants.HttpHeaders.DEVICE_TYPE)
            with session_scope(db.session):
                Device.create_or_update(device_id=device_id, device_type=device_type, user=user)
        # generate auth token
        auth_token = new_user.encode_auth_token()
        return {
            'status': 'success',
            'message': 'Successfully registered.',
            'auth_token': auth_token.decode()
        }, 201
    else:
        # user already registered, set False to device.active
        if Constants.HttpHeaders.DEVICE_ID in request.headers:
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device = Device.first_by(device_id=device_id)
            if device:
                with session_scope(db.session):
                    device.active = False
        raise BusinessException(message='Sorry. That user already exists.') 
Example #19
Source File: models.py    From kqueen with MIT License 4 votes vote down vote up
def save(self, **kwargs):
        # While used in async method, app context is not available by default
        # and needs to be imported
        from flask import current_app as app
        from kqueen.server import create_app

        try:
            if not app.testing:
                app = create_app()
        except RuntimeError:
            app = create_app()

        with app.app_context():
            return super().save(**kwargs)