def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        app.config['SEASURF_INCLUDE_OR_EXEMPT_VIEWS'] = 'include'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.include
        @app.route('/foo', methods=['POST'])
        @app.route('/foo/<term>', methods=['POST'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        @app.route('/bar/<term>', methods=['POST'])
        def bar(term=None):
            return 'foo'
예제 #2
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)
        self.csrf.exempt_urls(('/foo',))

        @app.route('/foo/baz', methods=['POST'])
        def foobaz():
            return 'bar'

        @app.route('/foo/quz', methods=['POST'])
        def fooquz():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)
        self.csrf.exempt_urls(('/foo', ))

        @app.route('/foo/baz', methods=['POST'])
        def foobaz():
            return 'bar'

        @app.route('/foo/quz', methods=['POST'])
        def fooquz():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @self.csrf.disable_cookie
        def disable_cookie(response):
            if request.path == '/foo/baz':
                return True
            if request.path == '/manual':
                return True
            return False

        @app.route('/foo/baz', methods=['GET'])
        def foobaz():
            return 'bar'

        @app.route('/foo/quz', methods=['GET'])
        def fooquz():
            return 'bar'

        @csrf.exempt
        @app.route('/manual', methods=['POST'])
        def manual():
            csrf.validate()
            return 'bar'
예제 #5
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        app.config['SEASURF_INCLUDE_OR_EXEMPT_VIEWS'] = 'include'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.include
        @app.route('/foo', methods=['POST'])
        @app.route('/foo/<term>', methods=['POST'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        @app.route('/bar/<term>', methods=['POST'])
        def bar(term=None):
            return 'foo'
예제 #6
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @self.csrf.disable_cookie
        def disable_cookie(response):
            if request.path == '/foo/baz':
                return True
            if request.path == '/manual':
                return True
            return False

        @app.route('/foo/baz', methods=['GET'])
        def foobaz():
            return 'bar'

        @app.route('/foo/quz', methods=['GET'])
        def fooquz():
            return 'bar'

        @csrf.exempt
        @app.route('/manual', methods=['POST'])
        def manual():
            csrf.validate()
            return 'bar'
예제 #7
0
def setup_app():
    app = Flask(__name__)

    # HTTP security headers
    # Talisman(app, content_security_policy=content_security_policy)

    # CSRF library
    SeaSurf(app)

    # Limiter
    limiter.init_app(app)

    # SQLAlchemy
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cowserver.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)

    # Blueprints
    app.register_blueprint(redditflair)
    app.register_blueprint(user_verification)
    app.register_blueprint(flair_sheets)

    # Redis Session Interface
    app.session_interface = RedisSessionInterface()

    return app
예제 #8
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        self.app = app

        csrf = SeaSurf(app)
        csrf._csrf_disable = False
        self.csrf = csrf

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
예제 #9
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        self.app = app

        csrf = SeaSurf(app)
        csrf._csrf_disable = False
        self.csrf = csrf

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
예제 #10
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.config['SEASURF_INCLUDE_OR_EXEMPT_VIEWS'] = 'exempt'

        self.app = app

        csrf = SeaSurf(app)
        csrf._csrf_disable = False
        self.csrf = csrf

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
예제 #11
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.config['SEASURF_INCLUDE_OR_EXEMPT_VIEWS'] = 'exempt'

        self.app = app

        csrf = SeaSurf(app)
        csrf._csrf_disable = False
        self.csrf = csrf

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'
예제 #12
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.exempt
        @app.route('/manual', methods=['POST'])
        def manual():
            csrf.validate()
            return 'bar'
예제 #13
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.exempt
        @app.route('/manual', methods=['POST'])
        def manual():
            csrf.validate()
            return 'bar'
예제 #14
0
 def create_access_codes(self):
     token = SeaSurf()._generate_token()
     new_access_codes = {
         'access_granted':
         token,
         'expiration': (datetime.datetime.now() + datetime.timedelta(
             seconds=self.config['permissions_cache_expiry']))
     }
     self._access_codes = new_access_codes
     return self._access_codes
예제 #15
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar(term=None):
            self.csrf.generate_new_token()
            return 'foo'
예제 #16
0
def create_app():
    app = Flask(__name__)
    app.url_map.strict_slashes = False
    app.config.from_pyfile("config.cfg")
    app.wsgi_app = SassMiddleware(
        app.wsgi_app,
        {f"{__name__}": ("static/sass", "static/css", "/static/css")})

    from routes.auth import auth
    app.register_blueprint(auth)

    from routes.main import main
    app.register_blueprint(main)

    @app.errorhandler(403)
    def does_not_exist(err):
        return render_template(
            "errors/client.html",
            code="403",
            title="403 Forbidden",
            message="You do not have access to this page."), 403

    @app.errorhandler(404)
    def does_not_exist(err):
        return render_template("errors/client.html",
                               code="404",
                               title="404 Not Found",
                               message="Page not found."), 404

    @app.errorhandler(500)
    def does_not_exist(err):
        return render_template("errors/error.html",
                               title="500 Server Error"), 500

    login_manager = LoginManager()
    login_manager.session_protection = "strong"
    login_manager.login_view = "auth.login"
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(username: str):
        return User(username, True)

    limiter = Limiter(app,
                      key_func=get_remote_address,
                      default_limits=["1 per second"])

    @limiter.request_filter
    def ip_whitelist():
        return request.remote_addr == "127.0.0.1"

    SeaSurf(app)
    return app
예제 #17
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar(term=None):
            self.csrf.generate_new_token()
            return 'foo'
예제 #18
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        @app.after_request
        def after_request(response):
            from flask import session
            response.headers['X-Session-Modified'] = str(session.modified)
            return response

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo():
            return 'bar'
예제 #19
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        @app.after_request
        def after_request(response):
            from flask import session
            response.headers['X-Session-Modified'] = str(session.modified)
            return response

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo():
            return 'bar'
예제 #20
0
def create_app(test_config=None):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__)
    aconf = CRACK_CONF['app']
    #CORS(app, resources={r'/*': {'origins': 'http://localhost:8081',
    #                            'supports_credentials': True},
    #                   })
    app.config['SESSION_TYPE'] = aconf['SESSION_TYPE']
    app.config['SQLALCHEMY_DATABASE_URI'] = aconf['SQLALCHEMY_DATABASE_URI']
    app.config['SESSION_COOKIE_HTTPONLY'] = aconf['SESSION_COOKIE_HTTPONLY']
    app.config['SESSION_COOKIE_SECURE'] = aconf['SESSION_COOKIE_SECURE']
    app.config['PERMANENT_SESSION_LIFETIME'] = int(
        aconf['PERMANENT_SESSION_LIFETIME'])
    app.config['SESSION_PERMANENT'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    #Talisman(app, strict_transport_security=False)
    csrf = SeaSurf()
    app.config['CSRF_COOKIE_NAME'] = 'csrftoken'
    csrf.init_app(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    api = Api(app)
    api.add_resource(cq_api.Login, '/api/login')
    api.add_resource(cq_api.Sso, '/api/sso')
    api.add_resource(cq_api.Logout, '/api/logout')
    api.add_resource(cq_api.Options, '/api/options')
    api.add_resource(cq_api.Queuing, '/api/queuing/<job_id>')
    api.add_resource(cq_api.Adder, '/api/add')
    api.add_resource(cq_api.Reports, '/api/reports')

    #login_manager = LoginManager()
    #login_manager.session_protection = "strong"
    login_manager.init_app(app)
    session = Session(app)
    session.init_app(app)
    session.app.session_interface.db.create_all()
    return app
예제 #21
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'

        @app.route('/baz', methods=['GET'])
        def baz():
            return render_template_string('{{ csrf_token() }}')
예제 #22
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        self.csrf.init_app(app)

        @app.route('/foo', methods=['GET'])
        def foo():
            return 'bar'

        @app.route('/bar', methods=['POST'])
        def bar():
            return 'foo'

        @app.route('/baz', methods=['GET'])
        def baz():
            return render_template_string('{{ csrf_token() }}')
예제 #23
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        app.config['CSRF_CHECK_REFERER'] = False
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        @app.route('/foo/<term>', methods=['POST'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        @app.route('/bar/<term>', methods=['POST'])
        def bar(term=None):
            return 'foo'
예제 #24
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = '1234'
        app.config['CSRF_CHECK_REFERER'] = False
        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.exempt
        @app.route('/foo', methods=['POST'])
        @app.route('/foo/<term>', methods=['POST'])
        def foo(term=None):
            return 'bar'

        @app.route('/bar', methods=['POST'])
        @app.route('/bar/<term>', methods=['POST'])
        def bar(term=None):
            return 'foo'
예제 #25
0
 def __init__(self, *args, **kwargs):
     Flask.__init__(self, *args, **kwargs)
     self.unauthenticated_routes = {'static': True}
     self.csrf = SeaSurf(self)
     if not config.ok:
         log.error("Configuration is not correctly set. Please correct it")
         self.secret_key = "NOT THE REAL SECRET KEY"
         return
     self.config.update(
         SECRET_KEY=config.application.session_key,
         SESSION_COOKIE_SECURE=config.application.session_cookie_secure,
         SESSION_COOKIE_HTTPONLY=config.application.session_cookie_httponly
     )
     # PREFERRED_URL_SCHEME only valid in flask 0.9+
     if Version(flask.__version__) >= Version('0.9'):
         self.config.update(
             PREFERRED_URL_SCHEME=config.application.preferred_url_scheme
         )
     self.secret_key = config.application.session_key # Do we need this?
     # MAH has it's own logging mechanism, and this should be used for flask
     # extensions (such as seasurf)
     for handler in log.handlers:
         self.logger.addHandler(handler) # pylint: disable=E1101
예제 #26
0
db = SQLAlchemy(app, metadata=metadata)

# init login manager
login_manager = LoginManager()
login_manager.init_app(app)

# init flask principal
principals = Principal(app)

# init sqlmigration manager
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)

# init SeaSurf
seasurf = SeaSurf(app)

# init flask CDN
CDN(app)

# init flask HTMLMIN
HTMLMIN(app)

# init assets environment
assets = Environment(app)
register_filter(BabiliFilter)


class MiniJSONEncoder(JSONEncoder):
    """Minify JSON output."""
    item_separator = ','
예제 #27
0
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_seasurf import SeaSurf
from flask_login import LoginManager

db = SQLAlchemy()
mail = Mail()
csrf = SeaSurf()
login_manager = LoginManager()

예제 #28
0
def create_app(test_config=None):
    # Create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        DEBUG=False,
        SECRET_KEY=os.environ.get(
            "SECRET_KEY", 'ppBcUQ5AL7gEmvb0blMDyEOpiBEQUupGmk_a3DMaF34'),
        TOPIC_STORE_USER=database_username,
        TOPIC_STORE_PASSWORD=database_password,
        TOPIC_STORE_DBNAME=database_name,
        TOPIC_STORE_HOST=database_host,
        TOPIC_STORE_PORT=database_port,
        SECURITY_PASSWORD_SALT=os.environ.get(
            "SECURITY_PASSWORD_SALT",
            '139687009245803364536588051620840970665'),
        SECURITY_REGISTERABLE=True,
        SECURITY_RECOVERABLE=True,
        SECURITY_CHANGEABLE=True,
        SECURITY_EMAIL_SENDER=email_sender,
        SECURITY_URL_PREFIX="/auth",
        SECURITY_POST_LOGIN_VIEW="/maps/",
        SECURITY_POST_REGISTER_VIEW="/maps/",
        MAIL_SERVER=email_server,
        MAIL_PORT=587,
        MAIL_USE_SSL=False,
        MAIL_USERNAME=email_username,
        MAIL_PASSWORD=email_password,
        MAX_CONTENT_LENGTH=4 * 1024 *
        1024,  # 4 megabytes (temporarily - will be 2)
    )
    mail = Mail(app)
    csrf = SeaSurf(app)

    if test_config is None:
        # Load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # Load the test config if passed in
        app.config.from_mapping(test_config)

    # Ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route("/")
    def home():
        return render_template("index.html")

    @app.route("/health")
    def hello():
        return "Healthy!"

    # HTTP error handlers
    def forbidden(e):
        return render_template("403.html"), 403

    app.register_error_handler(403, forbidden)

    def page_not_found(e):
        return render_template("404.html"), 404

    app.register_error_handler(404, page_not_found)

    def internal_server_error(e):
        return render_template("500.html"), 500

    app.register_error_handler(500, internal_server_error)

    def request_entity_too_large(e):
        return render_template("413.html"), 413

    app.register_error_handler(413, request_entity_too_large)

    # Setup Flask-Security
    user_datastore = SQLAlchemySessionUserDatastore(user_store.db_session,
                                                    user_models.User,
                                                    user_models.Role)
    security = Security(app, user_datastore)

    @user_registered.connect_via(app)
    def user_registered_handler(app, user, confirm_token):
        default_role = user_datastore.find_role("user")
        user_datastore.add_role_to_user(user, default_role)
        user_store.db_session.commit()

    @app.before_first_request
    def create_user():
        user_store.init_db()

        # Create roles
        user_datastore.find_or_create_role(name="admin",
                                           description="Administrator")
        user_datastore.find_or_create_role(name="user", description="End user")

        # Create users
        if not user_datastore.get_user("*****@*****.**"):
            user_datastore.create_user(email="*****@*****.**",
                                       password=hash_password("Passw0rd1"))
        if not user_datastore.get_user("*****@*****.**"):
            user_datastore.create_user(email="*****@*****.**",
                                       password=hash_password("Passw0rd1"))
        user_store.db_session.commit()

        # Assign roles
        user_datastore.add_role_to_user("*****@*****.**", "user")
        user_datastore.add_role_to_user("*****@*****.**", "admin")
        user_store.db_session.commit()

    @app.teardown_request
    def checkin_db(exc):
        user_store.db_session.remove()

    # Register custom filters
    filters.register_filters(app)

    # Register Blueprints
    from contextualise import api

    app.register_blueprint(api.bp)

    from contextualise import map

    app.register_blueprint(map.bp)

    from contextualise import topic

    app.register_blueprint(topic.bp)

    from contextualise import image

    app.register_blueprint(image.bp)

    from contextualise import file

    app.register_blueprint(file.bp)

    from contextualise import link

    app.register_blueprint(link.bp)

    from contextualise import video

    app.register_blueprint(video.bp)

    from contextualise import association

    app.register_blueprint(association.bp)

    from contextualise import note

    app.register_blueprint(note.bp)

    from contextualise import three_d

    app.register_blueprint(three_d.bp)

    from contextualise import attribute

    app.register_blueprint(attribute.bp)

    # Add topic store
    from contextualise import topic_store

    topic_store.init_app(app)

    return app
예제 #29
0
    filename=os.path.join(os.path.dirname(__file__), 'locator-tool.log'),
    format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    level=logging.DEBUG,
)

app = Flask(__name__, static_url_path='', static_folder='static/')
app.config.from_pyfile('config.py')

# HTTP security headers
Talisman(app, content_security_policy={})

# CSRF protection. settings fitting Angular $httpProvider
app.config['CSRF_COOKIE_NAME'] = 'XSRF-TOKEN'
app.config['CSRF_HEADER_NAME'] = 'X-XSRF-TOKEN'
app.config['CSRF_COOKIE_PATH'] = '/locator-tool/'
SeaSurf(app)

mwoauth = MWOAuth(base_url='https://commons.wikimedia.org/w',
                  clean_url='https://commons.wikimedia.org/wiki',
                  consumer_key=app.config['OAUTH_CONSUMER_KEY'],
                  consumer_secret=app.config['OAUTH_CONSUMER_SECRET'])
app.register_blueprint(mwoauth.bp)


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/user')
def user():
예제 #30
0
from flask_zslib import ZhongshanSecurities
from flask_zwlib import Zhiwang
from flask_xmlib import XinMi
from flask_sxblib import Sxb
from raven.contrib.flask import Sentry
from yxpay.ext.flask import YixinPay
from zslib.signals import debug_message_sent

from .compat.weixin_oauth import fixup_weixin_oauth

sentry = Sentry()
mako = MakoTemplates()
oauth = OAuth()
oauth_provider = OAuth2Provider()
limiter = Limiter()
seasurf = SeaSurf()
yixin = Yixin()
yxpay = YixinPay()
zslib = ZhongshanSecurities()
zhiwang = Zhiwang()
xinmi = XinMi()
sxb = Sxb()
weixin_api = WeixinAPI()

weixin = oauth.remote_app(
    'weixin',
    app_key='WEIXIN',
    request_token_params={'scope': 'snsapi_base'},
    base_url='https://api.weixin.qq.com',
    authorize_url='https://open.weixin.qq.com/connect/oauth2/authorize',
    access_token_url='https://api.weixin.qq.com/sns/oauth2/access_token',
예제 #31
0
    def __init__(
        self,
        name=None,
        server=None,
        filename=None,
        sharing=None,
        app_url=None,
        url_base_pathname='/',
        csrf_protect=True
    ):
        # allow users to supply their own flask server
        if server is not None:
            self.server = server
        else:
            if name is None:
                name = 'dash'
            self.server = Flask(name)

        if self.server.secret_key is None:
            # If user supplied their own server, they might've supplied a
            # secret_key with it
            secret_key_name = 'dash_{}_secret_key'.format(
                # replace any invalid characters
                re.sub('[\W_]+', '_', name)
            )
            secret_key = os.environ.get(
                secret_key_name, SeaSurf()._generate_token()
            )
            os.environ[secret_key_name] = secret_key
            self.server.secret_key = secret_key

        if filename is not None:
            fid = plotly_api.create_or_overwrite_dash_app(
                filename, sharing, app_url
            )
            self.fid = fid
            self.app_url = app_url
            self.sharing = sharing
            self.access_codes = self.create_access_codes()
        else:
            self.fid = None
            self.access_codes = None

        self.url_base_pathname = url_base_pathname

        # list of dependencies
        self.callback_map = {}

        # gzip
        Compress(self.server)

        # csrf protect
        if csrf_protect:
            self._csrf = SeaSurf(self.server)

        # static files from the packages
        self.css = Css()
        self.scripts = Scripts()
        self.registered_paths = {}

        # urls
        self.server.add_url_rule(
            '{}_dash-login'.format(self.url_base_pathname),
            view_func=authentication.login,
            methods=['post']
        )

        self.server.add_url_rule(
            '{}_dash-layout'.format(self.url_base_pathname),
            view_func=self.serve_layout,
            endpoint='{}_dash-layout'.format(self.url_base_pathname)
        )

        self.server.add_url_rule(
            '{}_dash-dependencies'.format(self.url_base_pathname),
            view_func=self.dependencies,
            endpoint='{}_dash-dependencies'.format(self.url_base_pathname)
        )

        self.server.add_url_rule(
            '{}_dash-update-component'.format(self.url_base_pathname),
            view_func=self.dispatch,
            endpoint='{}_dash-update-component'.format(self.url_base_pathname),
            methods=['POST'])

        self.server.add_url_rule((
            '{}_dash-component-suites'
            '/<string:package_name>'
            '/<path:path_in_package_dist>').format(self.url_base_pathname),
            view_func=self.serve_component_suites,
            endpoint='{}_dash-component-suites'.format(self.url_base_pathname)
        )

        self.server.add_url_rule(
            '{}_dash-routes'.format(self.url_base_pathname),
            view_func=self.serve_routes,
            endpoint='{}_dash-routes'.format(self.url_base_pathname)
        )

        self.server.add_url_rule(
            self.url_base_pathname, 
            view_func=self.index,
            endpoint=self.url_base_pathname
        )

        # catch-all for front-end routes
        self.server.add_url_rule(
            '{}<path:path>'.format(self.url_base_pathname),
            view_func=self.index,
            endpoint='{}<path:path>'.format(self.url_base_pathname)
        )

        self.server.before_first_request(self._setup_server)

        self._layout = None
        self.routes = []
예제 #32
0
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
#app.config['USE_X_SENDFILE'] = True
app.config['SERVER_NAME'] = "cwby.biz"

# session management with Redis
app.session_interface = sesh.RedisSessionInterface()

# CSRF prevention with SeaSurf
app.config['CSRF_COOKIE_NAME'] = "_csrf_token"
app.config['CSRF_COOKIE_TIMEOUT'] = 2678400  # 31 days in seconds
app.config['CSRF_COOKIE_SECURE'] = FORCE_HTTPS
# app.config['CSRF_COOKIE_PATH']
app.config['CSRF_COOKIE_DOMAIN'] = "cwby.biz"
app.config['CSRF_COOKIE_SAMESITE'] = "Lax"
#app.config['CSRF_DISABLE'] = True
csrf = SeaSurf(app)
csrf.init_app(app)

# Configure mail
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config.from_object('settings.cfg')
# instantiate mail with app config
mail = Mail(app)
mail.init_app(app)

# Enforce CSP
Talisman(app,
         force_https=FORCE_HTTPS,
         content_security_policy=CSP,
예제 #33
0
import os
from flask import Flask, render_template, session
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine, MongoEngineSessionInterface
from flask_seasurf import SeaSurf
from flask_reggie import Reggie

# Set up the application
app = Flask('victims.web')

# say hello to reggie
reggie = Reggie(app)

# CSRF protection
csrf = SeaSurf(app)

# Twitter Bootstrap
bootstrap = Bootstrap(app)

# configuration
from victims.web import config
app.config.from_object(config)

# logging
logging.basicConfig(
    filename=os.path.join(app.config.get('LOG_FOLDER'), 'server.log'),
    format='%(asctime)s - %(levelname)s: %(message)s',
    datefmt='%a %b %d %Y %H:%M:%S %Z',
    level=app.config['LOG_LEVEL'],
)
예제 #34
0
import logging, os
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_seasurf import SeaSurf
from flask_cors import CORS
from config import Config, Development

db = SQLAlchemy()
login_manager = LoginManager()
migrate = Migrate()
seasurf = SeaSurf()
cors = CORS()

login_manager.needs_refresh_message = (
    u"To protect your account, please reauthenticate (sign-out then sign-in) to access this page."
)


def create_app(config_class=Development):
    """Construct the core application."""
    app = Flask(__name__,
                static_folder='../client/build/static',
                instance_relative_config=False)
    # Application Configuration
    app.config.from_object(config_class)
    with app.app_context():
        # Initialize Plugins
        login_manager.init_app(app)
예제 #35
0
def create_app(config=None):
    from . import models, routes, services
    from .assets import assets
    app = Flask(__name__)

    # Read log level from environment variable
    log_level_name = os.environ.get('PDNS_ADMIN_LOG_LEVEL', 'WARNING')
    log_level = logging.getLevelName(log_level_name.upper())
    # Setting logger
    logging.basicConfig(
        level=log_level,
        format=
        "[%(asctime)s] [%(filename)s:%(lineno)d] %(levelname)s - %(message)s")

    # If we use Docker + Gunicorn, adjust the
    # log handler
    if "GUNICORN_LOGLEVEL" in os.environ:
        gunicorn_logger = logging.getLogger("gunicorn.error")
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)

    # Proxy
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protection
    csrf = SeaSurf(app)
    csrf.exempt(routes.index.dyndns_checkip)
    csrf.exempt(routes.index.dyndns_update)
    csrf.exempt(routes.index.saml_authorized)
    csrf.exempt(routes.api.api_login_create_zone)
    csrf.exempt(routes.api.api_login_delete_zone)
    csrf.exempt(routes.api.api_generate_apikey)
    csrf.exempt(routes.api.api_delete_apikey)
    csrf.exempt(routes.api.api_update_apikey)
    csrf.exempt(routes.api.api_zone_subpath_forward)
    csrf.exempt(routes.api.api_zone_forward)
    csrf.exempt(routes.api.api_create_zone)

    # Load config from env variables if using docker
    if os.path.exists(os.path.join(app.root_path, 'docker_config.py')):
        app.config.from_object('powerdnsadmin.docker_config')
    else:
        # Load default configuration
        app.config.from_object('powerdnsadmin.default_config')

    # Load config file from FLASK_CONF env variable
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')

    # Load app sepecified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    # HSTS
    if app.config.get('HSTS_ENABLED'):
        from flask_sslify import SSLify
        _sslify = SSLify(app)  # lgtm [py/unused-local-variable]

    # SMTP
    app.mail = Mail(app)

    # Load app's components
    assets.init_app(app)
    models.init_app(app)
    routes.init_app(app)
    services.init_app(app)

    # Register filters
    app.jinja_env.filters['display_record_name'] = utils.display_record_name
    app.jinja_env.filters['display_master_name'] = utils.display_master_name
    app.jinja_env.filters['display_second_to_time'] = utils.display_time
    app.jinja_env.filters[
        'email_to_gravatar_url'] = utils.email_to_gravatar_url
    app.jinja_env.filters[
        'display_setting_state'] = utils.display_setting_state

    # Register context proccessors
    from .models.setting import Setting

    @app.context_processor
    def inject_sitename():
        setting = Setting().get('site_name')
        return dict(SITE_NAME=setting)

    @app.context_processor
    def inject_setting():
        setting = Setting()
        return dict(SETTING=setting)

    return app
예제 #36
0
파일: odie.py 프로젝트: fsmi/odie-server
from functools import partial
from datetime import timedelta
import logging

from flask import Flask, session
from flask_babelex import Babel
from flask_sqlalchemy import SQLAlchemy
from flask_seasurf import SeaSurf  # CSRF. Got it?

app = Flask("odie", template_folder='admin/templates', static_folder='admin/static')

import config  # pylint: disable=unused-import
app.config.from_object('config.FlaskConfig')

babel = Babel(app)
csrf = SeaSurf(app)
sqla = SQLAlchemy(app)

@app.before_request
def make_session_permanent():
    # We use flask sessions for remembering which client is in kiosk mode.
    # By default, these sessions expire when the browser is closed. Prevent that.
    session.permanent = True
    app.permanent_session_lifetime = timedelta(days=2*365)  # should be long enough...

if app.debug:
    # allow requests from default broccoli server port
    from flask_cors import CORS
    CORS(app, origins=['http://localhost:4200'], supports_credentials=True)

    import flask_debugtoolbar
예제 #37
0
파일: __init__.py 프로젝트: f0cker/crackq
def create_app():
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__)
    aconf = CRACK_CONF['app']
    #CORS(app, resources={r'/*': {'origins': 'http://localhost:8081',
    #                             'supports_credentials': True},
    #                    })
    app.config['DEBUG'] = False
    app.config['JSON_SORT_KEYS'] = False
    app.config['SESSION_TYPE'] = aconf['SESSION_TYPE']
    app.config['SQLALCHEMY_DATABASE_URI'] = aconf['SQLALCHEMY_DATABASE_URI']
    app.config['SESSION_COOKIE_HTTPONLY'] = aconf['SESSION_COOKIE_HTTPONLY']
    app.config['SESSION_COOKIE_SECURE'] = aconf['SESSION_COOKIE_SECURE']
    app.config['PERMANENT_SESSION_LIFETIME'] = int(
        aconf['PERMANENT_SESSION_LIFETIME'])
    app.config['SESSION_PERMANENT'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    csrf = SeaSurf()
    app.config['CSRF_COOKIE_NAME'] = 'csrftoken'
    csrf.init_app(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    admin_view = cq_api.Admin.as_view('admin')
    profile_view = cq_api.Profile.as_view('profile')
    bench_view = cq_api.Benchmark.as_view('benchmark')
    login_view = cq_api.Login.as_view('login')
    logout_view = cq_api.Logout.as_view('logout')
    sso_view = cq_api.Sso.as_view('sso')
    options_view = cq_api.Options.as_view('options')
    queuing_view = cq_api.Queuing.as_view('queuing')
    add_view = cq_api.Adder.as_view('adder')
    report_view = cq_api.Reports.as_view('reports')
    tasks_view = cq_api.TasksView.as_view('tasks')
    templates_view = cq_api.TemplatesView.as_view('templates')
    app.add_url_rule('/api/admin/',
                     defaults={'user_id': None},
                     view_func=admin_view,
                     methods=['POST', 'GET'])
    app.add_url_rule('/api/admin/<uuid:user_id>',
                     view_func=admin_view,
                     methods=['GET', 'DELETE', 'PUT', 'PATCH'])
    app.add_url_rule('/api/admin/', view_func=admin_view, methods=['POST'])
    app.add_url_rule('/api/profile/',
                     view_func=profile_view,
                     methods=['GET', 'POST'])
    app.add_url_rule('/api/benchmark/',
                     view_func=bench_view,
                     methods=['GET', 'POST'])
    app.add_url_rule('/api/login',
                     view_func=login_view,
                     methods=['GET', 'POST'])
    app.add_url_rule('/api/sso', view_func=sso_view, methods=['GET', 'POST'])
    app.add_url_rule('/api/logout', view_func=logout_view, methods=['GET'])
    app.add_url_rule('/api/options', view_func=options_view, methods=['GET'])
    app.add_url_rule('/api/queuing/<string:job_id>',
                     view_func=queuing_view,
                     methods=['GET', 'DELETE', 'PUT', 'PATCH'])
    app.add_url_rule('/api/add', view_func=add_view, methods=['POST'])
    app.add_url_rule('/api/reports',
                     view_func=report_view,
                     methods=['GET', 'POST'])
    app.add_url_rule('/api/tasks/templates',
                     defaults={'temp_id': None},
                     view_func=templates_view,
                     methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/tasks/templates/<uuid:temp_id>',
                     view_func=templates_view,
                     methods=['DELETE'])
    app.add_url_rule('/api/tasks',
                     view_func=tasks_view,
                     methods=['GET', 'POST'])
    app.add_url_rule('/api/tasks/<uuid:task_id>',
                     view_func=tasks_view,
                     methods=['DELETE'])
    login_manager.init_app(app)
    session = Session(app)
    session.init_app(app)
    migrate = Migrate()
    migrate.init_app(app, db, compare_type=True, render_as_batch=True)
    session.app.session_interface.db.create_all()
    return app
예제 #38
0
def create_app(config=None):
    sentry_sdk.init(send_default_pii=False, integrations=[FlaskIntegration()])

    app = Flask(__name__)
    config = config or 'sfa_dash.config.DevConfig'
    app.config.from_object(config)
    app.secret_key = app.config['SECRET_KEY']
    SeaSurf(app)
    register_jinja_filters(app)
    error_handlers.register_handlers(app)

    if app.config['SQLALCHEMY_DATABASE_URI']:
        db.init_app(app)
        db.create_all(app=app)

    make_auth0_blueprint(app,
                         base_url=app.config['AUTH0_OAUTH_BASE_URL'],
                         storage=session_storage)

    def protect_endpoint():
        try:
            authorized = oauth_request_session.authorized
        except ValueError:
            # no token set for user/no user set
            authorized = False

        # authorized == True means we have a token, not necessarily that it
        # hasn't expired, but refreshing is handled
        # by request_oauthlib and oauthlib
        # and the api validates expiration
        if not authorized:
            session['redirect_path'] = request.path
            return redirect(url_for('auth0.login'))

    @app.route('/')
    def index():
        # move index to app so all blueprints are secured
        # should probably test if authorized and show one
        # page, show a different page w/ login link otherwise
        return render_template('index.html')

    @app.route('/documentation/')
    def documentation():
        return render_template('documentation.html')

    @app.route('/changelog/')
    def changelog():
        return render_template('changelog.html')

    @app.context_processor
    def inject_globals():
        # Injects variables into all rendered templates
        global_template_args = {}
        global_template_args['user'] = session.get('userinfo')
        global_template_args.update(template_variables())
        return global_template_args

    @app.errorhandler(500)
    def server_error_handler(error):
        return render_template("500.html",
                               sentry_event_id=sentry_sdk.last_event_id(),
                               dsn=os.getenv('SENTRY_DSN', '')), 500

    from sfa_dash.blueprints.main import data_dash_blp
    from sfa_dash.blueprints.form import forms_blp
    from sfa_dash.blueprints.admin import admin_blp

    for blp in (data_dash_blp, forms_blp, admin_blp):
        blp.before_request(protect_endpoint)
        app.register_blueprint(blp)
    return app
예제 #39
0
파일: app.py 프로젝트: rustamtm/iqra-web
#!/usr/bin/env python
from flask import (
    Flask, jsonify, abort, request, render_template, redirect,
    send_from_directory
)
from flask_seasurf import SeaSurf
from config import API_KEY, API_ROUTE
import requests
import json


app = Flask(__name__, static_folder="./static", template_folder="./templates")
app.config.from_object('config')
csrf = SeaSurf(app)


def getAssetSource():
    if app.debug:
        jsSource = "http://127.0.0.1:8080/static/js/bundle.js"
        cssSource = "http://127.0.0.1:8080/static/css/bundle.css"
    else:
        with open("webpack-assets.json", "r") as assetsFile:
            assetsJson = json.load(assetsFile)
        jsSource = assetsJson["main"]["js"]
        cssSource = assetsJson["main"]["css"]
    return jsSource, cssSource


@app.route('/static/<path:path>')
def sendStatic(path):
    return send_from_directory('static', path)
예제 #40
0
        "Define environment variable APP_CONFIG_FILE to point to a configuration file "
        "to customize configuration from the defaults.")

#
# verify MONGODB_URL has been set successfully in our configuration
#
if "MONGODB_URL" not in flask_app.config:
    flask_app.logger.error("Could not find required setting MONGODB_URL.")
else:
    flask_app.logger.info("Using MongoDB at {}".format(
        flask_app.config["MONGODB_URL"]))

if 'FLASK_ENV' in flask_app.config and flask_app.config[
        'FLASK_ENV'] != 'development':
    # enable csrf when not using swagger, client must present csrf token
    csrf = SeaSurf(flask_app)
    selected_csp_policy = {
        'font-src': '\'self\'',
        'img-src': '\'self\'',
        'frame-src': '\'self\'',
        'script-src': '\'self\'',
        'style-src': '\'self\'',
        'default-src': '\'self\'',
    }
else:
    #
    # Swagger isn't SeaSurf aware, so do not enable it in development mode.
    #
    # Talisman will prevent the swaggerui from loading in the browser due to unsafe inlines in the swagger web content,
    # so modify the CSP so swagger can work when in development mode.
    #
예제 #41
0
from multimeter import users, settings, tasks
from multimeter.user_views import user_bp
from multimeter.admin_views import admin_bp

# Настройка Flask
app = Flask(__name__)
app.config[
    'SECRET_KEY'] = 'b3ae4cfc3de6b0f6be6f82c751e0175554f47a5b61ee5f2be7fc1fd0b312bf71'
app.config['DEBUG'] = app.config['TESTING'] = settings.development
app.config['PORT'] = settings.port
if not os.path.isdir(settings.work_dir):
    print("Work folder", settings.work_dir, "not found !!!")
    sys.exit()

# Настройка плагинов
sea_surf = SeaSurf(app)


@app.context_processor
def multimeter_context():
    return {
        'settings': settings,
        'tasks': tasks,
        'users': users,
    }


@app.context_processor
def time_left():
    t = settings.end_time - datetime.now()
    sec = int(t.total_seconds())
예제 #42
0
def create_app(test_config=None):
    # Create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        DEBUG=False,
        SECRET_KEY=os.environ.get("SECRET_KEY", "ppBcUQ5AL7gEmvb0blMDyEOpiBEQUupGmk_a3DMaF34"),
        TOPIC_STORE_USER=database_username,
        TOPIC_STORE_PASSWORD=database_password,
        TOPIC_STORE_DBNAME=database_name,
        TOPIC_STORE_HOST=database_host,
        TOPIC_STORE_PORT=database_port,
        SECURITY_PASSWORD_SALT=os.environ.get("SECURITY_PASSWORD_SALT", "139687009245803364536588051620840970665"),
        SECURITY_REGISTERABLE=True,
        SECURITY_RECOVERABLE=True,
        SECURITY_EMAIL_SENDER=email_sender,
        SECURITY_URL_PREFIX="/auth",
        SECURITY_POST_LOGIN_VIEW="/maps/",
        SECURITY_POST_REGISTER_VIEW="/maps/",
        MAIL_SERVER=email_server,
        MAIL_PORT=587,
        MAIL_USE_SSL=False,
        MAIL_USERNAME=email_username,
        MAIL_PASSWORD=email_password,
        MAX_CONTENT_LENGTH=4 * 1024 * 1024,
        # 4 megabytes (temporarily - will be 2)
    )
    mail = Mail(app)
    csrf = SeaSurf(app)

    if test_config is None:
        # Load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # Load the test config if passed in
        app.config.from_mapping(test_config)

    # Ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route("/")
    def home():
        maps = get_topic_store().get_promoted_topic_maps()

        # Reset breadcrumbs and (current) scope
        session["breadcrumbs"] = []
        session["current_scope"] = UNIVERSAL_SCOPE
        session["scope_filter"] = 1

        return render_template("index.html", maps=maps)

    @app.route("/health")
    def hello():
        return "Healthy!"

    # HTTP error handlers
    def forbidden(e):
        return render_template("403.html"), 403

    app.register_error_handler(403, forbidden)

    def page_not_found(e):
        return render_template("404.html"), 404

    app.register_error_handler(404, page_not_found)

    def internal_server_error(e):
        return render_template("500.html"), 500

    app.register_error_handler(500, internal_server_error)

    def request_entity_too_large(e):
        return render_template("413.html"), 413

    app.register_error_handler(413, request_entity_too_large)

    # Setup Flask-Security
    user_datastore = SQLAlchemySessionUserDatastore(user_store.db_session, user_models.User, user_models.Role)
    security = Security(app, user_datastore)

    @user_registered.connect_via(app)
    def user_registered_handler(app, user, confirm_token, form_data, **extra_args):
        default_role = user_datastore.find_role("user")
        user_datastore.add_role_to_user(user, default_role)
        user_store.db_session.commit()

    @user_authenticated.connect_via(app)
    def user_authenticated_handler(app, user, authn_via, **extra_args):
        app.logger.info(f"User logged in successfully: [{user.email}], authentication method: [{authn_via}]")

    @app.before_first_request
    def create_user():
        user_store.init_db()

        # Create roles
        user_datastore.find_or_create_role(name="admin", description="Administrator")
        user_datastore.find_or_create_role(name="user", description="End user")

        # Create users
        if not user_datastore.get_user("*****@*****.**"):
            user_datastore.create_user(email="*****@*****.**", password=hash_password("Passw0rd1"))
        if not user_datastore.get_user("*****@*****.**"):
            user_datastore.create_user(email="*****@*****.**", password=hash_password("Passw0rd1"))
        user_store.db_session.commit()

        # Assign roles
        user_datastore.add_role_to_user("*****@*****.**", "user")
        user_datastore.add_role_to_user("*****@*****.**", "admin")
        user_store.db_session.commit()

    @app.teardown_request
    def checkin_db(exc):
        user_store.db_session.remove()

    # Register custom filters
    filters.register_filters(app)

    # Register Blueprints
    from contextualise import api

    app.register_blueprint(api.bp)
    csrf.exempt(api.create_topic)
    csrf.exempt(api.create_association)

    from contextualise import map

    app.register_blueprint(map.bp)

    from contextualise import topic

    app.register_blueprint(topic.bp)

    from contextualise import image

    app.register_blueprint(image.bp)

    from contextualise import file

    app.register_blueprint(file.bp)

    from contextualise import link

    app.register_blueprint(link.bp)

    from contextualise import video

    app.register_blueprint(video.bp)

    from contextualise import association

    app.register_blueprint(association.bp)

    from contextualise import note

    app.register_blueprint(note.bp)

    from contextualise import three_d

    app.register_blueprint(three_d.bp)

    from contextualise import attribute

    app.register_blueprint(attribute.bp)

    from contextualise import visualisation

    app.register_blueprint(visualisation.bp)

    from contextualise import tag

    app.register_blueprint(tag.bp)

    # Add topic store
    # from contextualise import topic_store

    # topic_store.init_app(app)

    # Set up logging
    if not app.debug:
        if not os.path.exists("logs"):
            os.mkdir("logs")
        file_handler = RotatingFileHandler("logs/contextualise.log", maxBytes=10240, backupCount=10)
        file_handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]")
        )
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info("Contextualise startup")

    return app