Пример #1
0
 def __initLoginManager(self):
     login_manager = LoginManager()
     login_manager.anonymous_user = SupportUser.Anonymous
     login_manager.login_view = '/login'
     login_manager.login_message = ''
     login_manager.user_loader(loadUserByID)
     login_manager.init_app(self)
Пример #2
0
def setup_app(app):
    """Setup login extension."""

    app.config.setdefault('CFG_OPENID_AUTHENTICATION', False)
    app.config.setdefault('CFG_OAUTH1_AUTHENTICATION', False)
    app.config.setdefault('CFG_OAUTH2_AUTHENTICATION', False)

    @app.errorhandler(401)
    def do_login_first(error=401):
        """Displays login page when user is not authorised."""
        if request.is_xhr:
            return g._("Authorization failure"), 401
        if current_user.is_guest:
            flash(g._("Please sign in to continue."), 'info')
        else:
            flash(g._("Authorization failure."), 'danger')
        from invenio.modules.accounts.views.accounts import login
        return login(referer=request.url), 401

    # Let's create login manager.
    _login_manager = LoginManager(app)
    _login_manager.login_view = app.config.get('CFG_LOGIN_VIEW',
                                               'webaccount.login')
    _login_manager.anonymous_user = UserInfo
    _login_manager.unauthorized_handler(do_login_first)

    @_login_manager.user_loader
    def _load_user(uid):
        """
        Function should not raise an exception if uid is not valid
        or User was not found in database.
        """
        return UserInfo(int(uid))

    return app
Пример #3
0
def create_app():
    global app
    global db
    global login_manager

    # Flask
    app = Flask(__name__,
                static_folder='static/dist/',
                static_url_path='/static')
    app.config.from_object('config.flask_config')

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Login
    login_manager = LoginManager(app)
    login_manager.login_view = 'users.login'

    # Debug
    app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug')

    @login_manager.user_loader
    def load_user(userid):
        from models import User
        return User.query.get(userid)

    from app.models import AnonymousUser
    login_manager.anonymous_user = AnonymousUser

    register_blueprints(app)
    return app, db
Пример #4
0
    def initialise(self):
        """
        The application needs initialisation to load the database
        connection etc. In previous versions this was done with the
        initialisation of the class in the __init__ method. This is
        now separated into this function.
        """
        #: Check if the secret key is defined, if not raise an
        #: exception since it is required
        assert self.secret_key, 'Secret Key is not defined in config'

        #: Load the cache
        self.load_cache()

        #: Initialise the CSRF handling
        self.csrf_protection = CsrfProtect()
        self.csrf_protection.init_app(self)

        self.view_functions['static'] = self.send_static_file

        # Backend initialisation
        self.load_backend()

        #: Initialise the login handler
        login_manager = LoginManager()
        login_manager.user_loader(self._pool.get('nereid.user').load_user)
        login_manager.header_loader(
            self._pool.get('nereid.user').load_user_from_header
        )
        login_manager.token_loader(
            self._pool.get('nereid.user').load_user_from_token
        )
        login_manager.unauthorized_handler(
            self._pool.get('nereid.user').unauthorized_handler
        )
        login_manager.login_view = "nereid.website.login"
        login_manager.anonymous_user = self._pool.get('nereid.user.anonymous')
        login_manager.init_app(self)

        self.login_manager = login_manager

        # Monkey patch the url_for method from flask-login to use
        # the nereid specific url_for
        flask.ext.login.url_for = url_for

        self.template_context_processors[None].append(
            self.get_context_processors()
        )

        # Add the additional template context processors
        self.template_context_processors[None].append(
            nereid_default_template_ctx_processor
        )

        # Add template_filters registered using decorator
        for name, function in self.get_template_filters():
            self.jinja_env.filters[name] = function

        # Finally set the initialised attribute
        self.initialised = True
Пример #5
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)
    lm.init_app(app)
    return lm
Пример #6
0
    def init_app(self, app, datastore):
        """Initializes the Flask-Security extension for the specified
        application and datastore implentation.

        :param app: The application.
        :param datastore: An instance of a user datastore.
        """
        if app is None or datastore is None:
            return

        # TODO: change blueprint name
        blueprint = Blueprint('auth', __name__)

        configured = {}

        for key, value in default_config.items():
            configured[key] = app.config.get(key, value)

        app.config.update(configured)
        config = app.config

        # setup the login manager extension
        login_manager = LoginManager()
        login_manager.anonymous_user = AnonymousUser
        login_manager.login_view = config[LOGIN_VIEW_KEY]
        login_manager.setup_app(app)
        app.login_manager = login_manager

        Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
        Form = get_class_from_config(LOGIN_FORM_KEY, config)
        pw_hash = config[PASSWORD_HASH_KEY]

        app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
        app.auth_provider = Provider(Form)
        app.principal = Principal(app)

        from flask.ext import security as s
        s.User, s.Role = datastore.get_models()

        setattr(app, config[USER_DATASTORE_KEY], datastore)

        @identity_loaded.connect_via(app)
        def on_identity_loaded(sender, identity):
            if hasattr(current_user, 'id'):
                identity.provides.add(UserNeed(current_user.id))

            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

            identity.user = current_user

        @login_manager.user_loader
        def load_user(user_id):
            try:
                return datastore.with_id(user_id)
            except Exception, e:
                logger.error('Error getting user: %s' % e)
                return None
Пример #7
0
    def initialise(self):
        """
        The application needs initialisation to load the database
        connection etc. In previous versions this was done with the
        initialisation of the class in the __init__ method. This is
        now separated into this function.
        """
        #: Check if the secret key is defined, if not raise an
        #: exception since it is required
        assert self.secret_key, 'Secret Key is not defined in config'

        #: Load the cache
        self.load_cache()

        #: Initialise the CSRF handling
        self.csrf_protection = NereidCsrfProtect()
        self.csrf_protection.init_app(self)

        self.view_functions['static'] = self.send_static_file

        # Backend initialisation
        self.load_backend()

        #: Initialise the login handler
        login_manager = LoginManager()
        login_manager.user_loader(self._pool.get('nereid.user').load_user)
        login_manager.header_loader(
            self._pool.get('nereid.user').load_user_from_header)
        login_manager.token_loader(
            self._pool.get('nereid.user').load_user_from_token)
        login_manager.unauthorized_handler(
            self._pool.get('nereid.user').unauthorized_handler)
        login_manager.login_view = "nereid.website.login"
        login_manager.anonymous_user = self._pool.get('nereid.user.anonymous')
        login_manager.init_app(self)

        self.login_manager = login_manager

        # Monkey patch the url_for method from flask-login to use
        # the nereid specific url_for
        flask.ext.login.url_for = url_for

        self.template_context_processors[None].append(
            self.get_context_processors())

        # Add the additional template context processors
        self.template_context_processors[None].append(
            nereid_default_template_ctx_processor)

        # Add template_filters registered using decorator
        for name, function in self.get_template_filters():
            self.jinja_env.filters[name] = function

        # Initialize Babel
        Babel(self)

        # Finally set the initialised attribute
        self.initialised = True
Пример #8
0
    def init_app(self, app, datastore):
        """Initializes the Flask-Security extension for the specified
        application and datastore implentation.

        :param app: The application.
        :param datastore: An instance of a user datastore.
        """
        if app is None or datastore is None:
            return

        # TODO: change blueprint name
        blueprint = Blueprint('auth', __name__)

        configured = {}

        for key, value in default_config.items():
            configured[key] = app.config.get(key, value)

        app.config.update(configured)
        config = app.config

        # setup the login manager extension
        login_manager = LoginManager()
        login_manager.anonymous_user = AnonymousUser
        login_manager.login_view = config[LOGIN_VIEW_KEY]
        login_manager.setup_app(app)
        app.login_manager = login_manager

        Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
        Form = get_class_from_config(LOGIN_FORM_KEY, config)
        pw_hash = config[PASSWORD_HASH_KEY]

        app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
        app.auth_provider = Provider(Form)
        app.principal = Principal(app)

        from flask.ext import security as s
        s.User, s.Role = datastore.get_models()

        setattr(app, config[USER_DATASTORE_KEY], datastore)

        @identity_loaded.connect_via(app)
        def on_identity_loaded(sender, identity):
            if hasattr(current_user, 'id'):
                identity.provides.add(UserNeed(current_user.id))

            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

            identity.user = current_user

        @login_manager.user_loader
        def load_user(user_id):
            try:
                return datastore.with_id(user_id)
            except Exception, e:
                logger.error('Error getting user: %s' % e)
                return None
def get_login_manager(app):
    lm = LoginManager(app)
    lm.session_protection = 'strong'
    lm.anonymous_user = AnonymousUser
    lm.login_view = '/login'
    lm.user_loader(load_user)
    lm.token_loader(load_token)
    lm.init_app(app)
    return lm
Пример #10
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)
    lm.login_message, lm.login_message_category = cv('MSG_LOGIN', app=app)
    lm.needs_refresh_message, lm.needs_refresh_message_category = cv('MSG_REFRESH', app=app)
    lm.init_app(app)
    return lm
Пример #11
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.login_message = None
    lm.needs_refresh_message = None
    lm.unauthorized_callback = lambda: abort(401)
    lm.init_app(app)
    return lm
Пример #12
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)
    lm.login_message, lm.login_message_category = cv('MSG_LOGIN', app=app)
    lm.needs_refresh_message, lm.needs_refresh_message_category = cv(
        'MSG_REFRESH', app=app)
    lm.init_app(app)
    return lm
Пример #13
0
def setup_login_manager(app):
    """
    Configure the LoginManager for the provided app.
    """
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login_user'
    login_manager.login_message = 'Resource access not authorized.'
    login_manager.login_message_category = 'error'
    login_manager.anonymous_user = AnonymousUser
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    user_logged_in.connect(on_login, app)
Пример #14
0
def init(app):
    security = Security(app, user_datastore)
    security._state.principal._is_static_route = is_static_route
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous

    @login_manager.user_loader
    def load_user(user_id):
        try:
            return user_datastore.get_user(int(user_id))
        except Exception:
            current_app.logger.exception('Erorr')
            return Anonymous()
Пример #15
0
def init(app):
    security = Security(app, user_datastore)
    security._state.principal._is_static_route = is_static_route
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous

    @login_manager.user_loader
    def load_user(user_id):
        try:
            return user_datastore.get_user(int(user_id))
        except Exception:
            current_app.logger.exception('Erorr')
            return Anonymous()
Пример #16
0
    def init_app(self, app):        
        if app is None: return
        
        blueprint = Blueprint(AUTH_CONFIG_KEY.lower(), __name__)
        
        config = default_config.copy()
        try: config.update(app.config.get(AUTH_CONFIG_KEY, {}))
        except: pass
        app.config[AUTH_CONFIG_KEY] = config
        
        app.logger.debug("Auth Configuration: %s" % config)
        
        # setup the login manager extension
        login_manager = LoginManager()
        login_manager.anonymous_user = Anonymous
        login_manager.login_view = config[LOGIN_VIEW_KEY]
        login_manager.setup_app(app)
            
        # get some things form the config
        Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
        Encryptor = get_class_from_config(PASSWORD_ENCRYPTOR_KEY, config)
        Form = get_class_from_config(LOGIN_FORM_CLASS_KEY, config)
        
        # create the service and auth provider and add it to the app
        # so it can be referenced elsewhere
        app.login_manager = login_manager
        app.password_encryptor = Encryptor(config[SALT_KEY])
        app.auth_provider = Provider(Form)
        
        DEBUG_LOGIN = '******'
        DEBUG_XHR_LOGIN = '******'
        ERROR_LOGIN = '******'
        DEBUG_LOGOUT = 'User logged out, redirecting to: %s'
        FLASH_INACTIVE = 'Inactive user'
        
        @login_manager.user_loader
        def load_user(id):
            try: 
                user = user_service.get_user_with_id(id)
                # check if the password matches encryptor pattern
                if not current_app.password_encryptor.matches_encryption_pattern(user.password):
                    encrypted_password = current_app.password_encryptor.encrypt(user.password)
                    user.password = encrypted_password
                    user.save()

                return user
            except Exception, e:
                current_app.logger.error('Error getting user: %s' % e) 
                return None
Пример #17
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = "%s.login" % cv("BLUEPRINT_NAME", app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)

    if cv("FLASH_MESSAGES", app=app):
        lm.login_message, lm.login_message_category = cv("MSG_LOGIN", app=app)
        lm.needs_refresh_message, lm.needs_refresh_message_category = cv("MSG_REFRESH", app=app)
    else:
        lm.login_message = None
        lm.needs_refresh_message = None

    lm.init_app(app)
    return lm
Пример #18
0
def init_login(app):
    login_manager = LoginManager()

    login_manager.login_view = "user.login"
    login_manager.logout_view = 'user.logout'
    login_manager.login_message = u"Please log in to access this page."
    login_manager.refresh_view = "user.reauth"
    login_manager.anonymous_user = Anonymous

    login_manager.setup_app(app)
    
    
    @login_manager.user_loader
    def load_user(id):
        from user.models import User
        from common import db
        return db.session.query(User).filter(User.id==id).first()
Пример #19
0
def setup_app(app):
    """Setup login extension."""
    app.config.setdefault("CFG_OPENID_AUTHENTICATION", False)
    app.config.setdefault("CFG_OAUTH1_AUTHENTICATION", False)
    app.config.setdefault("CFG_OAUTH2_AUTHENTICATION", False)

    @app.errorhandler(401)
    def do_login_first(error=401):
        """Display login page when user is not authorised."""
        if request.is_xhr:
            return g._("Authorization failure"), 401
        secure_url = url_for(request.endpoint, _external=True, _scheme="https", **request.view_args)
        if not urllib.unquote(secure_url).startswith(request.base_url):
            return redirect(secure_url)
        if current_user.is_guest:
            flash(g._("Please sign in to continue."), "info")
            from invenio.modules.accounts.views.accounts import login

            return login(referer=request.url), 401
        else:
            flash(g._("Authorization failure."), "danger")
            from flask import render_template

            return render_template("401.html"), 401

    # Let's create login manager.
    _login_manager = LoginManager(app)
    _login_manager.login_view = app.config.get("CFG_LOGIN_VIEW", "webaccount.login")
    _login_manager.anonymous_user = UserInfo
    _login_manager.unauthorized_handler(do_login_first)

    @user_logged_in.connect_via(app)
    def _logged_in(sender, user):
        """Update last login date."""
        from invenio.modules.accounts.models import User

        User.query.filter_by(id=user.get_id()).update(dict(last_login=datetime.now()))

    @_login_manager.user_loader
    def _load_user(uid):
        """Do not raise an exception if uid is not valid or missing."""
        return UserInfo(int(uid))

    return app
Пример #20
0
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
Пример #21
0
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
Пример #22
0
def init_app(app):
    """ Configure middleware for the application. """

    principal = Principal(app)
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = 'users.login'
    login_manager.anonymous_user = Guest

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        user = user_from_id(identity._id) 
        identity.provides.add(RoleNeed(user.access_level))
        identity.user = user
        g.user = user

    @login_manager.user_loader
    def load_user(uid):
        return user_from_id(uid)


    db.register(User)
Пример #23
0
class OhmAnonymousUserMixin(AnonymousUserMixin):
    def __init__(self):
        super(OhmAnonymousUserMixin, self).__init__()
        self.user = None

    def short_name(self):
        return None

    def full_name(self):
        return None

    def hash(self):
        return None


login_manager.anonymous_user = OhmAnonymousUserMixin


def checkMobile(request):
    mobileQry = ''
    if hasattr(request, 'MOBILE') and request.MOBILE:
        mobileQry = "mobile/"

    return mobileQry


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

Пример #24
0
app = Flask(__name__)
app.jinja_env.filters['firstparagraph'] = firstparagraph
app.jinja_env.filters['remainingparagraphs'] = remainingparagraphs
app.secret_key = _cfg("secret-key")
app.jinja_env.cache = None
app.json_encoder = CustomJSONEncoder
markdown = Markdown(app, safe_mode='remove', extensions=[KerbDown()])
init_db()
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(username):
    return User.query.filter(User.username == username).first()

login_manager.anonymous_user = lambda: None

app.register_blueprint(profiles)
app.register_blueprint(accounts)
app.register_blueprint(anonymous)
app.register_blueprint(blog)
app.register_blueprint(admin)
app.register_blueprint(mods)
app.register_blueprint(api)

try:
    locale.setlocale(locale.LC_ALL, 'en_US')
except:
    try:
        locale.setlocale(locale.LC_ALL, 'en')
    except:
Пример #25
0
# this allows the handler to adhere to rate limit of reddit API
# see r and bot below to enable in production.

handler = MultiprocessHandler()

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_message = None
mail = Mail(app)
Bootstrap(app)
lm.login_view = 'login'
migrate = Migrate(app, db)

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler(app.config['LOGFILE'], maxBytes = 1024*1024)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

bot = praw.Reddit(app.config['REDDIT_USER_AGENT'], handler=handler)
#bot.login(app.config['REDDIT_USERNAME'], app.config['REDDIT_PASSWORD'])

from cbbpoll import views, models, admin
lm.anonymous_user = models.AnonymousUser
app.jinja_env.globals['timestamp'] = views.timestamp

Пример #26
0
		return True
	def get_id(self):
		return None



app = Flask(__name__)

import sys
if "debug" in sys.argv:
	print("Flask running in debug mode!")
	app.debug = True
app.config.from_object('config.BaseConfig')

lm = LoginManager()
lm.anonymous_user = AnonUser
lm.init_app(app)
lm.login_view = 'login'
lm.login_message = lazy_gettext('Please log in to access this page.')

babel = Babel(app)
CsrfProtect(app)

if "debug" in sys.argv:
	print("Installing debug toolbar!")
	toolbar = DebugToolbarExtension(app)

if not app.debug:
	import logging
	from logging.handlers import RotatingFileHandler
	file_handler = RotatingFileHandler('tmp/ReadableWebProxy.log', 'a', 1 * 1024 * 1024, 10)
Пример #27
0
# TODO update this url, needed for the user login token
base_url = "http://www.l-functions.org"
# TODO: Not sure this should be changed from l-functions -> lmfdb, because
# I don't really understand how this is used. Paul


@login_manager.user_loader
def load_user(userid):
    from pwdmanager import LmfdbUser
    return LmfdbUser(userid)


login_manager.login_view = "users.info"

# this anonymous user has the is_admin() method
login_manager.anonymous_user = LmfdbAnonymousUser


def get_username(uid):
    """returns the name of user @uid"""
    return LmfdbUser(uid).name


# globally define user properties and username


@app.context_processor
def ctx_proc_userdata():
    userdata = {}
    userdata['username'] = '******' if current_user.is_anonymous(
    ) else current_user.name
Пример #28
0
app.config.update(config)

# Log to stdout:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)

# Setup Bcrypt
bcrypt = Bcrypt(app)

# Setup Flask-login:
from library.models.member import AnonymousMember, Member
from library.models import Session

login_manager = LoginManager()
login_manager.anonymous_user = AnonymousMember
login_manager.init_app(app)

@login_manager.user_loader
def load_user(member_id):
    """
    Gets the member for Flask-Login.
    """
    return Member.get(member_id)

# Tell jinja to clean whitespace:
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

# Setup teardown.
@app.teardown_appcontext
Пример #29
0
app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)


class UserAnonymous(AnonymousUserMixin):
    id = None

    def is_admin(self):
        return False

lm = LoginManager()
lm.init_app(app)
lm.anonymous_user = UserAnonymous
lm.login_view = 'user_login'


@lm.user_loader
def load_user(user_id):
    from app.models import User
    return User.query.get(int(user_id))


@app.template_filter('datetime')
def format_datetime(value, format='%d.%m.%Y %H:%M'):
    return datetime.strftime(value, format)


@app.template_filter('timedelta')
Пример #30
0
login_manager = LoginManager()
login_manager.init_app(application)
login_manager.login_view = 'user.sign_in'

# Set up the database.
db = SQLAlchemy(application)
db.Model.to_dict = model_to_dict

from viaduct.api.user import UserAPI
from viaduct.api.group import GroupPermissionAPI

# Set jinja global variables
application.jinja_env.globals.update(enumerate=enumerate)
application.jinja_env.globals.update(render_template=render_template)
application.jinja_env.globals.update(markdown=markdown)
application.jinja_env.globals.update(Markup=Markup)
application.jinja_env.globals.update(UserAPI=UserAPI)
application.jinja_env.globals.update(GroupPermissionAPI=GroupPermissionAPI)
application.jinja_env.globals.update(datetime=datetime)

# Register the blueprints.
import api  # noqa

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

register_views(application, os.path.join(path, 'views'))

from viaduct.models import User

login_manager.anonymous_user = User.get_anonymous_user
Пример #31
0
from flask.ext.login import AnonymousUserMixin, LoginManager

from flask_tracking.users.models import User

login_manager = LoginManager()


class AnonymousUser(AnonymousUserMixin):
    id = None


login_manager.anonymous_user = AnonymousUser
login_manager.login_view = "users.login"
# We have not created the users.login view yet
# but that is the name that we will use for our
# login view, so we will set it now.


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)
Пример #32
0
Файл: pgpy.py Проект: 9R/pgpy
UPLOADS_DEFAULT_DEST = 'static/'

#DEBUG=True
#SESSION_COOKIE_SECURE = True

sitename = config.py['sitename']

#### application

app = Flask(__name__)
app.config.from_object(__name__)

#### login

login_manager = LoginManager()
login_manager.anonymous_user= libpgpy.Anonymous
login_manager.login_view = "login"
login_manager.login_message = u"Please log"
login_manager.refresh_view = "reauth"
login_manager.setup_app(app)

#### uploads

media = UploadSet('media', IMAGES + ('mp4',) )
configure_uploads(app, media )

#### utils

@login_manager.user_loader
def load_user(id):
  return USERS.get(int(id))
Пример #33
0
from flask import current_app, redirect, url_for
from flask.ext.login import LoginManager
from flask.ext.oauthlib.client import OAuth
import formencode_jinja2
import sqlalchemy.orm
from flask import json

import midauth.models.user
from midauth.utils import importlib
from . import defaults
from . import dispatch
from .ext import OAuth2Provider


login_manager = LoginManager()
login_manager.anonymous_user = midauth.models.user.AnonymousUser

current_user = flask.ext.login.current_user

oauth2 = OAuth2Provider()
oauth_client = OAuth()


def create_app(config):
    app = flask.Flask('midauth.web')
    app.config.from_object(defaults)
    if isinstance(config, collections.Mapping):
        app.config.update(config)
    else:
        app.config.from_pyfile(config)
    login_manager.init_app(app)
Пример #34
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, AnonymousUserMixin
from flask.ext.mobility import Mobility
from flask_sslify import SSLify
import os

app = Flask(__name__)
app.secret_key = 'L1t3raLl4bV13w' #USER MUST REPLACE THIS
app.config['COMMUNICATION_KEY'] = '804e33bcd2dfc0cb435fe64ce20646fe' #MUST BE SAME AS CLIENT's config.xml
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/llw.db'
app.config['UPLOADS_FOLDER'] = os.path.join(os.getcwd(),'uploads')

db = SQLAlchemy(app)

sslify = SSLify(app)

Mobility(app)

lm = LoginManager()
lm.login_view = "login"
lm.login_message = u"Please log in to access this page."
AnonymousUserMixin.name = u'Anonymous'
lm.anonymous_user = AnonymousUserMixin
lm.setup_app(app)
Пример #35
0
from flask.ext.pymongo import PyMongo
from sqlalchemy import desc
import models
import form_class
import redis
import cve_redis
import json
import cgi
import syslog
import logging
from bson import json_util

#Login_manager (session)
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.anonymous_user = models.AnonymousUser

# Parsing Conf File #
configfile = 'config/config.cfg'
cfg = ConfigParser.ConfigParser()
cfg.read(configfile)

########################################################################
####################### APP INIT & CONFIG ##############################
########################################################################
app = Flask(__name__)

manager = Manager(app)
mail = Mail(app)
login_manager.init_app(app)
bootstrap = Bootstrap(app)
Пример #36
0
    "DB": urlparse(MONGO_URL).path[1:],
    "host": MONGO_URL}

# MongoEngine DB
db = MongoEngine(app)

admin.config = app.config
app.register_blueprint(admin.mod)

webhook.config = app.config
app.register_blueprint(webhook.mod)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "admin.index"
login_manager.anonymous_user = tools.AnonymousUser

@login_manager.user_loader
def load_user(userid):
    try:
        return User.objects.get(id=userid)
    except AutoReconnect:
        flash("Cannot connect to DB.... sorry.")
    except User.DoesNotExist:
        flash("This user account no longer exists.")

    return AnonymousUser()

if not app.debug:
    @app.errorhandler(Exception)
    def catch_all(exception):
Пример #37
0
UPLOADS_DEFAULT_DEST = 'static/'

#DEBUG=True
#SESSION_COOKIE_SECURE = True

sitename = config.py['sitename']

#### application

app = Flask(__name__)
app.config.from_object(__name__)

#### login

login_manager = LoginManager()
login_manager.anonymous_user = libpgpy.Anonymous
login_manager.login_view = "login"
login_manager.login_message = u"Please log"
login_manager.refresh_view = "reauth"
login_manager.setup_app(app)

#### uploads

media = UploadSet('media', IMAGES + ('mp4', ))
configure_uploads(app, media)

#### utils


@login_manager.user_loader
def load_user(id):
Пример #38
0
        self.load()


class Group(Model):
    api_endpoint = '/2/groups/?group_id=%(_id)s'
    api_identifier = '_id'
    field_mapping = {'id': '_id'}
    collection = 'groups'


class Guest(AnonymousUser):
    # define name to be compatible with :class:`User`
    name = 'Guest'


login_manager.anonymous_user = Guest


class Venue(Model):
    field_mapping = {'id': '_id'}
    collection = 'venues'
    dont_save_fields = ['distance']
    name = ''

    def __unicode__(self):
        return self.name

    def claim(self, user_id, **fields):
        """Mark a venue as claimed, adding any additional information as well.

        In order to claim the venue, the `user_id` must be provided. All other
Пример #39
0
    app.config.from_pyfile('../config.py')
    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app


app.config.from_pyfile('../config.py')
db.init_app(app)

from .models import *

migrate = Migrate(app, db)

login_manager.init_app(app)
login_manager.anonymous_user = AnonymousUser

manager = Manager(app)

manager.add_command('db', MigrateCommand)


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


@app.errorhandler(401)
def unauthorized(error):
    return redirect(url_for('account.login'))
Пример #40
0
# TODO update this url, needed for the user login token
base_url = "http://www.l-functions.org"
# TODO: Not sure this should be changed from l-functions -> lmfdb, because
# I don't really understand how this is used. Paul


@login_manager.user_loader
def load_user(userid):
    from pwdmanager import LmfdbUser
    return LmfdbUser(userid)

login_manager.login_view = "users.info"

# this anonymous user has the is_admin() method
login_manager.anonymous_user = LmfdbAnonymousUser


def get_username(uid):
    """returns the name of user @uid"""
    return LmfdbUser(uid).name

# globally define user properties and username


@app.context_processor
def ctx_proc_userdata():
    userdata = {}
    userdata['userid'] = 'anon' if current_user.is_anonymous() else current_user._uid
    userdata['username'] = '******' if current_user.is_anonymous() else current_user.name
    userdata['user_is_authenticated'] = current_user.is_authenticated()
Пример #41
0
	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 preemptiveCache
		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(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)

		# start the intermediary server
		self._start_intermediary_server(s)

		# 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)
		preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))

		# ... and initialize all plugins

		def octoprint_plugin_inject_factory(name, implementation):
			"""Factory for injections for all OctoPrintPlugins"""

			if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
				# we only care about OctoPrintPlugins
				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),
				preemptive_cache=preemptiveCache
			)

		def settings_plugin_inject_factory(name, implementation):
			"""Factory for additional injections depending on plugin type"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				# we only care about SettingsPlugins
				return None

			# SettingsPlugin instnances get a PluginSettings instance injected
			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_and_cleanup(name, implementation):
			"""Take care of migrating and cleaning up any old settings"""

			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([octoprint.plugin.SettingsPlugin.config_version_key])
				if stored_version is None or stored_version < settings_version:
					settings_migrator(settings_version, stored_version)
					implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)

			implementation.on_settings_cleanup()
			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_and_cleanup(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_and_cleanup]

		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()

		# make sure plugin lifecycle events relevant for jinja2 are taken care of
		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.configure_timelapse()

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

		# setup access control
		userManagerName = s.get(["accessControl", "userManager"])
		try:
			clazz = octoprint.util.get_class(userManagerName)
			userManager = clazz()
		except AttributeError as e:
			self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
			userManager = octoprint.users.FilebasedUserManager()
		finally:
			userManager.enabled = s.getBoolean(["accessControl", "enabled"])

		loginManager = LoginManager()
		loginManager.session_protection = "strong"
		loginManager.user_callback = load_user
		if not userManager.enabled:
			loginManager.anonymous_user = users.DummyUser
			principals.identity_loaders.appendleft(users.dummy_identity_loader)
		loginManager.init_app(app)

		# register API blueprint
		self._setup_blueprints()

		## Tornado initialization starts here

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

		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"]))

		def mime_type_guesser(path):
			from octoprint.filemanager import get_mime_type
			return get_mime_type(path)

		download_handler_kwargs = dict(
			as_attachment=True,
			allow_client_caching=False
		)
		additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
		admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
		no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))

		def joined_dict(*dicts):
			if not len(dicts):
				return dict()

			joined = dict()
			for d in dicts:
				joined.update(d)
			return joined

		server_routes = self._router.urls + [
			# various downloads
			(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
			(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
			(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
			# camera snapshot
			(r"/downloads/camera/current", util.tornado.UrlProxyHandler, 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"))),
			# online indicators - text file with "online" as content and a transparent gif
			(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
			(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
		]

		# fetch additional routes from plugins
		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._stop_intermediary_server()

		# initialize and bind the server
		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)

		# auto connect
		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)

				# when we are through with that we also run our preemptive cache
				if settings().getBoolean(["devel", "cache", "preemptive"]):
					self._execute_preemptive_flask_caching(preemptiveCache)

			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")

			if self._octoprint_daemon is not None:
				self._logger.info("Cleaning up daemon pidfile")
				self._octoprint_daemon.terminated()

			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:")
Пример #42
0
    def run(self):
        if not self._allowRoot:
            self._checkForRoot()
        global gcodeManager
        global userManager
        global eventManager
        global loginManager
        global debug

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

        debug = self._debug

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

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

        # configure timelapse
        octoprint.timelapse.configureTimelapse()

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

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

        app.wsgi_app = ReverseProxied(app.wsgi_app)

        app.secret_key = settings.get('server', 'secret_key')
        if not app.secret_key:
            raise NoSecretKeyError()
        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.get("server", "port")

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

        from octoprint.server.ajax import ajax
        from octoprint.server.api import api

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

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

        self._tornado_app = Application(self._router.urls + [
            (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {
             "path": settings.getpath("timelapse"), "as_attachment": True}),
            (r"/downloads/gcode/([^/]*\.(gco|gcode))", LargeResponseHandler, {
                "path": settings.getpath("uploads"), "as_attachment": True}),
            (r".*", FallbackHandler,
             {"fallback": WSGIContainer(app.wsgi_app)})
        ])
        self._server = HTTPServer(self._tornado_app)
        self._server.listen(self._port, address=self._host)

        eventManager.fire("Startup")
        if settings.get("serial", "autoconnect"):
            port, baudrate = (settings.get('serial', e) 
                              for e in ('port', 'baudrate'))
            connectionOptions = getConnectionOptions()
            if port in connectionOptions["ports"]:
                self.printer.connect(port, baudrate)
        try:
            IOLoop.instance().start()
        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:")
Пример #43
0
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Morse.  If not, see <http://www.gnu.org/licenses/>.

from . import app
from flask import render_template, request, redirect, url_for
from flask.ext.login import LoginManager, login_user, logout_user
from ..models.core import User, Guest

# Integration into flask login extension
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.anonymous_user = Guest

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

@app.route('/account/login',methods=['GET','POST'])
def login():
    """ 
    Renders the login view on GET / logs a user in on POST
    :rtype: html
    """
    if request.method == 'GET':
        return render_template('account/login.html')

    username = request.form['username']
Пример #44
0
from views.user import user_blueprint

########################################################################
####################### APP INIT & CONFIG ##############################
########################################################################

app = Flask(__name__)

app.register_blueprint(main_blueprint)
app.register_blueprint(notif_blueprint, url_prefix='/notif')
app.register_blueprint(user_blueprint, url_prefix='/user')

# Login_manager (session)
login_manager = LoginManager(app)
login_manager.session_protection = 'strong'
login_manager.anonymous_user = models.AnonymousUser

mail.init_app(app)
manager = Manager(app)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = cfg.get("Secret", "wtf_secret_key")

# app.config['SERVER_NAME'] = "www.circl.lu:443"
# app.config['APPLICATION_ROOT'] = '/cve-portal'
# app.config['WTF_CSRF_ENABLED'] = True

# SMTP email config #
app.config['MAIL_SERVER'] = cfg.get('SMTP', 'server')
app.config['MAIL_PORT'] = cfg.get('SMTP', 'port')
app.config['MAIL_USE_TLS'] = cfg.get('SMTP', 'tls')
app.config['DEFAULT_MAIL_SENDER'] = cfg.get('SMTP', 'sender')
Пример #45
0
# Initialize Admin module
admin = Admin(app)

# Initialize Login Module


class Anonymous(AnonymousUser):
    name = u"Anonymous"

    def is_authenticated(user):
        return False


lm = LoginManager()
lm.anonymous_user = Anonymous
lm.init_app(app)
lm.login_view = 'login'

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('/var/www/technights/technights.log',
                                       'a', 1 * 1024 * 1024, 10)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        ))
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
Пример #46
0
	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 preemptiveCache
		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(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 BEEweb %s" % DISPLAY_VERSION)

		# start the intermediary server
		self._start_intermediary_server(s)

		# 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 = BeePrinter(fileManager, analysisQueue, printerProfileManager)
		appSessionManager = util.flask.AppSessionManager()
		pluginLifecycleManager = LifecycleManager(pluginManager)
		preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))

		# ... and initialize all plugins

		def octoprint_plugin_inject_factory(name, implementation):
			"""Factory for injections for all OctoPrintPlugins"""

			if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
				# we only care about OctoPrintPlugins
				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),
				preemptive_cache=preemptiveCache
			)

		def settings_plugin_inject_factory(name, implementation):
			"""Factory for additional injections depending on plugin type"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				# we only care about SettingsPlugins
				return None

			# SettingsPlugin instnances get a PluginSettings instance injected
			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_and_cleanup(name, implementation):
			"""Take care of migrating and cleaning up any old settings"""

			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([octoprint.plugin.SettingsPlugin.config_version_key])
				if stored_version is None or stored_version < settings_version:
					settings_migrator(settings_version, stored_version)
					implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)

			implementation.on_settings_cleanup()
			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_and_cleanup(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_and_cleanup]

		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()

		# make sure plugin lifecycle events relevant for jinja2 are taken care of
		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.configure_timelapse()

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

		# setup access control
		userManagerName = s.get(["accessControl", "userManager"])
		try:
			clazz = octoprint.util.get_class(userManagerName)
			userManager = clazz()
		except AttributeError as e:
			self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
			userManager = octoprint.users.FilebasedUserManager()
		finally:
			userManager.enabled = s.getBoolean(["accessControl", "enabled"])

		loginManager = LoginManager()
		loginManager.session_protection = "strong"
		loginManager.user_callback = load_user
		if not userManager.enabled:
			loginManager.anonymous_user = users.DummyUser
			principals.identity_loaders.appendleft(users.dummy_identity_loader)
		loginManager.init_app(app)

		# register API blueprint
		self._setup_blueprints()

		## Tornado initialization starts here

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

		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"]))

		def mime_type_guesser(path):
			from octoprint.filemanager import get_mime_type
			return get_mime_type(path)

		download_handler_kwargs = dict(
			as_attachment=True,
			allow_client_caching=False
		)
		additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
		admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
		no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))

		def joined_dict(*dicts):
			if not len(dicts):
				return dict()

			joined = dict()
			for d in dicts:
				joined.update(d)
			return joined

		server_routes = self._router.urls + [
			# various downloads
			(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
			(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
			(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
			# camera snapshot
			(r"/downloads/camera/current", util.tornado.UrlProxyHandler, 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"))),
			# online indicators - text file with "online" as content and a transparent gif
			(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
			(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif")),
			(r"/stl/([^/]*\.stl)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("stls")))),
			(r"/firmware/([^/]*\.BIN)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("firmware"))))
		]

		# fetch additional routes from plugins
		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._stop_intermediary_server()

		# initialize and bind the server
		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)

		# auto connect
		#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")

		if s.getBoolean(["usb", "autoconnect"]):
			printer_profile = printerProfileManager.get_default()
			connectionOptions = get_connection_options()
			printer.connect()


		# 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)

				# when we are through with that we also run our preemptive cache
				if settings().getBoolean(["devel", "cache", "preemptive"]):
					self._execute_preemptive_flask_caching(preemptiveCache)

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

			from octoprint.server.util.connection_util import detect_bvc_printer_connection
			if printer.is_closed_or_error():
				bvc_conn_thread = threading.Thread(target=detect_bvc_printer_connection, args=(printer.connect, ))
				bvc_conn_thread.daemon = True
				bvc_conn_thread.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")

			if self._octoprint_daemon is not None:
				self._logger.info("Cleaning up daemon pidfile")
				self._octoprint_daemon.terminated()

			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:")
Пример #47
0
app.jinja_env.filters['remainingparagraphs'] = remainingparagraphs
app.secret_key = _cfg("secret-key")
app.jinja_env.cache = None
app.json_encoder = CustomJSONEncoder
markdown = Markdown(app, safe_mode='remove', extensions=[KerbDown()])
init_db()
login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def load_user(username):
    return User.query.filter(User.username == username).first()


login_manager.anonymous_user = lambda: None

app.register_blueprint(profiles)
app.register_blueprint(accounts)
app.register_blueprint(anonymous)
app.register_blueprint(blog)
app.register_blueprint(admin)
app.register_blueprint(mods)
app.register_blueprint(api)

locale.setlocale(locale.LC_ALL, 'en_US')

if not app.debug:

    @app.errorhandler(500)
    def handle_500(e):
Пример #48
0
import vutils, webdisproxy, vauth

CP = 'utf-8'

################################################################################

# app setup

app = Flask(__name__)
app.config.from_object('default_settings')
#~ app.config.from_object(__name__) # USERS
log = app.logger

login_manager = LoginManager()
login_manager.anonymous_user = vauth.Anonymous
login_manager.login_view = "login"
login_manager.login_message = u"Для доступа к этой странице вам надо зарегистрироваться."
login_manager.refresh_view = "reauth"
login_manager.session_protection = "strong"


@login_manager.user_loader
def load_user(id):
    return vauth.USERS.get(int(id))


login_manager.setup_app(app)


def updateSession(sender, **extra):