Python flask.request.is_secure() Examples

The following are 17 code examples of flask.request.is_secure(). 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.request , or try the search function .
Example #1
Source File: csrf.py    From jbox with MIT License 8 votes vote down vote up
def protect(self):
        if request.method not in self._app.config['WTF_CSRF_METHODS']:
            return

        if not validate_csrf(self._get_csrf_token()):
            reason = 'CSRF token missing or incorrect.'
            return self._error_response(reason)

        if request.is_secure and self._app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                reason = 'Referrer checking failed - no Referrer.'
                return self._error_response(reason)

            good_referrer = 'https://%s/' % request.host
            if not same_origin(request.referrer, good_referrer):
                reason = 'Referrer checking failed - origin does not match.'
                return self._error_response(reason)

        request.csrf_valid = True  # mark this request is csrf valid 
Example #2
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def protect(self):
        if request.method not in current_app.config['WTF_CSRF_METHODS']:
            return

        try:
            validate_csrf(self._get_csrf_token())
        except ValidationError as e:
            logger.info(e.args[0])
            self._error_response(e.args[0])

        if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                self._error_response('The referrer header is missing.')

            good_referrer = 'https://{0}/'.format(request.host)

            if not same_origin(request.referrer, good_referrer):
                self._error_response('The referrer does not match the host.')

        g.csrf_valid = True  # mark this request as CSRF valid 
Example #3
Source File: markdown.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def nofollow_callback(attrs, new=False):
    """
    Turn relative links into external ones and avoid `nofollow` for us,

    otherwise add `nofollow`.
    That callback is not splitted in order to parse the URL only once.
    """

    if (None, 'href') not in attrs:
        return attrs
    parsed_url = urlparse(attrs[(None, 'href')])
    if parsed_url.netloc in ('', current_app.config['SERVER_NAME']):
        path = parsed_url.path
        attrs[(None, 'href')] = '{scheme}://{netloc}{path}'.format(
            scheme='https' if request.is_secure else 'http',
            netloc=current_app.config['SERVER_NAME'],
            path=path if path.startswith('/') else f'/{path}')
        return attrs
    else:
        rel = [x for x in attrs.get((None, 'rel'), '').split(' ') if x]
        if 'nofollow' not in [x.lower() for x in rel]:
            rel.append('nofollow')
        attrs[(None, 'rel')] = ' '.join(rel)
        return attrs 
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: models.py    From flask-blog with MIT License 5 votes vote down vote up
def gravatar(self, size=40, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.author_email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #6
Source File: models.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #7
Source File: models.py    From flask-blog with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #8
Source File: models.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #9
Source File: storage.py    From flask-fs with MIT License 5 votes vote down vote up
def _clean_url(self, url):
        if not url.startswith('http://') and not url.startswith('https://'):
            url = ('https://' if request.is_secure else 'http://') + url
        if not url.endswith('/'):
            url += '/'
        return url 
Example #10
Source File: models.py    From flasky-first-edition with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #11
Source File: userauth.py    From confidant with Apache License 2.0 5 votes vote down vote up
def log_in(self):
        response = flask.make_response()
        result = self.authomatic.login(
            WerkzeugAdapter(request, response),
            'google',
            session=session,
            session_saver=lambda: current_app.save_session(session, response),
            secure_cookie=(True if request.is_secure else False)
        )
        if result:
            if result.error:
                msg = 'Google auth failed with error: {0}'
                logger.error(msg.format(result.error))
                return abort(403)

            # successful login
            if result.user:
                result.user.update()
                user = result.user
                self.set_expiration()
                self.set_current_user(email=user.email,
                                      first_name=user.first_name,
                                      last_name=user.last_name)
                # TODO: find a way to save the angular args?
                # authomatic adds url params google auth has stripped the
                # angular args anyway, so let's just redirect back to the
                # index.
                resp = self.redirect_to_index()
                self.set_csrf_token(resp)
                return resp

        # Authomatic will have put a redirect in our response here.
        return response 
Example #12
Source File: ssl.py    From zeus with Apache License 2.0 5 votes vote down vote up
def set_hsts_header(self, response):
        """
        Adds HSTS header to each response.
        """
        if request.is_secure:
            response.headers.setdefault("Strict-Transport-Security", self.hsts_header)
        return response 
Example #13
Source File: models.py    From flask-pycon2014 with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or \
               hashlib.md5(self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating) 
Example #14
Source File: request.py    From pylti1.3 with MIT License 5 votes vote down vote up
def is_secure(self):
        return self._request_is_secure 
Example #15
Source File: request.py    From pylti1.3 with MIT License 5 votes vote down vote up
def __init__(self, cookies=None, session=None, request_data=None, request_is_secure=None):
        self._cookies = request.cookies if cookies is None else cookies
        self.session = flask_session if session is None else session
        self._request_is_secure = request.is_secure if request_is_secure is None else request_is_secure

        if request_data:
            self._request_data = request_data 
Example #16
Source File: sitemap.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_scheme(fn):
    @wraps(fn)
    def set_scheme_on_call(*args, **kwargs):
        scheme = 'https' if request.is_secure else 'http'
        current_app.config['SITEMAP_URL_SCHEME'] = scheme
        return fn(*args, **kwargs)
    return set_scheme_on_call 
Example #17
Source File: users.py    From Flashcards with MIT License 5 votes vote down vote up
def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)