Adds ability to exclude paths from redirects.

This commit is contained in:
tofias
2015-03-25 18:37:12 -05:00
parent 6f4b90ddca
commit 30c27772bb
+25 -13
View File
@@ -1,24 +1,25 @@
# -*- coding: utf-8 -*-
from flask import request, redirect, current_app
from flask import request, redirect
YEAR_IN_SECS = 31536000
class SSLify(object):
"""Secures your Flask App."""
def __init__(self, app=None, age=YEAR_IN_SECS, subdomains=False, permanent=False):
self.hsts_age = age
self.hsts_include_subdomains = subdomains
self.permanent = permanent
def __init__(self, app, age=YEAR_IN_SECS, subdomains=False, permanent=False, skips=None):
if app is not None:
self.init_app(app)
self.app = app
self.hsts_age = age
self.hsts_include_subdomains = subdomains
self.permanent = permanent
self.skip_list = skips or app.config['SSL_SKIPS']
self.init_app(self.app)
else:
self.app = None
def init_app(self, app):
"""Configures the configured Flask app to enforce SSL."""
app.before_request(self.redirect_to_ssl)
app.after_request(self.set_hsts_header)
@@ -32,27 +33,38 @@ class SSLify(object):
return hsts_policy
@property
def skipping(self):
"""Checks the skip list."""
# Should we skip?
if self.skip_list:
for skip in self.skip_list:
if request.path.startswith('/' + skip):
return True
def redirect_to_ssl(self):
"""Redirect incoming requests to HTTPS."""
# Should we redirect?
criteria = [
request.is_secure,
current_app.debug,
self.app.debug,
request.headers.get('X-Forwarded-Proto', 'http') == 'https'
]
if not any(criteria):
# if not any(criteria) and self.skipping != True:
if not any(criteria) and not self.skipping is True:
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://', 1)
code = 302
if self.permanent:
code = 301
r = redirect(url, code=code)
return r
def set_hsts_header(self, response):
"""Adds HSTS header to each response."""
if request.is_secure:
# Should we add STS header?
if not self.skipping is True:
response.headers.setdefault('Strict-Transport-Security', self.hsts_header)
return response