示例#1
0
mail = Mail(app)
db = SQLAlchemy(app)
scheduler = APScheduler()
scheduler.init_app(app)
login_manager = LoginManager(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'

from watchlist.schedulers import task_daily

scheduler.add_job(func=task_daily,
                  id='cron_task',
                  trigger='cron',
                  hour='1',
                  replace_existing=True)
scheduler.start()

mc = memcache.Client(["127.0.0.1:11211"])

CSRFProtect(app)


@login_manager.user_loader
def load_user(user_email):
    from watchlist.models import User
    user = User.query.get(user_email)
    return user


from watchlist import views, commands
示例#2
0
import subprocess

import os
import json
from subprocess import Popen, PIPE, check_output
from flask import Flask, redirect, url_for, render_template, request, session
from flask_wtf.csrf import CSRFProtect
from flask_talisman import Talisman
from passlib.hash import sha256_crypt

app = Flask(__name__)
app.config['SECRET_KEY'] = 'BdAui8H9npasU'

# used for  csrf token
csrf = CSRFProtect(app)

# talisman use for security
Talisman(app,
         force_https=False,
         strict_transport_security=False,
         session_cookie_secure=False)

#Users file
Users = {}


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

示例#3
0
'''
Main entry point homeportal application
'''
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from config import config
from .extensions import db_kookboek

csrf = CSRFProtect()


def create_app(config_name):
    '''
    application factory
    '''
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config[config_name])

    csrf.init_app(app)
    db_kookboek.init_app(app)

    with app.app_context():

        from .home import home
        from .kookboek.routes import kookboek_bp

        # Database
        db_kookboek.create_all()  # Create all tables

        # Register Blueprints
示例#4
0
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

bcrypt = Bcrypt()
csrf_protect = CSRFProtect()
login = LoginManager()
login.login_view = 'account.login'
login.login_message = 'Please log in to access this page.'
db = SQLAlchemy()
migrate = Migrate()
moment = Moment()
示例#5
0
import json

import psycopg2.extras
from flask import Flask, g, request
from flask_wtf.csrf import CSRFProtect
from flask_login import current_user

app = Flask(__name__, instance_relative_config=True)
csrf = CSRFProtect(app)  # Make sure all forms are CSRF protected
csrf.init_app(app)

app.config.from_object('config.default')  # Load config/INSTANCE_NAME.py
app.config.from_pyfile('production.py')  # Load instance/INSTANCE_NAME.py

thunderforest_API_key = app.config["THUNDERFOREST_API_KEY"]
openatlas_url = app.config["OPENATLAS_URL"]
domaintypes = app.config["DOMAIN_TYPES"]
periodtypes = app.config["PERIOD_TYPES"]
countrytypes = app.config["COUNTRY_TYPES"]
api_url = app.config["API_URL"]
loc_image = app.config["API_FILE_DISPLAY"]
use_api = app.config["USE_API"]
use_jpgs = app.config["USE_JPGS"]
geonames_user = app.config["GEONAMES_USERNAME"]
leafletVersion = ""

if not use_api:
    if use_jpgs:
        loc_image = app.config["JPG_FOLDER_PATH"] + '/'
    else:
        loc_image = app.config["WEB_FOLDER_PATH"] + '/'
示例#6
0
def create_app(config_name):
    """工厂方法"""
    # 1.创建app对象
    app = Flask(__name__)

    # development -- DevelopmentConfig 根据传入的参数不同获取不同的配置信息
    config_class = config_dict[config_name]

    # 设置日志
    set_log(config_class)

    # 将对于的配置类关联到app身上
    # DevelopmentConfig:对应的就是开发模式的app
    # ProductionConfig: 对应的就是线上模式的app
    app.config.from_object(config_class)

    # 2.创建数据库对象
    # 使用延迟,懒加载的模式:真实的db数据库对象的初始化操作
    db.init_app(app)

    # 3.创建redis对象 -- 延迟加载的思想
    # decode_responses=True 获取的数据转换成字符串
    global redis_store
    redis_store = StrictRedis(host=config_class.REDIS_HOST,
                              port=config_class.REDIS_PORT,
                              db=config_class.REDIS_NUM,
                              decode_responses=True
                              )

    # 4.给项目添加csrf防护机制
    # 提取cookie中的csrf_token
    # 如果有表单提取form表单中的csrf_token,如果前端发送的ajax请求从请求头的X-CSRFToken字段中提取csrf_token
    # 进行值的比对
    CSRFProtect(app)

    # 借助钩子函数请求完毕页面显示的时候就在cookie中设置csrf_token
    @app.after_request
    def set_csrf_token(response):
        # 请求结束后来调用
        # 1. 生成csrf_token随机值
        csrf_token = generate_csrf()
        # 2. 借助response响应对象值设置到cookie中
        response.set_cookie("csrf_token", csrf_token)
        # 3. 返回响应对象
        return response

    # 5.将session存储的数据从`内存`转移到`redis`中存储的
    Session(app)

    # 添加最定义过滤器
    app.add_template_filter(set_rank_class, "set_rank_class")

    @app.errorhandler(404)
    @user_login_data
    def handler_404(e):
        """处理404页面"""
        # 获取当前登录用户数据
        user = g.user
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/404.html", data=data)


    # 6.注册index首页的蓝图对象
    # 延迟导入解决循环导入问题
    from info.module.index import index_bp
    app.register_blueprint(index_bp)

    # 登录注册模块蓝图注册
    from info.module.passport import passport_bp
    app.register_blueprint(passport_bp)

    # 新闻详情模块蓝图注册
    from info.module.news import newsdetail_bp
    app.register_blueprint(newsdetail_bp)

    # 用户中心模块蓝图注册
    from info.module.profile import profile_bp
    app.register_blueprint(profile_bp)

    # 后台管理模块蓝图注册
    from info.module.admin import admin_bp
    app.register_blueprint(admin_bp)

    return app
示例#7
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        session['userid'] = form.data.get('userid')

        return redirect('/')

    return render_template('login.html', form=form)

@app.route('/logout', methods=['GET'])
def logout():
    session.pop('userid', None)
    return redirect('/')


# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/testdb2'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:0000@localhost/testdb'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'adqdasdqddasdqw'

csrf = CSRFProtect()    # 사이트위조공격 방지
csrf.init_app(app)

db.init_app(app)
db.app = app
db.create_all()

if __name__ == "__main__":
    #app.run(host='127.0.0.1', port=5000, debug=True)
    app.run(host='0.0.0.0', port=5000)
示例#8
0
文件: app.py 项目: OWLsync/OWLsync
#!/usr/bin/env python3
from flask_wtf.csrf import CSRFProtect
from www import APP
from www.models import DB

from www.views import *

from config import CURRENT_CONFIG

csrf = CSRFProtect(APP)

if __name__ == '__main__':
    # DB.create_all()
    # DB.session.commit()
    APP.run(use_reloader=False, debug=CURRENT_CONFIG.DEBUG)
    csrf.init_app(APP)
示例#9
0
from functools import wraps
from sqlalchemy import create_engine
from flask_wtf.csrf import CSRFProtect
import json

import function_database
import function_call
import function_company
import secret

from models import *
from forms import *

# Default Settings
application = Flask(__name__)
csrf = CSRFProtect(application)
csrf.init_app(application)
db.init_app(application)  # models.py에 있는 클래스 이용하기 위해 필요
application.config['SQLALCHEMY_DATABASE_URI'] = \
    'mysql+pymysql://{user}:{password}@{host}/{db}' \
        .format(user=secret.user, password=secret.password, host=secret.host, db=secret.db)
application.secret_key = "123"
page_list = {'call': None, 'company': None, 'employee': None, 'manage': None}
login_error_message = "ID: admin, PW: bestgood"
application.permanent_session_lifetime = timedelta(hours=24)
Session = sessionmaker()
engine = create_engine('sqlite:///:memory:', echo=True)
Session.configure(bind=engine)


def select_page(page):
示例#10
0
def create_app():
    app = Flask(__name__)

    # sessionを使う際にSECRET_KEYを設定
    app.config['SECRET_KEY'] = b'R\x1c`\x8d\xed_\xe5\xd6\x8d\xef\xc6\x19g- J'

    # ここから /// 画像アップロードの設定
    # 画像のアップロード先のディレクトリ
    app.config["IMAGE_UPLOADS"] = 'flmapp/static/user_image'
    app.config["ORIGINAL_IMAGE_UPLOADS"] = 'flmapp/static/original_user_image'
    app.config["ITEM_IMAGE_UPLOADS"] = 'flmapp/static/item_image'
    app.config["ITEM_TEMP_IMAGE_UPLOADS"] = 'flmapp/static/item_temp_image'
    app.config[
        "ORIGINAL_ITEM_IMAGE_UPLOADS"] = 'flmapp/static/original_item_image'
    # アップロードされる拡張子の制限
    app.config["ALLOWED_IMAGE_EXTENSIONS"] = ["JPEG", "JPG", "PNG", "GIF"]
    # 画像サイズの制限
    app.config["MAX_IMAGE_FILESIZE"] = 0.5 * 1024 * 1024
    # ここまで /// 画像アップロードの設定

    # ここから /// データベースの設定
    # DBはSQLiteを使う
    #! パスを変えてください
    app.config['SQLALCHEMY_DATABASE_URI'] = \
        'sqlite:///' + "/Users/shimomuramei/Desktop/set_prefs/data.sqlite"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_ECHO'] = False
    # ここまで /// データベースの設定

    # ここから /// メール送信の設定
    app.config['DEBUG'] = True  # デバッグのサポート
    app.config['TESTING'] = False
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    app.config['MAIL_USERNAME'] = '******'
    app.config['MAIL_PASSWORD'] = '******'
    app.config['MAIL_DEFAULT_SENDER'] = '*****@*****.**'
    app.config['MAIL_MAX_EMAILS'] = 5  #送信するメールの最大数
    app.config['MAIL_SUPPRESS_SEND'] = False
    app.config['MAIL_ASCII_ATTACHHMENTS'] = False
    # ここまで /// メール送信の設定

    # ここから /// キャプチャの設定
    app.config['CAPTCHA_ENABLE'] = True
    app.config['CAPTCHA_LENGTH'] = 5
    app.config['CAPTCHA_WIDTH'] = 160
    app.config['CAPTCHA_HEIGHT'] = 100
    app.config['SESSION_TYPE'] = 'sqlalchemy'
    # ここまで /// キャプチャの設定

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    mail.init_app(app)
    Session(app)
    captcha = FlaskSessionCaptcha(app)
    CSRFProtect(app)

    # カスタムテンプレートフィルターの登録
    app.add_template_filter(replace_newline)

    # 分割したblueprintを登録する
    from flmapp.views import (auth, mypage, route, sell, item, buy,
                              transaction, ajax, user, history, search,
                              todolist)

    app.register_blueprint(auth.bp)
    app.register_blueprint(mypage.bp)
    app.register_blueprint(route.bp)
    app.register_blueprint(sell.bp)
    app.register_blueprint(item.bp)
    app.register_blueprint(buy.bp)
    app.register_blueprint(transaction.bp)
    app.register_blueprint(ajax.bp)
    app.register_blueprint(user.bp)
    app.register_blueprint(history.bp)
    app.register_blueprint(search.bp)
    app.register_blueprint(todolist.bp)

    return app
示例#11
0
def create_app():
    # Helper function to access secrets
    def get_secret(secret_name):
        try:
            with open('/run/secrets/{0}'.format(secret_name), 'r') as secret_file:
                return secret_file.read()
        except IOError:
            return None
    
    # Application setup
    app = Flask(__name__)
    app.config.update(
        SECRET_KEY = get_secret("secret_key").strip(),
        SESSION_COOKIE_HTTPONLY = True,
        SESSION_COOKIE_SAMESITE = 'Strict',
        PERMANENT_SESSION_LIFETIME = 600,
        SQLALCHEMY_DATABASE_URI = 'sqlite:///spellchecker.db',
        SQLALCHEMY_TRACK_MODIFICATIONS = True
    )
    csrf = CSRFProtect(app)
    
    # Database setup
    db = SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'user'
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(100), nullable=False)
        password = db.Column(db.String(100), nullable=False)
        twofa = db.Column(db.String(100), nullable=True)

    class Query(db.Model):
        __tablename__ = 'query'
        id = db.Column(db.Integer, primary_key=True)
        uid = db.Column(db.Integer, db.ForeignKey('user.id'))
        user = db.relationship(User)
        textout = db.Column(db.Text, nullable=False)
        misspelled = db.Column(db.Text, nullable=True)

    class Log(db.Model):
        __tablename__ = 'log'
        id = db.Column(db.Integer, primary_key=True)
        uid = db.Column(db.Integer, db.ForeignKey('user.id'))
        user = db.relationship(User)
        login = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())
        logout = db.Column(db.DateTime, nullable=True, default=None)

    db.create_all()
    
    # Database functions
    def register_with_user_info(uname, pword, twofa):
        user = db.session.query(User).filter(User.username == uname).first()
        if not user:
            hashed_pword = bcrypt.hashpw(pword.encode('utf8'), bcrypt.gensalt())
            hashed_twofa = bcrypt.hashpw(twofa.encode('utf8'), bcrypt.gensalt())
            new_user = User(username=uname, password=hashed_pword, twofa=hashed_twofa)
            db.session.add(new_user)
            db.session.commit()
            return 0
        else:
            return 1
        
    def login_with_user_info(uname, pword, twofa):
        user = db.session.query(User).filter(User.username == uname).first()
        if not user:
            return 2
        if bcrypt.checkpw(pword.encode('utf8'), user.password) == False:
            return 2
        if bcrypt.checkpw(twofa.encode('utf8'), user.twofa) == False:
            return 1
        new_log = Log(uid=user.id)
        db.session.add(new_log)
        db.session.commit()
        return 0

    def add_spellcheck(uname, textout, misspelled):
        user = db.session.query(User).filter(User.username == uname).first()
        if user:
            new_query = Query(uid=user.id, textout=textout, misspelled=misspelled)
            db.session.add(new_query)
            db.session.commit()

    def create_admin():
        register_with_user_info("admin", get_secret("admin_pword").strip(), get_secret("admin_2fa").strip())
    create_admin()

    # Web application pages
    @app.route("/")
    def home():
        return render_template("home.html")

    @app.route("/register", methods = ['GET', 'POST'])
    def register():
        success = ""
        if 'username' not in session:
            if request.method == 'POST':
                uname = bleach.clean(request.form['uname'])
                pword = bleach.clean(request.form['pword'])
                twofa = bleach.clean(request.form['2fa'])
                status = register_with_user_info(uname, pword, twofa)
                if status == 0:
                    success = "Registration Success!"
                else:
                    success = "Registration Failure!"
            return render_template("register.html", id = success)
        else:
            success = "Already logged in!"
            return render_template("register.html", id = success)

    @app.route("/login", methods = ['GET', 'POST'])
    def login():
        result = ""
        if 'username' not in session:
            if request.method == 'POST':
                uname = bleach.clean(request.form['uname'])
                pword = bleach.clean(request.form['pword'])
                twofa = bleach.clean(request.form['2fa'])
                status = login_with_user_info(uname, pword, twofa)
                if status == 2:
                    result = "Incorrect username or password!"
                elif status == 1:
                    result = "Two-factor failure!"
                else:
                    result = "Success!"
                    session.permanent = True
                    session['username'] = uname
            return render_template("login.html", id = result)
        else:
            result = "Already logged in!"
            return render_template("login.html", id = result)

    @app.route("/spell_check", methods = ['GET', 'POST'])
    def spell_check():
        if 'username' in session:
            textout = ""
            misspelled = ""
            if request.method == 'POST':
                textout = bleach.clean(request.form['inputtext'])
                with open("test.txt", "w+") as fo:
                    fo.write(textout)
                misspelled = subprocess.check_output(["./a.out", "test.txt", "wordlist.txt"])
                misspelled = misspelled.decode('utf-8').strip().split('\n')
                misspelled = ", ".join(misspelled)
                fo.close()
                os.remove("test.txt")
                name = session['username']
                add_spellcheck(name, textout, misspelled)
            return render_template("spell_check.html", textout = textout, misspelled = misspelled)
        else:
            return redirect(url_for("home"))

    @app.route("/logout")
    def logout():
        if 'username' in session:
            name = session['username']
            userlog = db.session.query(Log).join(User, Log.uid == User.id).filter(User.username == name).order_by(Log.id.desc()).first()
            if userlog:
                userlog.logout = datetime.utcnow()
                db.session.commit()
                session.pop('username', None)
        return redirect(url_for("home"))

    @app.route("/history", methods = ['GET', 'POST'])
    def history():
        if 'username' in session:
            name = session['username']
            if name == 'admin':
                uname = name
                if request.method == 'POST':
                    uname = bleach.clean(request.form['uname'])
                history = db.session.query(Query).join(User, Query.uid == User.id).filter(User.username == uname).all()
                return render_template("history.html", history=history, searched=uname, name=name)
            else:
                history = db.session.query(Query).join(User, Query.uid == User.id).filter(User.username == name).all()
                return render_template("history.html", history=history, searched=name)
        else:
            return redirect(url_for("home"))

    @app.route("/history/query<int:query_id>")
    def query(query_id):
        if 'username' in session:
            userquery = db.session.query(Query).join(User, Query.uid == User.id).filter(Query.id == query_id).first()
            if userquery:
                name = session['username']
                if userquery.user.username == name or name == 'admin':
                    return render_template("query.html", userquery=userquery)
            return redirect(url_for("history"))
        else:
            return redirect(url_for("home"))

    @app.route("/login_history", methods = ['GET', 'POST'])
    def login_history():
        if 'username' in session and session['username'] == "admin":
            uname = ""
            if request.method == 'POST':
                uname = bleach.clean(request.form['uname'])
                userlog = db.session.query(Log).join(User, Log.uid == User.id).filter(User.username == uname).all()
                if userlog:
                    return render_template("login_history.html", userlog=userlog, uname=uname)
            return render_template("login_history.html", uname=uname)
        else:
            return redirect(url_for("home"))

    @app.after_request
    def add_headers(response):
        response.headers['Strict-Transport-Security'] = "max-age=31536000 ; includeSubDomains"
        response.headers['Content-Security-Policy'] = "default-src 'self' ; style-src 'self' 'unsafe-inline'"
        response.headers['Set-Cookie'] = "HTTPOnly ; Secure"
        response.headers['X-FrameOptions'] = "DENY"
        response.headers['X-XSS-Protection'] = "1 ; mode=block"
        response.headers['X-Content-Type-Options'] = "nosniff"
        return response

    return app
示例#12
0
from flask import Flask, request
from flask_restful import Resource, Api
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor
from flask_wtf.csrf import CSRFProtect
from flask_cors import CORS

app = Flask(__name__)

cors = CORS(app, resources={r"/*": {"origins": "*"}})

api = Api(app)


csrf_protect = CSRFProtect(app)
api = Api(app, decorators=[csrf_protect.exempt])

mysql = MySQL(cursorclass=DictCursor)

app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'gafur1'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

class Word(Resource):
    def get(self, word_id):
        with mysql.connect() as cursor:
            sql = "SELECT * FROM words WHERE id=" + word_id
            cursor.execute(sql)
            return cursor.fetchall()[0]
示例#13
0
'''Main package configuration'''
import os
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flaskblog.config import Config

#database
db = SQLAlchemy()

#csfr
csfr = CSRFProtect()

#Bcrypt
bcrypt = Bcrypt()

#Login manager
login_manager = LoginManager()
login_manager.login_view = 'user.login'
login_manager.login_message_category = 'info'

#Mail
mail = Mail()


def create_app(config_class=Config):
    '''Create the app with the given configuration.'''
    #app
示例#14
0
def build_app() -> Flask:
    app = Flask(__name__, instance_relative_config=True)

    # Configs
    # Load the default configuration
    app.config.from_object("config.default")
    # Load the configuration from the instance folder
    app.config.from_pyfile('config.py', silent=True)
    # Load config according to run environment
    # Variables defined here will override those in the default configuration
    if app.debug:
        app.config.from_object("config.debug")
    else:
        app.config.from_object("config.production")
    # Save whitespace in templates
    app.jinja_env.lstrip_blocks = True
    app.jinja_env.trim_blocks = True

    celery.init_celery(app)
    db.init_app(app)

    # Bootstrap
    Bootstrap(app)
    init_translations(app)

    # CSRF protection
    csrf = CSRFProtect()
    csrf.init_app(app)

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

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'favicon.ico', mimetype='image/vnd.microsoft.icon')

    # Redirection
    app.add_url_rule("/", endpoint="index")

    # apply the blueprints to the app
    from psan import auth
    app.register_blueprint(auth.bp)
    from psan import account
    app.register_blueprint(account.bp)
    from psan import submission
    app.register_blueprint(submission.bp)
    from psan import annotate
    app.register_blueprint(annotate.bp)
    from psan import rule
    app.register_blueprint(rule.bp)
    from psan import label
    app.register_blueprint(label.bp)
    from psan import generate
    app.register_blueprint(generate.bp)

    # Create register token
    if os.environ.get("ALLOW_TOKEN_REGISTRATION", default="0") == "1":
        if app.config.get("SERVER_NAME"):
            with app.app_context():
                path = url_for('auth.register', token=generate_auth_token(REGISTER_TOKEN_NAME), _external=True)
        else:
            with app.test_request_context("localhost"):  # workaround for missing SERVER_NAME
                path = "http://localhost:5000" + \
                    url_for('auth.register', token=generate_auth_token(REGISTER_TOKEN_NAME))
            app.logger.info(
                f"You can register new user at {path}")

    return app
示例#15
0
def create_app(config):
    app = Flask(__name__,
                template_folder=config.SOURCE_TEMPLATES_DIR,
                static_folder=path.join(config.SECUREDROP_ROOT, 'static'))
    app.request_class = RequestThatSecuresFileUploads
    app.config.from_object(config.SourceInterfaceFlaskConfig)

    # The default CSRF token expiration is 1 hour. Since large uploads can
    # take longer than an hour over Tor, we increase the valid window to 24h.
    app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24

    CSRFProtect(app)

    @app.errorhandler(CSRFError)
    def handle_csrf_error(e):
        msg = render_template('session_timeout.html')
        session.clear()
        flash(Markup(msg), "important")
        return redirect(url_for('main.index'))

    assets = Environment(app)
    app.config['assets'] = assets

    i18n.setup_app(app)

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True
    app.jinja_env.globals['version'] = version.__version__
    if getattr(config, 'CUSTOM_HEADER_IMAGE', None):
        app.jinja_env.globals['header_image'] = config.CUSTOM_HEADER_IMAGE
        app.jinja_env.globals['use_custom_header_image'] = True
    else:
        app.jinja_env.globals['header_image'] = 'logo.png'
        app.jinja_env.globals['use_custom_header_image'] = False

    app.jinja_env.filters['rel_datetime_format'] = \
        template_filters.rel_datetime_format
    app.jinja_env.filters['nl2br'] = evalcontextfilter(template_filters.nl2br)
    app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat

    for module in [main, info, api]:
        app.register_blueprint(module.make_blueprint(config))

    @app.before_request
    @ignore_static
    def check_tor2web():
        # ignore_static here so we only flash a single message warning
        # about Tor2Web, corresponding to the initial page load.
        if 'X-tor2web' in request.headers:
            flash(
                Markup(
                    gettext(
                        '<strong>WARNING:</strong> You appear to be using Tor2Web. '
                        'This <strong>does not</strong> provide anonymity. '
                        '<a href="{url}">Why is this dangerous?</a>').format(
                            url=url_for('info.tor2web_warning'))),
                "banner-warning")

    @app.before_request
    @ignore_static
    def setup_g():
        """Store commonly used values in Flask's special g object"""
        g.locale = i18n.get_locale()
        g.text_direction = i18n.get_text_direction(g.locale)
        g.html_lang = i18n.locale_to_rfc_5646(g.locale)
        g.locales = i18n.get_locale2name()

        if 'expires' in session and datetime.utcnow() >= session['expires']:
            msg = render_template('session_timeout.html')

            # clear the session after we render the message so it's localized
            session.clear()

            flash(Markup(msg), "important")

        session['expires'] = datetime.utcnow() + \
            timedelta(minutes=getattr(config,
                                      'SESSION_EXPIRATION_MINUTES',
                                      120))

        # ignore_static here because `crypto_util.hash_codename` is scrypt
        # (very time consuming), and we don't need to waste time running if
        # we're just serving a static resource that won't need to access
        # these common values.
        if logged_in():
            g.codename = session['codename']
            g.filesystem_id = crypto_util.hash_codename(g.codename)
            try:
                g.source = Source.query \
                            .filter(Source.filesystem_id == g.filesystem_id) \
                            .one()
            except NoResultFound as e:
                app.logger.error("Found no Sources when one was expected: %s" %
                                 (e, ))
                del session['logged_in']
                del session['codename']
                return redirect(url_for('main.index'))
            g.loc = store.path(g.filesystem_id)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        """Automatically remove database sessions at the end of the request, or
        when the application shuts down"""
        db_session.remove()

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('notfound.html'), 404

    @app.errorhandler(500)
    def internal_error(error):
        return render_template('error.html'), 500

    return app