Example #1
0
# _*_ coding:utf-8 _*_
# Author:Jazpenn

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager
from config import config

db = SQLAlchemy()
bootstrap = Bootstrap()
loging_manager = LoginManager()
loging_manager.session_protection = 'strong'
loging_manager.login_view = 'admin.login'
loging_manager.login_message = u'请登入帐号再进行下一步操作!'

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    bootstrap.init_app(app)
    loging_manager.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
Example #2
0
                ])))

    return config


app.config.update(generate_config())
app.config['DEBUG'] = True
app.config['TESTING'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///idp.db'
app.config['WTF_CSRF_ENABLED'] = True

# load our blueprints:
app.register_blueprint(idp_component)

# Setup Flask-Security
lm = LoginManager(app)
lm.login_view = 'idp.login'


@lm.user_loader
def load_user(user_id):
    """User loader callback for Flask-Login."""
    return User.query.get(int(user_id))


db.init_app(app)
admin = setup_admin(app, db)


@app.before_first_request
def initialize_self():
Example #3
0
from flask.ext.login import LoginManager
from flask.ext.login import login_required
from flask.ext.login import login_user
from flask.ext.login import logout_user
from flask.ext.login import current_user
from passwordhelper import PasswordHelper
from mockdbhelper import MockDBHelper as DBHelper
from user import User
import config
from bitlyhelper import BitlyHelper

DB = DBHelper()
PH = PasswordHelper()
BH = BitlyHelper()
app = Flask(__name__)
login_manager = LoginManager(app)
app.secret_key="Q5lkCSMeMfFPvMlk4PXNBgnh8VVII0dFZyN22zTMgtammv2os2fx9wjmGNvFsQ01fzOFRx6LLehf" \
               "62UU0NZK4PxYX1ZTpu17Ymv"


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


@app.route("/login", methods=['POST'])
def login():
    email = request.form.get("email")
    password = request.form.get("password")
    stored_user = DB.get_user(email)
    if stored_user and PH.validate_password(password, stored_user['salt'],
Example #4
0
    def test_class_init(self):
        login_manager = LoginManager(self.app, add_context_processor=True)

        self.assertIsInstance(login_manager, LoginManager)
Example #5
0
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'deterministic'
        self.app.config['SESSION_PROTECTION'] = None
        self.app.config['TESTING'] = True
        self.remember_cookie_name = 'remember'
        self.app.config['REMEMBER_COOKIE_NAME'] = self.remember_cookie_name
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._login_disabled = False

        @self.app.route('/')
        def index():
            return u'Welcome!'

        @self.app.route('/secret')
        def secret():
            return self.login_manager.unauthorized()

        @self.app.route('/login-notch')
        def login_notch():
            return unicode(login_user(notch))

        @self.app.route('/login-notch-remember')
        def login_notch_remember():
            return unicode(login_user(notch, remember=True))

        @self.app.route('/login-notch-permanent')
        def login_notch_permanent():
            session.permanent = True
            return unicode(login_user(notch))

        @self.app.route('/needs-refresh')
        def needs_refresh():
            return self.login_manager.needs_refresh()

        @self.app.route('/confirm-login')
        def _confirm_login():
            confirm_login()
            return u''

        @self.app.route('/username')
        def username():
            if current_user.is_authenticated():
                return current_user.name
            return u'Anonymous'

        @self.app.route('/is-fresh')
        def is_fresh():
            return unicode(login_fresh())

        @self.app.route('/logout')
        def logout():
            return unicode(logout_user())

        @self.login_manager.user_loader
        def load_user(user_id):
            return USERS[int(user_id)]

        @self.login_manager.header_loader
        def load_user_from_header(header_value):
            if header_value.startswith('Basic '):
                header_value = header_value.replace('Basic ', '', 1)
            try:
                user_id = base64.b64decode(header_value)
            except TypeError:
                pass
            return USERS.get(int(user_id))

        @self.login_manager.request_loader
        def load_user_from_request(request):
            user_id = request.args.get('user_id')
            try:
                user_id = int(float(user_id))
            except TypeError:
                pass
            return USERS.get(user_id)

        @self.app.route('/empty_session')
        def empty_session():
            return unicode(u'modified=%s' % session.modified)

        # This will help us with the possibility of typoes in the tests. Now
        # we shouldn't have to check each response to help us set up state
        # (such as login pages) to make sure it worked: we will always
        # get an exception raised (rather than return a 404 response)
        @self.app.errorhandler(404)
        def handle_404(e):
            raise e

        unittest.TestCase.setUp(self)
Example #6
0
def init(config):
    global app
    global babel
    global login_manager
    global db
    global cache

    # Main application object
    app = Flask(__name__)
    if config is None:
        parser = ConfigParser.ConfigParser()
        parser.readfp(open('/etc/hokuto.cfg'))
        conf = parser.items('config')
        userconfig = {}
        for c in conf:
            val = c[1]
            if (c[1] == 'True' or c[1] == 'False'):
                val = bool(val)
            userconfig[c[0].upper().rstrip()] = val
        app.config.update(userconfig)
    else:
        for key in config:
            app.config[key] = config[key]

    # Load any environment-specific configuration file
    if os.environ.get('ONOC_CONFIG') is not None:
        app.config.from_envvar('ONOC_CONFIG')

    # Logging
    logfile = app.config.get('LOGGER_FILE', None)
    if logfile is not None:
        handler = logging.FileHandler(logfile)
        handler.setFormatter(
            logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
        loglevel = parse_logger_level(app.config.get('LOGGER_LEVEL'))
        if loglevel is not None:
            app.logger.setLevel(loglevel)
            handler.level = loglevel
        app.logger.addHandler(handler)
    app.logger.info('Hokuto is initializing...')

    # Caching
    # A little bit simplistic for now, we could improve that
    cache = SimpleCache()

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Babel
    babel = Babel(app)

    @babel.localeselector
    def babel_locateselector():
        # Fall back to configuration
        return None

    @babel.timezoneselector
    def babel_timezoneselector():
        #Fall back to configuration
        return None

    # Livestatus connector
    if app.config.get('LIVESTATUS_SOCKET', None) is not None:
        livestatus.set_server_address(app.config['LIVESTATUS_SOCKET'])
    else:
        livestatus.set_server_address(
            (app.config.get('LIVESTATUS_HOST', '127.0.0.1'),
             int(app.config.get('LIVESTATUS_PORT', 50000))))

    # Security session manager
    login_manager = LoginManager()
    login_manager.init_app(app, add_context_processor=True)
    login_manager.login_message = gettext('Please log in to access this page')
    login_manager.login_view = 'login'

    # A useful route converter that filters a URL using a regular expression
    # It can be used like this in a rule : blah/<regex([a-z]):data>
    class RegexConverter(BaseConverter):
        def __init__(self, map, *items):
            super(RegexConverter, self).__init__(map)
            self.regex = items[0]

    app.url_map.converters['regex'] = RegexConverter

    # Assets manager
    #assets = Environment(app)
    #register_all(app, assets)

    # Include views
    import user  # User management (incl. login)
    import grapher  # Graph screens (logical & physical)
    import dashboard  # Dashboard page
    import widgetsloader  # Dashboard widgets tools
    import structureservice
    import graphiteservice  # Graphites services
    import livestatusservice  # Livestatus services
    import predictservice  # predictation tools
    import reports  # logs screens
    import configservice  # Shinken configuration web services

    #Starting point
    @app.route('/')
    @login_required
    def index():
        return render_template('main.html')

    init_db(user.User)
    app.logger.debug('Initialization successful!')
    return app
Example #7
0
# -*- coding=utf-8 -*-
from flask import Flask, session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager

from config import config

db = SQLAlchemy()

bootstrap = Bootstrap()

login_manager = LoginManager()  #实例化对象
# login_manager.session_protection = 'strong' #设置flask-login session等级
login_manager.login_view = 'admin.login'  #如果未登入转跳到指定方法
login_manager.login_message = u'please login first'  #未登入提示语


def create_app(config_name):
    """
    binding extensions to app
    regist blue prients
    """
    app = Flask(__name__, template_folder='templates')
    app.config.from_object(config[config_name])
    # config[config_name].init_app(app)

    db.init_app(app)
    with app.app_context():
        db.create_all()
        # Extensions like Flask-SQLAlchemy now know what the "current" app
Example #8
0
class Server():
    def __init__(self,
                 configfile=None,
                 basedir=None,
                 host="0.0.0.0",
                 port=5000,
                 debug=False):
        self._configfile = configfile
        self._basedir = basedir
        self._host = host
        self._port = port
        self._debug = debug

    def run(self):
        # Global as I can't work out a way to get it into PrinterStateConnection
        global printer
        global gcodeManager
        global userManager
        global eventManager

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        self._initSettings(self._configfile, self._basedir)

        # then initialize logging
        self._initLogging(self._debug)
        logger = logging.getLogger(__name__)

        eventManager = events.eventManager()
        gcodeManager = gcodefiles.GcodeManager()
        printer = Printer(gcodeManager)

        # setup system and gcode command triggers
        events.SystemCommandTrigger(printer)
        events.GcodeCommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        if settings().getBoolean(["accessControl", "enabled"]):
            userManagerName = settings().get(["accessControl", "userManager"])
            try:
                clazz = util.getClass(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)

        app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
        login_manager = LoginManager()
        login_manager.session_protection = "strong"
        login_manager.user_callback = load_user
        if userManager is None:
            login_manager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        login_manager.init_app(app)

        if self._host is None:
            self._host = settings().get(["server", "host"])
        if self._port is None:
            self._port = settings().getInt(["server", "port"])

        logger.info("Listening on http://%s:%d" % (self._host, self._port))
        app.debug = self._debug

        self._router = tornadio2.TornadioRouter(self._createSocketConnection)

        self._tornado_app = Application(self._router.urls +
                                        [(".*", FallbackHandler, {
                                            "fallback": WSGIContainer(app)
                                        })])
        self._server = HTTPServer(self._tornado_app)
        self._server.listen(self._port, address=self._host)

        eventManager.fire("Startup")
        if settings().getBoolean(["serial", "autoconnect"]):
            (port, baudrate) = settings().get(
                ["serial", "port"]), settings().getInt(["serial", "baudrate"])
            connectionOptions = getConnectionOptions()
            if port in connectionOptions["ports"]:
                printer.connect(port, baudrate)
        IOLoop.instance().start()
def config_web(args):
    from flask import Flask, request, json
    from flask.ext.login import LoginManager
    from flask.ext.oauth import (
        OAuth, OAuthRemoteApp, OAuthException, get_etree
    )
    from werkzeug import url_decode, parse_options_header
    import flask.ext.oauth as nasty_patch_to_oauth

    global app
    app = Flask('wikimetrics')
    # note absolute_path does not change on the life of the application
    app.absolute_path_to_app_root = get_absolute_path()
    # TODO do we need this config to be created like an object instead of a dictionary?
    web_config = create_object_from_text_config_file(args.web_config)
    # if args.override_config:
    # override_config = create_object_from_text_config_file(args.override_config)
    # TODO override one obj with other, can we use dict?

    app.config.from_object(web_config)

    version, latest = get_wikimetrics_version()
    app.config['WIKIMETRICS_LATEST'] = latest
    app.config['WIKIMETRICS_VERSION'] = version
    
    # configure logging
    if not app.config['DEBUG']:
        import logging
        import sys
        app.logger.addHandler(logging.StreamHandler(stream=sys.stderr))
    
    global login_manager
    login_manager = LoginManager()
    login_manager.init_app(app)

    # TODO, this does not need to be a
    # global, could be stored in flask application context
    global google
    oauth = OAuth()
    google = oauth.remote_app(
        'google',
        base_url=app.config['GOOGLE_BASE_URL'],
        authorize_url=app.config['GOOGLE_AUTH_URI'],
        request_token_url=None,
        request_token_params={
            'scope': app.config['GOOGLE_AUTH_SCOPE'],
            'response_type': 'code',
        },
        access_token_url=app.config['GOOGLE_TOKEN_URI'],
        access_token_method='POST',
        access_token_params={
            'grant_type':
            'authorization_code'
        },
        consumer_key=app.config['GOOGLE_CLIENT_ID'],
        consumer_secret=app.config['GOOGLE_CLIENT_SECRET'],
    )

    global mw_oauth_token
    mw_oauth_token = ConsumerToken(
        app.config['META_MW_CONSUMER_KEY'],
        app.config['META_MW_CLIENT_SECRET'],
    )
Example #10
0
from flask import Flask, render_template, send_from_directory
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.heroku import Heroku
from flask.ext.login import LoginManager
import os

app = Flask(__name__) #create our application object
app.config.from_object('config') #load our local config file

heroku = Heroku(app) #create a heroku config object from our app object

login_manager = LoginManager(app) #create a LoginManager Object from our app object

db = SQLAlchemy(app) #create a db (SQLAlchemy) object from our app object

#register the users module blueprint
from app.users.views import mod as usersModule
app.register_blueprint(usersModule)

#add our view as the login view to finish configuring the LoginManager
login_manager.login_view = "users.login_view"

#register the tracking module blueprint
from app.tracking.views import mod as trackingModule
app.register_blueprint(trackingModule)

#----------------------------------------
# controllers
#----------------------------------------

@app.route('/favicon.ico')
Example #11
0
def create_app(options):
    """
        Create the application. Files outside the app directory can import
        this function and use it to create the application
    """
    app = Flask(__name__)

    # config
    app.config.from_object(settings)
    app.config.update(options)

    # views as blueprint
    app.register_blueprint(comments_bp)

    # db
    db.init_app(app)

    # admin
    admin = Admin(app,
                  name="Comimoc",
                  index_view=LoginView(app.config, name="Index"))
    admin.add_view(CommentModelView())
    admin.add_view(UserModelView())

    # login
    login_manager = LoginManager(app)

    @login_manager.user_loader
    def load_user(user_id):
        # .first() return None if no user as Flask-Login needs
        return User.objects(id=user_id).first()

    # CORS
    @app.after_request
    def add_headers(response):
        '''
        Add some headers to the response
        to be able to perform some CORS request
        '''
        if not app.config.get("USE_CORS", False):
            return response

        origin = request.headers.get("Origin")
        if origin not in app.config['CORS_ALLOW_ORIGIN_WHITELIST']:
            return response

        response.headers.add('Access-Control-Allow-Origin', origin)
        if app.config['CORS_ALLOW_CREDENTIALS']:
            response.headers.add('Access-Control-Allow-Credentials', 'true')
        response.headers.add('Access-Control-Allow-Methods',
                             app.config['CORS_ALLOW_METHODS'])
        response.headers.add('Access-Control-Allow-Headers',
                             app.config['CORS_ALLOW_HEADERS'])
        response.headers.add('Access-Control-Max-Age',
                             app.config['CORS_MAX_AGE'])

        return response

    # ping pong
    @app.route('/ping', methods=['GET'])
    def ping():
        return 'pong', 200

    return app
Example #12
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager
from flask.ext.mail import Mail

basedir = os.path.abspath(os.path.dirname(__file__))
db = SQLAlchemy()
bootstrap = Bootstrap()
auth_manager = LoginManager()
auth_manager.session_protection = 'strong'
auth_manager.login_view = 'bp_authentication.login'
email = Mail()


class Config:
    SECRET_KEY = 'YOU WONT GUESS'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    TOKEN_EXPIRATION = 3600
    MAIL_SENDER = '*****@*****.**'
    DEFAULT_PAGE = 'bp_profile.profile-detail'
    UPLOAD_FOLDER = 'beattime/static/beattime/img/avatars'
    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])


class DevConfig(Config):
    DEBUG = True
Example #13
0
class Server():
    def __init__(self,
                 configfile=None,
                 basedir=None,
                 host="0.0.0.0",
                 port=5000,
                 debug=False,
                 allowRoot=False,
                 logConf=None):
        self._configfile = configfile
        self._basedir = basedir
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
        self._logConf = logConf
        self._server = None

        self._logger = None

        self._lifecycle_callbacks = defaultdict(list)

        self._template_searchpaths = []

    def run(self):
        if not self._allowRoot:
            self._check_for_root()

        global app
        global babel

        global printer
        global printerProfileManager
        global fileManager
        global slicingManager
        global analysisQueue
        global userManager
        global eventManager
        global loginManager
        global pluginManager
        global appSessionManager
        global pluginLifecycleManager
        global debug

        from tornado.ioloop import IOLoop
        from tornado.web import Application, RequestHandler

        import sys

        debug = self._debug

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        s = settings(init=True,
                     basedir=self._basedir,
                     configfile=self._configfile)

        # then monkey patch a bunch of stuff
        util.tornado.fix_ioloop_scheduling()
        util.flask.enable_additional_translations(
            additional_folders=[s.getBaseFolder("translations")])

        # setup app
        self._setup_app()

        # setup i18n
        self._setup_i18n(app)

        # then initialize logging
        self._setup_logging(self._debug, self._logConf)
        self._logger = logging.getLogger(__name__)

        def exception_logger(exc_type, exc_value, exc_tb):
            self._logger.error("Uncaught exception",
                               exc_info=(exc_type, exc_value, exc_tb))

        sys.excepthook = exception_logger
        self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

        # then initialize the plugin manager
        pluginManager = octoprint.plugin.plugin_manager(init=True)

        printerProfileManager = PrinterProfileManager()
        eventManager = events.eventManager()
        analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
        slicingManager = octoprint.slicing.SlicingManager(
            s.getBaseFolder("slicingProfiles"), printerProfileManager)
        storage_managers = dict()
        storage_managers[
            octoprint.filemanager.FileDestinations.
            LOCAL] = octoprint.filemanager.storage.LocalFileStorage(
                s.getBaseFolder("uploads"))
        fileManager = octoprint.filemanager.FileManager(
            analysisQueue,
            slicingManager,
            printerProfileManager,
            initial_storage_managers=storage_managers)
        printer = Printer(fileManager, analysisQueue, printerProfileManager)
        appSessionManager = util.flask.AppSessionManager()
        pluginLifecycleManager = LifecycleManager(pluginManager)

        def octoprint_plugin_inject_factory(name, implementation):
            if not isinstance(implementation,
                              octoprint.plugin.OctoPrintPlugin):
                return None
            return dict(plugin_manager=pluginManager,
                        printer_profile_manager=printerProfileManager,
                        event_bus=eventManager,
                        analysis_queue=analysisQueue,
                        slicing_manager=slicingManager,
                        file_manager=fileManager,
                        printer=printer,
                        app_session_manager=appSessionManager,
                        plugin_lifecycle_manager=pluginLifecycleManager,
                        data_folder=os.path.join(
                            settings().getBaseFolder("data"), name))

        def settings_plugin_inject_factory(name, implementation):
            if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
                return None
            default_settings = implementation.get_settings_defaults()
            get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors(
            )
            plugin_settings = octoprint.plugin.plugin_settings(
                name,
                defaults=default_settings,
                get_preprocessors=get_preprocessors,
                set_preprocessors=set_preprocessors)
            return dict(settings=plugin_settings)

        def settings_plugin_config_migration(name, implementation):
            if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
                return

            settings_version = implementation.get_settings_version()
            settings_migrator = implementation.on_settings_migrate

            if settings_version is not None and settings_migrator is not None:
                stored_version = implementation._settings.get_int(
                    ["_config_version"])
                if stored_version is None or stored_version < settings_version:
                    settings_migrator(settings_version, stored_version)
                    implementation._settings.set_int(["_config_version"],
                                                     settings_version)
                    implementation._settings.save()

            implementation.on_settings_initialized()

        pluginManager.implementation_inject_factories = [
            octoprint_plugin_inject_factory, settings_plugin_inject_factory
        ]
        pluginManager.initialize_implementations()

        settingsPlugins = pluginManager.get_implementations(
            octoprint.plugin.SettingsPlugin)
        for implementation in settingsPlugins:
            try:
                settings_plugin_config_migration(implementation._identifier,
                                                 implementation)
            except:
                self._logger.exception(
                    "Error while trying to migrate settings for plugin {}, ignoring it"
                    .format(implementation._identifier))

        pluginManager.implementation_post_inits = [
            settings_plugin_config_migration
        ]

        pluginManager.log_all_plugins()

        # initialize file manager and register it for changes in the registered plugins
        fileManager.initialize()
        pluginLifecycleManager.add_callback(
            ["enabled", "disabled"],
            lambda name, plugin: fileManager.reload_plugins())

        # initialize slicing manager and register it for changes in the registered plugins
        slicingManager.initialize()
        pluginLifecycleManager.add_callback(
            ["enabled", "disabled"],
            lambda name, plugin: slicingManager.reload_slicers())

        # setup jinja2
        self._setup_jinja2()

        def template_enabled(name, plugin):
            if plugin.implementation is None or not isinstance(
                    plugin.implementation, octoprint.plugin.TemplatePlugin):
                return
            self._register_additional_template_plugin(plugin.implementation)

        def template_disabled(name, plugin):
            if plugin.implementation is None or not isinstance(
                    plugin.implementation, octoprint.plugin.TemplatePlugin):
                return
            self._unregister_additional_template_plugin(plugin.implementation)

        pluginLifecycleManager.add_callback("enabled", template_enabled)
        pluginLifecycleManager.add_callback("disabled", template_disabled)

        # setup assets
        self._setup_assets()

        # configure timelapse
        octoprint.timelapse.configureTimelapse()

        # setup command triggers
        events.CommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        # setup access control
        if s.getBoolean(["accessControl", "enabled"]):
            userManagerName = s.get(["accessControl", "userManager"])
            try:
                clazz = octoprint.util.get_class(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                self._logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)

        app.wsgi_app = util.ReverseProxied(
            app.wsgi_app, s.get(["server", "reverseProxy", "prefixHeader"]),
            s.get(["server", "reverseProxy", "schemeHeader"]),
            s.get(["server", "reverseProxy", "hostHeader"]),
            s.get(["server", "reverseProxy", "prefixFallback"]),
            s.get(["server", "reverseProxy", "schemeFallback"]),
            s.get(["server", "reverseProxy", "hostFallback"]))

        secret_key = s.get(["server", "secretKey"])
        if not secret_key:
            import string
            from random import choice
            chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
            secret_key = "".join(choice(chars) for _ in xrange(32))
            s.set(["server", "secretKey"], secret_key)
            s.save()
        app.secret_key = secret_key
        loginManager = LoginManager()
        loginManager.session_protection = "strong"
        loginManager.user_callback = load_user
        if userManager is None:
            loginManager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        loginManager.init_app(app)

        if self._host is None:
            self._host = s.get(["server", "host"])
        if self._port is None:
            self._port = s.getInt(["server", "port"])

        app.debug = self._debug

        # register API blueprint
        self._setup_blueprints()

        ## Tornado initialization starts here

        ioloop = IOLoop()
        ioloop.install()

        self._router = SockJSRouter(self._create_socket_connection, "/sockjs")

        upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]),
                               path=s.get(["server", "uploads", "pathSuffix"]))

        server_routes = self._router.urls + [
            # various downloads
            (r"/downloads/timelapse/([^/]*\.mpg)",
             util.tornado.LargeResponseHandler,
             dict(path=s.getBaseFolder("timelapse"), as_attachment=True)),
            (r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler,
             dict(path=s.getBaseFolder("uploads"),
                  as_attachment=True,
                  path_validation=util.tornado.path_validation_factory(
                      lambda path: not os.path.basename(path).startswith("."),
                      status_code=404))),
            (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler,
             dict(path=s.getBaseFolder("logs"),
                  as_attachment=True,
                  access_validation=util.tornado.access_validation_factory(
                      app, loginManager, util.flask.admin_validator))),
            # camera snapshot
            (r"/downloads/camera/current", util.tornado.UrlForwardHandler,
             dict(url=s.get(["webcam", "snapshot"]),
                  as_attachment=True,
                  access_validation=util.tornado.access_validation_factory(
                      app, loginManager, util.flask.user_validator))),
            # generated webassets
            (r"/static/webassets/(.*)", util.tornado.LargeResponseHandler,
             dict(path=os.path.join(s.getBaseFolder("generated"), "webassets"))
             )
        ]
        for name, hook in pluginManager.get_hooks(
                "octoprint.server.http.routes").items():
            try:
                result = hook(list(server_routes))
            except:
                self._logger.exception(
                    "There was an error while retrieving additional server routes from plugin hook {name}"
                    .format(**locals()))
            else:
                if isinstance(result, (list, tuple)):
                    for entry in result:
                        if not isinstance(entry, tuple) or not len(entry) == 3:
                            continue
                        if not isinstance(entry[0], basestring):
                            continue
                        if not isinstance(entry[2], dict):
                            continue

                        route, handler, kwargs = entry
                        route = r"/plugin/{name}/{route}".format(
                            name=name,
                            route=route
                            if not route.startswith("/") else route[1:])

                        self._logger.debug(
                            "Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}"
                            .format(**locals()))
                        server_routes.append((route, handler, kwargs))

        server_routes.append(
            (r".*", util.tornado.UploadStorageFallbackHandler,
             dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app),
                  file_prefix="octoprint-file-upload-",
                  file_suffix=".tmp",
                  suffixes=upload_suffixes)))

        self._tornado_app = Application(server_routes)
        max_body_sizes = [("POST", r"/api/files/([^/]*)",
                           s.getInt(["server", "uploads", "maxSize"])),
                          ("POST", r"/api/languages", 5 * 1024 * 1024)]

        # allow plugins to extend allowed maximum body sizes
        for name, hook in pluginManager.get_hooks(
                "octoprint.server.http.bodysize").items():
            try:
                result = hook(list(max_body_sizes))
            except:
                self._logger.exception(
                    "There was an error while retrieving additional upload sizes from plugin hook {name}"
                    .format(**locals()))
            else:
                if isinstance(result, (list, tuple)):
                    for entry in result:
                        if not isinstance(entry, tuple) or not len(entry) == 3:
                            continue
                        if not entry[
                                0] in util.tornado.UploadStorageFallbackHandler.BODY_METHODS:
                            continue
                        if not isinstance(entry[2], int):
                            continue

                        method, route, size = entry
                        route = r"/plugin/{name}/{route}".format(
                            name=name,
                            route=route
                            if not route.startswith("/") else route[1:])

                        self._logger.debug(
                            "Adding maximum body size of {size}B for {method} requests to {route})"
                            .format(**locals()))
                        max_body_sizes.append((method, route, size))

        self._server = util.tornado.CustomHTTPServer(
            self._tornado_app,
            max_body_sizes=max_body_sizes,
            default_max_body_size=s.getInt(["server", "maxSize"]))
        self._server.listen(self._port, address=self._host)

        eventManager.fire(events.Events.STARTUP)
        if s.getBoolean(["serial", "autoconnect"]):
            (port, baudrate) = s.get(["serial", "port"
                                      ]), s.getInt(["serial", "baudrate"])
            printer_profile = printerProfileManager.get_default()
            connectionOptions = get_connection_options()
            if port in connectionOptions["ports"]:
                printer.connect(port=port,
                                baudrate=baudrate,
                                profile=printer_profile["id"]
                                if "id" in printer_profile else "_default")

        # start up watchdogs
        if s.getBoolean(["feature", "pollWatched"]):
            # use less performant polling observer if explicitely configured
            observer = PollingObserver()
        else:
            # use os default
            observer = Observer()
        observer.schedule(
            util.watchdog.GcodeWatchdogHandler(fileManager, printer),
            s.getBaseFolder("watched"))
        observer.start()

        # run our startup plugins
        octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
                                     "on_startup",
                                     args=(self._host, self._port))

        def call_on_startup(name, plugin):
            implementation = plugin.get_implementation(
                octoprint.plugin.StartupPlugin)
            if implementation is None:
                return
            implementation.on_startup(self._host, self._port)

        pluginLifecycleManager.add_callback("enabled", call_on_startup)

        # prepare our after startup function
        def on_after_startup():
            self._logger.info("Listening on http://%s:%d" %
                              (self._host, self._port))

            # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
            # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
            # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
            # create a single use thread in which to perform our after-startup-tasks, start that and hand back
            # control to the ioloop
            def work():
                octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
                                             "on_after_startup")

                def call_on_after_startup(name, plugin):
                    implementation = plugin.get_implementation(
                        octoprint.plugin.StartupPlugin)
                    if implementation is None:
                        return
                    implementation.on_after_startup()

                pluginLifecycleManager.add_callback("enabled",
                                                    call_on_after_startup)

            import threading
            threading.Thread(target=work).start()

        ioloop.add_callback(on_after_startup)

        # prepare our shutdown function
        def on_shutdown():
            # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods
            # on all registered ShutdownPlugins
            self._logger.info("Shutting down...")
            observer.stop()
            observer.join()
            octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
                                         "on_shutdown")
            self._logger.info("Goodbye!")

        atexit.register(on_shutdown)

        def sigterm_handler(*args, **kwargs):
            # will stop tornado on SIGTERM, making the program exit cleanly
            def shutdown_tornado():
                ioloop.stop()

            ioloop.add_callback_from_signal(shutdown_tornado)

        signal.signal(signal.SIGTERM, sigterm_handler)

        try:
            # this is the main loop - as long as tornado is running, OctoPrint is running
            ioloop.start()
        except (KeyboardInterrupt, SystemExit):
            pass
        except:
            self._logger.fatal(
                "Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!"
            )
            self._logger.exception("Stacktrace follows:")
Example #14
0
from libraries.graphLib.graphe_tbc import GraphTBC

#Create Flask app
server = Flask(__name__)

# Import Config
server.config.from_pyfile('../server.config')

# SQLAlchemy
db = SQLAlchemy(server)

# Celery
celery = make_celery(server)

# Graphe
G = GraphTBC()

from project.libraries.celeryLib.tasks import *

# FlaskLogin
login_manager = LoginManager(server)

# FlaskPrincipal
Principal(server)

# FlaskGCM
clientGCM = FlaskGCM(server)

# FlaskAPNS
clientAPNS = FlaskAPNS(server)
Example #15
0
def unauthorized_401(app):
    lm = LoginManager()
    lm.setup_app(app)
    with raises(Unauthorized):
        with assert_fired(user_unauthorized):
            res = lm.unauthorized()
Example #16
0
class Server():
    def __init__(self,
                 configfile=None,
                 basedir=None,
                 host="0.0.0.0",
                 port=5000,
                 debug=False,
                 allowRoot=False,
                 logConf=None):
        self._configfile = configfile
        self._basedir = basedir
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
        self._logConf = logConf
        self._server = None

    def run(self):
        if not self._allowRoot:
            self._checkForRoot()

        global printer
        global printerProfileManager
        global fileManager
        global slicingManager
        global analysisQueue
        global userManager
        global eventManager
        global loginManager
        global pluginManager
        global appSessionManager
        global debug

        from tornado.ioloop import IOLoop
        from tornado.web import Application

        import sys

        debug = self._debug

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        settings(init=True, basedir=self._basedir, configfile=self._configfile)

        # then initialize logging
        self._initLogging(self._debug, self._logConf)
        logger = logging.getLogger(__name__)

        def exception_logger(exc_type, exc_value, exc_tb):
            logger.error("Uncaught exception",
                         exc_info=(exc_type, exc_value, exc_tb))

        sys.excepthook = exception_logger
        logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

        # then initialize the plugin manager
        pluginManager = octoprint.plugin.plugin_manager(init=True)

        printerProfileManager = PrinterProfileManager()
        eventManager = events.eventManager()
        analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
        slicingManager = octoprint.slicing.SlicingManager(
            settings().getBaseFolder("slicingProfiles"), printerProfileManager)
        storage_managers = dict()
        storage_managers[
            octoprint.filemanager.FileDestinations.
            LOCAL] = octoprint.filemanager.storage.LocalFileStorage(
                settings().getBaseFolder("uploads"))
        fileManager = octoprint.filemanager.FileManager(
            analysisQueue,
            slicingManager,
            printerProfileManager,
            initial_storage_managers=storage_managers)
        printer = Printer(fileManager, analysisQueue, printerProfileManager)
        appSessionManager = util.flask.AppSessionManager()

        def octoprint_plugin_inject_factory(name, implementation):
            if not isinstance(implementation,
                              octoprint.plugin.OctoPrintPlugin):
                return None
            return dict(plugin_manager=pluginManager,
                        printer_profile_manager=printerProfileManager,
                        event_bus=eventManager,
                        analysis_queue=analysisQueue,
                        slicing_manager=slicingManager,
                        file_manager=fileManager,
                        printer=printer,
                        app_session_manager=appSessionManager)

        def settings_plugin_inject_factory(name, implementation):
            if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
                return None
            default_settings = implementation.get_settings_defaults()
            get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors(
            )
            plugin_settings = octoprint.plugin.plugin_settings(
                name,
                defaults=default_settings,
                get_preprocessors=get_preprocessors,
                set_preprocessors=set_preprocessors)
            return dict(settings=plugin_settings)

        pluginManager.initialize_implementations(additional_inject_factories=[
            octoprint_plugin_inject_factory, settings_plugin_inject_factory
        ])
        pluginManager.log_all_plugins()
        slicingManager.initialize()

        # configure additional template folders for jinja2
        template_plugins = pluginManager.get_implementations(
            octoprint.plugin.TemplatePlugin)
        additional_template_folders = []
        for plugin in template_plugins:
            folder = plugin.get_template_folder()
            if folder is not None:
                additional_template_folders.append(
                    plugin.get_template_folder())

        import jinja2
        jinja_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader(additional_template_folders)
        ])
        app.jinja_loader = jinja_loader
        del jinja2
        app.jinja_env.add_extension("jinja2.ext.do")

        # configure timelapse
        octoprint.timelapse.configureTimelapse()

        # setup command triggers
        events.CommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        if settings().getBoolean(["accessControl", "enabled"]):
            userManagerName = settings().get(["accessControl", "userManager"])
            try:
                clazz = octoprint.util.get_class(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)

        app.wsgi_app = util.ReverseProxied(
            app.wsgi_app,
            settings().get(["server", "reverseProxy", "prefixHeader"]),
            settings().get(["server", "reverseProxy", "schemeHeader"]),
            settings().get(["server", "reverseProxy", "hostHeader"]),
            settings().get(["server", "reverseProxy", "prefixFallback"]),
            settings().get(["server", "reverseProxy", "schemeFallback"]),
            settings().get(["server", "reverseProxy", "hostFallback"]))

        secret_key = settings().get(["server", "secretKey"])
        if not secret_key:
            import string
            from random import choice
            chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
            secret_key = "".join(choice(chars) for _ in xrange(32))
            settings().set(["server", "secretKey"], secret_key)
            settings().save()
        app.secret_key = secret_key
        loginManager = LoginManager()
        loginManager.session_protection = "strong"
        loginManager.user_callback = load_user
        if userManager is None:
            loginManager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        loginManager.init_app(app)

        if self._host is None:
            self._host = settings().get(["server", "host"])
        if self._port is None:
            self._port = settings().getInt(["server", "port"])

        app.debug = self._debug

        from octoprint.server.api import api
        from octoprint.server.apps import apps

        # register API blueprint
        app.register_blueprint(api, url_prefix="/api")
        app.register_blueprint(apps, url_prefix="/apps")

        # also register any blueprints defined in BlueprintPlugins
        blueprint_plugins = octoprint.plugin.plugin_manager(
        ).get_implementations(octoprint.plugin.BlueprintPlugin)
        for plugin in blueprint_plugins:
            name = plugin._identifier
            blueprint = plugin.get_blueprint()
            if blueprint is None:
                continue

            if plugin.is_blueprint_protected():
                from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
                blueprint.before_request(apiKeyRequestHandler)
                blueprint.after_request(corsResponseHandler)

            url_prefix = "/plugin/{name}".format(name=name)
            app.register_blueprint(blueprint, url_prefix=url_prefix)
            logger.debug(
                "Registered API of plugin {name} under URL prefix {url_prefix}"
                .format(name=name, url_prefix=url_prefix))

        ## Tornado initialization starts here

        ioloop = IOLoop()
        ioloop.install()

        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")

        upload_suffixes = dict(
            name=settings().get(["server", "uploads", "nameSuffix"]),
            path=settings().get(["server", "uploads", "pathSuffix"]))
        self._tornado_app = Application(
            self._router.urls +
            [(r"/downloads/timelapse/([^/]*\.mpg)",
              util.tornado.LargeResponseHandler,
              dict(path=settings().getBaseFolder("timelapse"),
                   as_attachment=True)),
             (r"/downloads/files/local/([^/]*\.(gco|gcode|g|stl))",
              util.tornado.LargeResponseHandler,
              dict(path=settings().getBaseFolder("uploads"),
                   as_attachment=True)),
             (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler,
              dict(path=settings().getBaseFolder("logs"),
                   as_attachment=True,
                   access_validation=util.tornado.access_validation_factory(
                       app, loginManager, util.flask.admin_validator))),
             (r"/downloads/camera/current", util.tornado.UrlForwardHandler,
              dict(url=settings().get(["webcam", "snapshot"]),
                   as_attachment=True,
                   access_validation=util.tornado.access_validation_factory(
                       app, loginManager, util.flask.user_validator))),
             (r".*", util.tornado.UploadStorageFallbackHandler,
              dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app),
                   file_prefix="octoprint-file-upload-",
                   file_suffix=".tmp",
                   suffixes=upload_suffixes))])
        max_body_sizes = [("POST", r"/api/files/([^/]*)",
                           settings().getInt(["server", "uploads",
                                              "maxSize"]))]
        self._server = util.tornado.CustomHTTPServer(
            self._tornado_app,
            max_body_sizes=max_body_sizes,
            default_max_body_size=settings().getInt(["server", "maxSize"]))
        self._server.listen(self._port, address=self._host)

        eventManager.fire(events.Events.STARTUP)
        if settings().getBoolean(["serial", "autoconnect"]):
            (port, baudrate) = settings().get(
                ["serial", "port"]), settings().getInt(["serial", "baudrate"])
            printer_profile = printerProfileManager.get_default()
            connectionOptions = get_connection_options()
            if port in connectionOptions["ports"]:
                printer.connect(port=port,
                                baudrate=baudrate,
                                profile=printer_profile["id"]
                                if "id" in printer_profile else "_default")

        # start up watchdogs
        observer = Observer()
        observer.schedule(
            util.watchdog.GcodeWatchdogHandler(fileManager, printer),
            settings().getBaseFolder("watched"))
        observer.start()

        # run our startup plugins
        octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
                                     "on_startup",
                                     args=(self._host, self._port))

        # prepare our after startup function
        def on_after_startup():
            logger.info("Listening on http://%s:%d" % (self._host, self._port))

            # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
            # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
            # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
            # create a single use thread in which to perform our after-startup-tasks, start that and hand back
            # control to the ioloop
            def work():
                octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
                                             "on_after_startup")

            import threading
            threading.Thread(target=work).start()

        ioloop.add_callback(on_after_startup)

        # prepare our shutdown function
        def on_shutdown():
            logger.info("Goodbye!")
            observer.stop()
            observer.join()
            octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
                                         "on_shutdown")

        atexit.register(on_shutdown)

        try:
            ioloop.start()
        except KeyboardInterrupt:
            pass
        except:
            logger.fatal(
                "Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!"
            )
            logger.exception("Stacktrace follows:")
Example #17
0
else:
    print("Startup Failure: You need to place a "
          "config.py or user_config.py in your content directory.")
    exit(1)

app.config['CONTENT_DIR'] = 'content'
app.config['TITLE'] = 'wiki'

app.config['TITLELNK'] = []

app.config.from_pyfile(
    os.path.join(app.config.get('CONTENT_DIR'), config_filename))

manager = Manager(app)

loginmanager = LoginManager()
loginmanager.init_app(app)
loginmanager.login_view = 'user_login'

wiki = Wiki(app.config.get('CONTENT_DIR'))

users = UserManager(app.config.get('USER_CONFIG_DIR'))

if not os.path.exists(app.config.get('UPLOAD_DIR')):
    os.makedirs(app.config.get('UPLOAD_DIR'))


@loginmanager.user_loader
def load_user(name):
    return users.get_user(name)
Example #18
0
def create_login_manager():
    return LoginManager()
Example #19
0
def init(config):
    global app
    global babel
    global login_manager
    global db

    # Main application object
    app = Flask(__name__)
    if config is None:
        app.config.from_pyfile('config.cfg')
    else:
        for key in config:
            app.config[key] = config[key]

    # Load any environment-specific configuration file
    if os.environ.get('ONOC_CONFIG') is not None:
        app.config.from_envvar('ONOC_CONFIG')

    # Logging
    logfile = app.config.get('LOGGING', None)
    if logfile is not None:
        import logging
        handler = logging.FileHandler(logfile)
        handler.level = logging.DEBUG
        app.logger.addHandler(handler)


    # SQLAlchemy
    db = SQLAlchemy(app)

    # Babel
    babel = Babel(app)

    @babel.localeselector
    def babel_locateselector():
        # Fall back to configuration
        return None

    @babel.timezoneselector
    def babel_timezoneselector():
        #Fall back to configuration
        return None

    # Livestatus connector
    if app.config.get('LIVESTATUS_SOCKET', None) is not None:
        livestatus.set_server_address(app.config['LIVESTATUS_SOCKET'])
    else:
        livestatus.set_server_address((app.config.get('LIVESTATUS_HOST', '127.0.0.1'),
                                               int(app.config.get('LIVESTATUS_PORT', 50000))))

    # Security session manager
    login_manager = LoginManager()
    login_manager.init_app(app, add_context_processor=True)
    login_manager.login_message = gettext('Please log in to access this page')
    login_manager.login_view = 'login'

    # A useful route converter that filters a URL using a regular expression
    # It can be used like this in a rule : blah/<regex([a-z]):data>
    class RegexConverter(BaseConverter):
        def __init__(self, map, *items):
            super(RegexConverter, self).__init__(map)
            self.regex = items[0]

    app.url_map.converters['regex'] = RegexConverter

    # Assets manager
    #assets = Environment(app)
    #register_all(app, assets)

    # Include views
    import user # User management (incl. login)
    import grapher # Graph screens (logical & physical)
    import dashboard # Dashboard page
    import widgetsloader # Dashboard widgets tools
    import structureservice
    import graphiteservice # Graphites services
    import livestatusservice # Livestatus services
    import predictservice # predictation tools
    import reports # logs screens

    #Starting point
    @app.route('/')
    @login_required
    def index():
        return render_template('main.html')

    init_db(user.User)
Example #20
0
def create_app():

    app = flask.Flask(__name__)
    app.debug = True

    # Configurations set above in the ConfigClass ...
    app.config.from_object(__name__ + '.ConfigClass')

    #app.logger.debug(ssl.PROTOCOL_TLSv1)

    # Initialize Flask extensions
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
    mail = Mail(app)  # Initialize Flask-Mail ...
    bcrypt = Bcrypt(app)  # Inifialize Bcrypt ...

    # Define the User data model. Make sure to add flask.ext.user UserMixin !!!
    class User(db.Model, UserMixin):

        id = db.Column(db.Integer, primary_key=True)

        password = db.Column(db.String(255), nullable=False, server_default='')
        #reset_password_token = db.Column(db.String(100), nullable=False, server_default='')
        authenticate = db.Column(db.Boolean)

        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())

        is_enabled = db.Column(db.Boolean(), nullable=False, default=False)
        active = db.Column('is_active',
                           db.Boolean(),
                           nullable=False,
                           server_default='0')
        registered_on = db.Column('registered_on', db.DateTime)

        chrome_hash = db.Column(db.String(500))
        secure_token = db.Column(db.String(500))

        def hash_password(self, password):
            self.password = bcrypt.generate_password_hash(password)

        def verify_password(self, password):
            return bcrypt.check_password_hash(self.password, password)

        def activate(self):
            self.authenticate = True

        def is_authenticated(self):
            return True

        def is_active(self):
            return True

        def is_anonymous(self):
            return False

        def get_id(self):
            return unicode(self.id)

        def set_chrome_hash(self):
            self.chrome_hash = str(hashlib.sha224(self.email).hexdigest())

        def set_secure_token(self):
            secure_token = make_secure_token(self.email)

    class Path(db.Model):

        __tablename__ = 'paths'

        id = db.Column(db.Integer, primary_key=True)
        path = db.Column(db.String(50), nullable=False, unique=True)
        url = db.Column(db.String(250), nullable=False)
        creator_id = db.Column(db.Integer, nullable=True)
        clicks = db.Column(db.Integer, default=0)
        note = db.Column(db.String(300), default="No note.")
        timestamp = db.Column(db.DateTime)

    ### INITIALIZE THE DB, USER MODEL, LOGIN MANAGER, ETC. ... ###

    db.create_all()  # Create all database tables if they don't exist ...
    db_adapter = SQLAlchemyAdapter(db, User)  # Register the User model
    user_manager = UserManager(db_adapter, app)  # Initialize Flask-User
    login_manager = LoginManager()  # Initialize the Login manager? ...
    login_manager.init_app(
        app)  # this needs a secret key, set above in the Config class

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    ######################################################################
    #                                                                    #
    #                       CONFIRMATION EMAILS                          #
    #                                                                    #
    ######################################################################

    def get_serializer(secret_key=None):
        app.logger.debug("in get_serializer")
        if secret_key is None:
            secret_key = app.secret_key
        return URLSafeSerializer(secret_key)

    @app.route('/users/activate/<payload>')
    def activate_user(payload):
        app.logger.debug("in activate_user")
        s = get_serializer()
        try:
            user_id = s.loads(payload)
        except BadSignature:
            abort(404)

        user = User.query.get_or_404(user_id)
        user.authenticate = True
        db.session.commit()

        flash('User activated')
        return flask.redirect(home_url)

    def get_activation_link(user):
        app.logger.debug("in get_activation_link")
        s = get_serializer()
        payload = s.dumps(user.id)

        return url_for('activate_user', payload=payload)

    def send_confirmation_email(user):
        link = get_activation_link(user)
        msg = Message("Hello", sender="*****@*****.**")
        msg.add_recipient(user.email)
        msg.body = "people.ischool.berkeley.edu/~brian.carlo/server" + link
        mail.send(msg)

    ######################################################################
    #                                                                    #
    #                       REGISTRATION AND LOGIN                       #
    #                                                                    #
    ######################################################################

    @app.route('/login.html', methods=["GET", "POST"])
    def login():
        if request.method == 'GET':
            return render_template('login.html')
        email = request.form['email']
        password = request.form['password']

        registered_user = User.query.filter_by(email=email).first()

        if registered_user.verify_password(password):
            login_user(registered_user)
            flash('Logged in successfully')
            return flask.redirect(dashboard_url)
        else:
            flash('Username or Password is invalid', 'error')
            return render_template('login.html')

    @app.route('/register.html', methods=['GET', 'POST'])
    def register():
        if request.method == 'GET':
            return render_template('register.html')
        try:
            user = User(email=request.form['email'])
            user.hash_password(request.form['password'])
            db.session.add(user)
            db.session.commit()
            registered_user = User.query.filter_by(email=user.email).first()
            send_confirmation_email(registered_user)
            registered_user.set_chrome_hash()

            app.logger.debug(registered_user.chrome_hash)
            db.session.commit()

            response = make_response(flask.redirect(home_url))
            response.set_cookie('chrome_id',
                                value=registered_user.chrome_hash,
                                max_age=2592000)
            return response
        except:
            flash(
                "That e-mail address is already Nerping for real. Maybe Nerp a different e-mail?"
            )
            return render_template('register.html')

    ######################################################################
    #                                                                    #
    #                           POSTING PATHS!                           #
    #                                                                    #
    ######################################################################

    @app.before_request
    def validate():  # runs before any app.route()
        """ Helper validates URLs and handles errors for CHROME_PUT(), SHORTS_PUT(). """
        if request.path == '/shorts':  # if the server request is to '/shorts' ...
            shortpath = str(
                request.form.get('shortpath')).strip()  # grab the shortpath
            if shortpath == "":
                pass  # if there's no path, no worries
            else:
                if Path.query.filter_by(path=shortpath).first():
                    app.logger.debug("made it here")
                    flash("already taken!")

            inputURL = str(
                request.form.get('url')).lower().strip()  # grab the URL
            if inputURL == None or inputURL == "":  # if it's not there ...
                abort(412)  # throw the 412

    def insert_path_for_user_or_not(path, inputURL):
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        try:
            new_path = Path(path=path,
                            url=inputURL,
                            creator_id=current_user.id,
                            timestamp=datetime.utcnow())
            app.logger.debug("UID!")
        except:
            app.logger.debug("NOID!")
            new_path = Path(path=path,
                            url=inputURL,
                            creator_id=None,
                            timestamp=datetime.utcnow())
        db.session.add(new_path)
        db.session.commit()

    def make_random_path():
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        myPath = ""
        for i in range(7):
            myPath = myPath + chr(random.choice(possible))
        return myPath

    def format_url(inputURL):
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        parsed = urlparse(inputURL)
        if parsed.scheme == "":
            inputURL = "http://" + inputURL

        h = httplib2.Http()
        try:
            response = h.request(inputURL, 'HEAD')
            inputURL = response[0]['content-location']
            return inputURL
        except:
            return False

    def insert_note(path):
        added_path = Path.query.filter_by(path=path).first()
        added_path.note = str(request.form.get('note', ''))

    @app.route('/chrome', methods=['PUT', 'POST'])
    def chrome_put():

        if 'chrome_id' not in request.cookies:
            user_id = 0
        else:
            chrome_hash = request.cookies.get('chrome_id')
            user = User.query.filter_by(chrome_hash=chrome_hash).first()
            user_id = user.id

        inputURL = str(request.form.get('url', '')).lower()

        inputURL = format_url(inputURL)
        if not inputURL:
            response = make_response("Broken URL. Try another")
            return response

        shortpath = str(request.form.get('shortpath', ''))

        if not shortpath:
            myPath = make_random_path()
            while Path.query.filter_by(path=myPath).first():
                myPath = make_random_path()
            insert_path_for_user_or_not(myPath, inputURL)
            insert_note(myPath)
        else:
            insert_path_for_user_or_not(shortpath, inputURL)
            insert_note(shortpath)
        return flask.redirect(
            'http://people.ischool.berkeley.edu/~brian.carlo/server/chrome.html'
        )

    @app.route('/shorts', methods=['PUT', 'POST'])
    def shorts_put():
        try:
            inputURL = str(request.form.get('url', '')).lower()
            inputURL = format_url(inputURL)
            if not inputURL:
                response = make_response("Broken URL. Try another")
                return response

            shortpath = str(request.form.get('shortpath', ''))

            app.logger.debug(inputURL + "," + shortpath)

            if not shortpath:
                myPath = make_random_path()
                while Path.query.filter_by(path=myPath).first():
                    myPath = make_random_path()
                insert_path_for_user_or_not(myPath, inputURL)
                path = myPath
            else:
                insert_path_for_user_or_not(shortpath, inputURL)
                path = shortpath
            try:
                if current_user.id:
                    return flask.redirect(dashboard_url)
            except:
                flash("nerp.me/" + path)
                return render_template('promo.html')

        except:
            abort(405)

    @app.route('/delete', methods=['POST', 'PUT'])
    @login_required
    def delete_nerp():
        nerp_id = str(request.form.get('nerp_id',
                                       ''))  # REMEMBER TO CHANGE "NERP-ID"
        death_row_nerp = Path.query.filter_by(id=nerp_id).first()
        db.session.delete(death_row_nerp)
        db.session.commit()

    ######################################################################
    #                                                                    #
    #                           GET METHODS!                             #
    #                                                                    #
    ######################################################################

    @app.route('/shorts/<shortpath>', methods=['GET'])
    def shorts_shortpath(shortpath):
        try:
            path = Path.query.filter_by(path=shortpath).first()
            url = path.url
            path.clicks = path.clicks + 1
            db.session.commit()
            return flask.redirect(url)
        except:
            abort(404)

    @app.route('/chrome.html', methods=['GET'])
    def chrome_dash():
        return render_template('chrome.html')

    @app.route('/home.html', methods=['GET'])
    def root():
        return render_template('promo.html')

    @app.route('/dashboard.html', methods=['GET'])
    @login_required
    def dashboard():
        items = Path.query.filter_by(creator_id=current_user.id).order_by(
            Path.timestamp.desc()).all()
        top_nerps = Path.query.order_by(Path.clicks.desc()).limit(10)
        return render_template('dashboard.html',
                               items=items,
                               top_nerps=top_nerps)

    @app.route('/logout', methods=['GET'])
    def logout():
        logout_user()
        return flask.redirect(home_url)

    ######################################################################
    #                                                                    #
    #                           ERROR HANDLERS!                          #
    #                                                                    #
    ######################################################################

    @app.errorhandler(412)
    def precondition_failed(e):
        flash("put in a url, dumbass")
        try:
            if current_user.is_authenticated:
                return flask.redirect(dashboard_url)
        except:
            return render_template('promo.html')

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

    @app.errorhandler(405)
    def method_not_allowed(e):
        return render_template('promo.html'), 405

    @app.errorhandler(409)
    def conflict(e):
        return render_template(
            'final_temp_3.html',
            code=409,
            message="Short path already exists. Please choose a different path."
        ), 409

    return app
Example #21
0
class Server():
    def __init__(self,
                 configfile=None,
                 basedir=None,
                 host="0.0.0.0",
                 port=5000,
                 debug=False,
                 allowRoot=False,
                 logConf=None):
        self._configfile = configfile
        self._basedir = basedir
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
        self._logConf = logConf
        self._ioLoop = None

    def stop(self):
        if self._ioLoop:
            self._ioLoop.stop()
            self._ioLoop = None

    def run(self):
        if not self._allowRoot:
            self._checkForRoot()

        global userManager
        global eventManager
        global loginManager
        global debug
        global softwareManager
        global discoveryManager
        global VERSION
        global UI_API_KEY

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler

        from astroprint.printfiles.watchdogs import UploadCleanupWatchdogHandler

        debug = self._debug

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        self._initSettings(self._configfile, self._basedir)
        s = settings()

        UI_API_KEY = s.getString(['api', 'key'])

        # then initialize logging
        self._initLogging(self._debug, self._logConf)
        logger = logging.getLogger(__name__)

        if s.getBoolean(["accessControl", "enabled"]):
            userManagerName = s.get(["accessControl", "userManager"])
            try:
                clazz = util.getClass(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)

        softwareManager = swManager()
        VERSION = softwareManager.versionString

        logger.info("Starting AstroBox (%s) - Commit (%s)" %
                    (VERSION, softwareManager.commit))

        from astroprint.migration import migrateSettings
        migrateSettings()

        eventManager = events.eventManager()
        printer = printerManager(printerProfileManager().data['driver'])

        #Start some of the managers here to make sure there are no thread collisions
        from astroprint.network.manager import networkManager
        from astroprint.boxrouter import boxrouterManager

        networkManager()
        boxrouterManager()

        # configure timelapse
        #octoprint.timelapse.configureTimelapse()

        app.wsgi_app = ReverseProxied(app.wsgi_app)

        app.secret_key = boxrouterManager().boxId
        loginManager = LoginManager()
        loginManager.session_protection = "strong"
        loginManager.user_callback = load_user
        if userManager is None:
            loginManager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        loginManager.init_app(app)

        # setup command triggers
        events.CommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        if networkManager().isOnline():
            softwareManager.checkForcedUpdate()

        if self._host is None:
            self._host = s.get(["server", "host"])
        if self._port is None:
            self._port = s.getInt(["server", "port"])

        app.debug = self._debug

        from octoprint.server.api import api

        app.register_blueprint(api, url_prefix="/api")

        boxrouterManager(
        )  # Makes sure the singleton is created here. It doesn't need to be stored
        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")

        discoveryManager = DiscoveryManager()

        def access_validation_factory(validator):
            """
			Creates an access validation wrapper using the supplied validator.

			:param validator: the access validator to use inside the validation wrapper
			:return: an access validation wrapper taking a request as parameter and performing the request validation
			"""
            def f(request):
                """
				Creates a custom wsgi and Flask request context in order to be able to process user information
				stored in the current session.

				:param request: The Tornado request for which to create the environment and context
				"""
                wsgi_environ = tornado.wsgi.WSGIContainer.environ(request)
                with app.request_context(wsgi_environ):
                    app.session_interface.open_session(app, request)
                    loginManager.reload_user()
                    validator(request)

            return f

        self._tornado_app = Application(self._router.urls + [
            #(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": s.getBaseFolder("timelapse"), "as_attachment": True}),
            (r"/downloads/files/local/([^/]*\.(gco|gcode))",
             LargeResponseHandler, {
                 "path": s.getBaseFolder("uploads"),
                 "as_attachment": True
             }),
            (r"/downloads/logs/([^/]*)", LargeResponseHandler, {
                "path": s.getBaseFolder("logs"),
                "as_attachment": True,
                "access_validation": access_validation_factory(admin_validator)
            }),
            #(r"/downloads/camera/current", UrlForwardHandler, {"url": s.get(["webcam", "snapshot"]), "as_attachment": True, "access_validation": access_validation_factory(user_validator)}),
            (r".*", FallbackHandler, {
                "fallback": WSGIContainer(app.wsgi_app)
            })
        ])
        self._server = HTTPServer(
            self._tornado_app,
            max_buffer_size=167772160)  #Allows for uploads up to 160MB
        self._server.listen(self._port, address=self._host)

        logger.info("Listening on http://%s:%d" % (self._host, self._port))

        eventManager.fire(events.Events.STARTUP)
        if s.getBoolean(["serial", "autoconnect"]):
            (port, baudrate) = s.get(["serial", "port"
                                      ]), s.getInt(["serial", "baudrate"])
            connectionOptions = printer.getConnectionOptions()
            if port in connectionOptions["ports"]:
                printer.connect(port, baudrate)

        # start up watchdogs
        observer = Observer()
        observer.schedule(UploadCleanupWatchdogHandler(),
                          s.getBaseFolder("uploads"))
        observer.start()

        try:
            self._ioLoop = IOLoop.instance()
            self._ioLoop.start()

        except SystemExit:
            pass

        except:
            logger.fatal(
                "Please report this including the stacktrace below in AstroPrint's bugtracker. Thanks!"
            )
            logger.exception("Stacktrace follows:")

        finally:
            observer.stop()
            self.cleanup()

        observer.join()
        logger.info('Good Bye!')
Example #22
0
'''
rtp.site.flask_app

author | Immanuel Washington

Functions
---------
monitor_app | creates flask app for monitor db
monitor_lm | creates login manager for monitor db
monitor_db | creates monitor db from sqlalchemy
'''
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager

monitor_app = Flask(__name__, static_folder='monitor/static', template_folder='monitor/templates')
monitor_app.config.from_pyfile('monitor/settings.py')

monitor_lm = LoginManager()
monitor_lm.init_app(monitor_app)

monitor_db = SQLAlchemy(monitor_app)
Example #23
0
 def test_login_disabled_is_set(self):
     login_manager = LoginManager(self.app, add_context_processor=True)
     self.assertFalse(login_manager._login_disabled)
Example #24
0
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from flask.ext.login import LoginManager

from frontend.models.account import User

login = LoginManager()
login.login_view = 'account.login_handler'


@login.user_loader
def load_user(user_id):
    try:
        user = User.query.get(user_id)
    except Exception, e:
        user = None

    return user
Example #25
0
from __init__ import __version__
from healthcheck import run_test_resource
from init import DB
from enums import RESOURCE_TYPES
from models import Resource, Run, User
from util import render_template2, send_email
import views

APP = Flask(__name__)
BABEL = Babel(APP)
APP.config.from_pyfile('config_main.py')
APP.config.from_pyfile('../instance/config_site.py')
APP.secret_key = APP.config['SECRET_KEY']

LOGIN_MANAGER = LoginManager()
LOGIN_MANAGER.init_app(APP)

GHC_SITE_URL = APP.config['GHC_SITE_URL'].rstrip('/')

LANGUAGES = (('en', 'English'), ('fr', 'Français'), ('de', 'German'),
             ('de_DE', 'German (Germany)'))


@APP.before_request
def before_request():
    g.user = current_user
    if request.args and 'lang' in request.args and request.args['lang'] != '':
        g.current_lang = request.args['lang']
    if not hasattr(g, 'current_lang'):
        g.current_lang = 'en'
Example #26
0
 def init_login(self):
     self.login_manager = LoginManager()
     self.login_manager.init_app(self)
     self.login_manager.user_callback = self.load_user
     self.login_manager.login_view = "auth.login"
Example #27
0
from libs.database import init_db
from libs.models import Indicator
from libs.models import Setting
from libs.models import User
from werkzeug.datastructures import ImmutableMultiDict
from wtforms import PasswordField
from wtforms import StringField
from wtforms.validators import DataRequired

#
# Configuration #
#

app = Flask(__name__)
app.config['SECRET_KEY'] = 'yek_terces'
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'

# Setup Database if Necessary
init_db()

app.register_blueprint(tn_api)


class LoginForm(Form):
    user = StringField('user', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])

    def get_user(self):
        return db_session.query(User).filter_by(
Example #28
0
def lm_creation_and_setup(app):
    lm = LoginManager()
    lm.setup_app(app)
    assert app.login_manager is lm
    assert lm._load_user in app.before_request_funcs[None]
    assert lm._update_remember_cookie in app.after_request_funcs[None]
Example #29
0
import arrow
from flask.ext.login import LoginManager
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.redis import FlaskRedis
from sqlalchemy_utils import force_auto_coercion

force_auto_coercion()

db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
redis = FlaskRedis()

from .user import User
from .guest import GuestPass, GuestUser

login_manager.login_view = 'AccountView:login'


@login_manager.user_loader
def load_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return None
    user.anonymous = False
    user.authenticated = True
    return user


Example #30
0
def create_app(config_filename=None):
    app = Flask(__name__)
    app.request_class = Request
    app.url_map.converters['re'] = RegexConverter

    if config_filename is None:
        HerokuConfig(app)
    else:
        AppConfig(app, config_filename)

    from_envvars(app.config, prefix='')
    app.debug = app.config.get('DEBUG')

    # TODO: these variables probably aren't unjsonnable anymore

    # push all variables into the environment
    unjsonnable = (datetime, timedelta)
    data = {
        k: json.dumps(v)
        for k, v in app.config.items() if not isinstance(v, unjsonnable)
    }
    os.environ.update(data)

    # app.logger.info('App is running on port %s', os.environ.get('PORT'))

    if app.config['DEBUG'] is not True:
        log_level = app.config.get('LOG_LEVEL', 'DEBUG')
        app.logger.setLevel(getattr(logging, log_level.upper()))

    import bauble.db as db

    if 'LOG_SQL' in os.environ:
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    db.init_app(app)

    # register flask extensionsa
    SSLify(app, permanent=True)
    app.login_manager = LoginManager(app)
    app.login_manager.login_view = "auth.login"
    app.mail = Mail(app)
    app.babel = Babel(app)

    from .assets import init_app
    init_app(app)

    # TODO: just import everything controllers

    for controller in ['auth', 'index', 'batch']:
        module = import_module('bauble.controllers.{}'.format(controller))
        app.register_blueprint(module.blueprint)

    from bauble.resource import Resource
    controllers = [
        'search', 'family', 'genus', 'taxon', 'accession', 'plant', 'location',
        'vernacular_name'
    ]
    for controller in controllers:
        module = import_module('bauble.controllers.{}'.format(controller))
        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            # find all the blueprints in the files
            if isinstance(attr, Blueprint):
                app.register_blueprint(attr)
            # if isclass(attr) and issubclass(attr, Blueprint) and attr != Resource:
            #     app.register_blueprint(attr())

    from bauble.error import init_errorhandlers
    init_errorhandlers(app)

    app.json_encoder = JSONEncoder

    return app