예제 #1
0
파일: app.py 프로젝트: kelockhart/adsws
def create_app(**kwargs_config):
    """
    Create the flask app
    :param kwargs_config: overwrite any base level config
    :return: flask.Flask instance
    """

    app = factory.create_app(app_name=__name__.replace('.app', ''),
                             **kwargs_config)

    api = Api(app)
    api.unauthorized = lambda noop: noop  #Overwrite WWW-Authenticate challenge on 401

    csrf = CsrfProtect(app)

    mail = Mail(app)

    cors = CORS(
        app,
        origins=app.config.get('CORS_DOMAINS'),
        allow_headers=app.config.get('CORS_HEADERS'),
        methods=app.config.get('CORS_METHODS'),
        supports_credentials=True,
    )

    app.json_encoder = JSONEncoder
    api.add_resource(Bootstrap, '/bootstrap')
    api.add_resource(StatusView, '/status')
    api.add_resource(OAuthProtectedView, '/protected')
    api.add_resource(CSRFView, '/csrf')
    api.add_resource(UserAuthView, '/user')
    api.add_resource(DeleteAccountView, '/user/delete')
    api.add_resource(UserRegistrationView, '/register')
    api.add_resource(LogoutView, '/logout')
    api.add_resource(PersonalTokenView, '/token')
    api.add_resource(ChangePasswordView, '/change-password')
    api.add_resource(ChangeEmailView, '/change-email')
    api.add_resource(VerifyEmailView, '/verify/<string:token>')
    api.add_resource(ForgotPasswordView, '/reset-password/<string:token>')
    app.ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])

    @app.login_manager.unauthorized_handler
    def unauthorized():
        """
        flask_login callback when @login_required is not met.
        This overrides the default behavior or re-directing to a login view
        """
        abort(401)

    # Register custom error handlers
    if not app.config.get('DEBUG'):
        app.errorhandler(AdsWSError)(on_adsws_error)
        app.errorhandler(AdsWSFormError)(on_adsws_form_error)

        @csrf.error_handler
        def csrf_error(reason):
            app.logger.warning("CSRF Blocked: {reason}".format(reason=reason))
            return jsonify(dict(error="Invalid CSRF token")), 400

    return app
예제 #2
0
def create_app():
    ''' Se encarga de crear la applicaciones de flask.

    Para esto, va a usar la configuracion correspondiente
    al hostname que el mismo esta usando.
    '''
    app = Flask(__name__,
                template_folder='../templates/',
                static_folder='../static')
    app.config.from_envvar('ENTRENAMIENTO_CONFIGURATION')
    db = SQLAlchemy(app)
    bcrypt = Bcrypt(app)
    csrf = CsrfProtect()
    csrf.init_app(app)
    logging_configuration(app)
    return (app, db, bcrypt)
예제 #3
0
def create_app():
    ''' Se encarga de crear la applicaciones de flask.

    Para esto, va a usar la configuracion correspondiente
    al hostname que el mismo esta usando.
    '''
    app = Flask(__name__,
                template_folder='../templates/',
                static_folder='../static')
    app.config.from_envvar('ENTRENAMIENTO_CONFIGURATION')
    db = SQLAlchemy(app)
    bcrypt = Bcrypt(app)
    csrf = CsrfProtect()
    csrf.init_app(app)
    logging_configuration(app)
    return (app, db, bcrypt)
예제 #4
0
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.wtf.csrf import CsrfProtect
from flaskext.uploads import UploadSet

from sponsortracker import data

app = Flask(__name__, template_folder='templates', static_folder='static')
app.config.from_object("sponsortracker.settings")

csrf = CsrfProtect(app)
mail = Mail(app)

preview_uploader = UploadSet("previews", data.ASSET_FORMATS_EXT)
예제 #5
0
class AdminHome(AdminIndexView):
    @expose(u'/')
    def index(self):
        return redirect(url_for(u'dashboard.index'))


admin = Admin(name='Apollo', index_view=AdminHome(name=u'Dashboard'))
babel = Babel()
cache = Cache()
db = MongoEngine()
mail = Mail()
menu = Menu()
security = Security()
gravatar = Gravatar(size=25, default="identicon", use_ssl=True)
sentry = Sentry()
csrf = CsrfProtect()


class Service(object):
    """A :class:`Service` instance encapsulates common MongoEngine document
    operations in the context of a :class:`Flask` application.
    """
    __model__ = None

    def _isinstance(self, model, raise_error=True):
        """Checks if the specified model instance matches the service's model.
        By default this method will raise a `ValueError` if the model is not
        the expected type.

        :param model: the model instance to check
        :param raise_error: flag to raise an error on a mismatch
예제 #6
0
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.bootstrap import Bootstrap
from flask.ext.wtf.csrf import CsrfProtect

from config import config
from oj.core.sqlalchemy import SQLAlchemy

import os
app_dir = os.path.abspath(os.path.dirname(__file__))

mail = Mail()
db = SQLAlchemy()
bootstrap = Bootstrap()
csrf = CsrfProtect()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'

app = Flask(__name__)

with app.app_context():
    config_name = os.getenv('OJ_CONFIG') or 'default'
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)
예제 #7
0
import base64
import os

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf.csrf import CsrfProtect

shitpost = Flask(__name__)
shitpost.config.from_object("config")

db = SQLAlchemy(shitpost)
csrf = CsrfProtect(shitpost)

from shitpost import main
예제 #8
0
# Define the database object which is imported
# by modules and controllers
db = SQLAlchemy(app)

# Authentication
# from .auth import AuthProvider
# auth = AuthProvider(app)

from flask_oauthlib.provider import OAuth2Provider
oauth = OAuth2Provider(app)

# CSRF protection for forms
from flask.ext.wtf.csrf import CsrfProtect

csrf = CsrfProtect()
csrf.init_app(app)

# Login Manager
from flask.ext.login import LoginManager
from .auth.models import User

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"


# Tell the login manager how to find the user
@login_manager.user_loader
def load_user(userid):
    return User.query.filter_by(username=userid).first()
예제 #9
0
from __future__ import print_function
from flask import Flask, render_template, session, redirect, url_for, request,\
        current_app, abort
from flask.ext.wtf.csrf import CsrfProtect, generate_csrf, validate_csrf
import pycrest
from collections import deque
import os


app = Flask(__name__)
CsrfProtect(app)


@app.context_processor
def inject_jinja():
    return {
        'eve': current_app.eve,
        'queue': current_app.queue,
    }


@app.before_first_request
def register_crest():
    current_app.eve = pycrest.EVE(
            client_id=os.environ['CLIENT_ID'],
            api_key=os.environ['CLIENT_SECRET'],
            redirect_uri=url_for('login', _external=True))


@app.before_first_request
def initialize_queue():