Python flask.current_app._get_current_object() Examples

The following are 30 code examples of flask.current_app._get_current_object(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.current_app , or try the search function .
Example #1
Source File: security_service.py    From flask-unchained with MIT License 6 votes vote down vote up
def change_password(self, user, password, send_email=None):
        """
        Service method to change a user's password.

        Sends signal `password_changed`.

        :param user: The :class:`User`'s password to change.
        :param password: The new password.
        :param send_email: Whether or not to override the config option
                           ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force
                           either sending or not sending an email.
        """
        user.password = password
        self.user_manager.save(user)
        if send_email or (app.config.SECURITY_SEND_PASSWORD_CHANGED_EMAIL
                          and send_email is None):
            self.send_mail(
                _('flask_unchained.bundles.security:email_subject.password_changed_notice'),
                to=user.email,
                template='security/email/password_changed_notice.html',
                user=user)
        password_changed.send(app._get_current_object(), user=user) 
Example #2
Source File: confirmable.py    From flask-security with MIT License 6 votes vote down vote up
def send_confirmation_instructions(user):
    """Sends the confirmation instructions email for the specified user.

    :param user: The user to send the instructions to
    """

    confirmation_link, token = generate_confirmation_link(user)

    send_mail(
        config_value("EMAIL_SUBJECT_CONFIRM"),
        user.email,
        "confirmation_instructions",
        user=user,
        confirmation_link=confirmation_link,
    )

    confirm_instructions_sent.send(app._get_current_object(), user=user, token=token) 
Example #3
Source File: decorators.py    From flask-security with MIT License 6 votes vote down vote up
def _check_token():
    # N.B. this isn't great Flask-Login 0.5.0 made this protected
    # Issue https://github.com/maxcountryman/flask-login/issues/471
    # was filed to restore public access. We want to call this via
    # login_manager in case someone has overridden the login_manager which we
    # allow.
    if hasattr(_security.login_manager, "request_callback"):
        # Pre 0.5.0
        user = _security.login_manager.request_callback(request)
    else:
        user = _security.login_manager._request_callback(request)

    if user and user.is_authenticated:
        app = current_app._get_current_object()
        _request_ctx_stack.top.user = user
        identity_changed.send(app, identity=Identity(user.fs_uniquifier))
        return True

    return False 
Example #4
Source File: views.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def post(self, pid, record, **kwargs):
        """Send a signal to count record view for the record stats."""
        data = request.get_json()
        event_name = data.get("event")
        if event_name == "record-view":
            record_viewed.send(
                current_app._get_current_object(), pid=pid, record=record,
            )
            return self.make_response(pid, record, 202)
        elif event_name == "file-download":
            if "key" not in data:
                abort(406, "File key is required")
            if "bucket_id" not in record:
                abort(406, "Record has no bucket")
            obj = ObjectVersion.get(record["bucket_id"], data["key"])
            file_downloaded.send(
                current_app._get_current_object(), obj=obj, record=record
            )
            return self.make_response(pid, record, 202)
        return StatsError(
            description="Invalid stats event request: {}".format(event_name)
        ) 
Example #5
Source File: __init__.py    From flask-ldap3-login with MIT License 6 votes vote down vote up
def add_server(self, hostname, port, use_ssl, tls_ctx=None, app=None):
        """
        Add an additional server to the server pool and return the
        freshly created server.

        Args:
            hostname (str): Hostname of the server
            port (int): Port of the server
            use_ssl (bool): True if SSL is to be used when connecting.
            tls_ctx (ldap3.Tls): An optional TLS context object to use
                when connecting.
            app (flask.Flask): The app on which to add the server. If not
                given, ``flask.current_app`` is used.

        Returns:
            ldap3.Server: The freshly created server object.
        """
        if app is None:
            app = current_app._get_current_object()
        if not use_ssl and tls_ctx:
            raise ValueError("Cannot specify a TLS context and not use SSL!")
        server = ldap3.Server(hostname, port=port, use_ssl=use_ssl, tls=tls_ctx)
        app.ldap3_login_manager_server_pool.add(server)
        return server 
Example #6
Source File: twofactor.py    From flask-security with MIT License 6 votes vote down vote up
def complete_two_factor_process(
    user, primary_method, totp_secret, is_changing, remember_login=None
):
    """clean session according to process (login or changing two-factor method)
     and perform action accordingly
    """

    _datastore.tf_set(user, primary_method, totp_secret=totp_secret)

    # if we are changing two-factor method
    if is_changing:
        completion_message = "TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL"
        tf_profile_changed.send(
            app._get_current_object(), user=user, method=primary_method
        )
    # if we are logging in for the first time
    else:
        completion_message = "TWO_FACTOR_LOGIN_SUCCESSFUL"
        tf_code_confirmed.send(
            app._get_current_object(), user=user, method=primary_method
        )
        login_user(user, remember=remember_login)
    tf_clean_session()
    return completion_message 
Example #7
Source File: recoverable.py    From flask-security with MIT License 6 votes vote down vote up
def send_reset_password_instructions(user):
    """Sends the reset password instructions email for the specified user.

    :param user: The user to send the instructions to
    """
    token = generate_reset_password_token(user)
    reset_link = url_for_security("reset_password", token=token, _external=True)

    if config_value("SEND_PASSWORD_RESET_EMAIL"):
        send_mail(
            config_value("EMAIL_SUBJECT_PASSWORD_RESET"),
            user.email,
            "reset_instructions",
            user=user,
            reset_link=reset_link,
        )

    reset_password_instructions_sent.send(
        app._get_current_object(), user=user, token=token
    ) 
Example #8
Source File: passwordless.py    From flask-security with MIT License 6 votes vote down vote up
def send_login_instructions(user):
    """Sends the login instructions email for the specified user.

    :param user: The user to send the instructions to
    """
    token = generate_login_token(user)
    login_link = url_for_security("token_login", token=token, _external=True)

    send_mail(
        config_value("EMAIL_SUBJECT_PASSWORDLESS"),
        user.email,
        "login_instructions",
        user=user,
        login_link=login_link,
    )

    login_instructions_sent.send(
        app._get_current_object(), user=user, login_token=token
    ) 
Example #9
Source File: collections.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def export_as_markdown(self, collection):
        data = collection.to_dict()

        export_path = current_app._get_current_object().config['EXPORT_PATH']
        file_name = '{0}-{1}.md'.format(collection.owner, collection.name)
        file_fullname = os.path.join(export_path, file_name)
        template_name = 'misc/export_collection.md'
        content = render_template(template_name, **data)

        with open(file_fullname, 'w') as fs:
            if sys.version_info < (3, 0):
                fs.write(content.encode('utf8'))
            else:
                fs.write(content)

        return send_from_directory(export_path, file_name, as_attachment=True)
        return content 
Example #10
Source File: collections.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def export_as_json(self, collection):
        data = collection.to_dict()
        # print(data, type(data))
        # return jsonify(data)
        export_path = current_app._get_current_object().config['EXPORT_PATH']
        file_name = '{0}-{1}.json'.format(collection.owner, collection.name)
        file_fullname = os.path.join(export_path, file_name)

        if sys.version_info < (3, 0):
            with io.open(file_fullname, 'w', encoding='utf-8') as f:
                # f.write(unicode(json.dumps(post_list, ensure_ascii=False, indent=4)))
                f.write(json.dumps(data, ensure_ascii=False, indent=4))
        else:
            with open(file_fullname, 'w') as fs:
                json.dump(data, fs, ensure_ascii=False, indent=4)

        return send_from_directory(export_path, file_name, as_attachment=True) 
Example #11
Source File: views.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def post(self):
        if request.form.get('login_github'):
            session['oauth_callback_type'] = 'login'
            return github_auth.github_auth()
            # return 'login_github'

        form = forms.LoginForm(obj=request.form)
        if form.validate():
            try:
                user = models.User.objects.get(username=form.username.data)
            except models.User.DoesNotExist:
                user = None

            if user and user.verify_password(form.password.data):
                login_user(user, form.remember_me.data)
                user.last_login = datetime.datetime.now
                user.save()
                identity_changed.send(current_app._get_current_object(), identity=Identity(user.username))
                return redirect(request.args.get('next') or url_for('main.index'))
            flash('Invalid username or password', 'danger')
        return self.get(form=form) 
Example #12
Source File: controllers.py    From sample-platform with ISC License 6 votes vote down vote up
def start_platforms(db, repository, delay=None, platform=None) -> None:
    """
    Start new test on both platforms in parallel.

    We use multiprocessing module which bypasses Python GIL to make use of multiple cores of the processor.
    """
    from run import config, log, app

    with app.app_context():
        from flask import current_app
        if platform is None or platform == TestPlatform.linux:
            linux_kvm_name = config.get('KVM_LINUX_NAME', '')
            log.info('Define process to run Linux VM')
            linux_process = Process(target=kvm_processor, args=(current_app._get_current_object(), db, linux_kvm_name,
                                                                TestPlatform.linux, repository, delay,))
            linux_process.start()
            log.info('Linux VM process kicked off')

        if platform is None or platform == TestPlatform.windows:
            win_kvm_name = config.get('KVM_WINDOWS_NAME', '')
            log.info('Define process to run Windows VM')
            windows_process = Process(target=kvm_processor, args=(current_app._get_current_object(), db, win_kvm_name,
                                                                  TestPlatform.windows, repository, delay,))
            windows_process.start()
            log.info('Windows VM process kicked off') 
Example #13
Source File: cron.py    From sample-platform with ISC License 6 votes vote down vote up
def cron(testing=False):
    """Script to run from cron for Sampleplatform."""
    from mod_ci.controllers import start_platforms, kvm_processor, TestPlatform
    from flask import current_app
    from run import config, log
    from database import create_session
    from github import GitHub

    log.info('Run the cron for kicking off CI platform(s).')
    # Create session
    db = create_session(config['DATABASE_URI'])
    gh = GitHub(access_token=config['GITHUB_TOKEN'])
    repository = gh.repos(config['GITHUB_OWNER'])(config['GITHUB_REPOSITORY'])

    if testing is True:
        kvm_processor(current_app._get_current_object(), db, config.get('KVM_LINUX_NAME', ''), TestPlatform.linux,
                      repository, None)
    else:
        start_platforms(db, repository) 
Example #14
Source File: __init__.py    From planespotter with MIT License 6 votes vote down vote up
def get_app(self, reference_app=None):
        """Helper method that implements the logic to look up an
        application."""

        if reference_app is not None:
            return reference_app

        if current_app:
            return current_app._get_current_object()

        if self.app is not None:
            return self.app

        raise RuntimeError(
            'No application found. Either work inside a view function or push'
            ' an application context. See'
            ' http://flask-sqlalchemy.pocoo.org/contexts/.'
        ) 
Example #15
Source File: security_service.py    From flask-unchained with MIT License 6 votes vote down vote up
def send_reset_password_instructions(self, user):
        """
        Sends the reset password instructions email for the specified user.

        Sends signal `reset_password_instructions_sent`.

        :param user: The user to send the instructions to.
        """
        token = self.security_utils_service.generate_reset_password_token(user)
        reset_link = url_for('security_controller.reset_password',
                             token=token, _external=True)
        self.send_mail(
            _('flask_unchained.bundles.security:email_subject.reset_password_instructions'),
            to=user.email,
            template='security/email/reset_password_instructions.html',
            user=user,
            reset_link=reset_link)
        reset_password_instructions_sent.send(app._get_current_object(),
                                              user=user, token=token) 
Example #16
Source File: security_service.py    From flask-unchained with MIT License 6 votes vote down vote up
def reset_password(self, user, password):
        """
        Service method to reset a user's password. The same as :meth:`change_password`
        except we this method sends a different notification email.

        Sends signal `password_reset`.

        :param user:
        :param password:
        :return:
        """
        user.password = password
        self.user_manager.save(user)
        if app.config.SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL:
            self.send_mail(
                _('flask_unchained.bundles.security:email_subject.password_reset_notice'),
                to=user.email,
                template='security/email/password_reset_notice.html',
                user=user)
        password_reset.send(app._get_current_object(), user=user) 
Example #17
Source File: movie.py    From slack_bot with MIT License 6 votes vote down vote up
def handle(data):
    ret = []

    def timeout_handle():
        return '\n'.join([r[0] for r in ret]), [r[1] for r in ret]

    @timeout(15, default=timeout_handle)
    def _handle(data, app):
        message = data['message']
        if not isinstance(message, unicode):
            message = message.decode('utf-8')
        msg = message.split()
        if len(msg) == 1 or (len(msg) == 2 and u'私聊' in msg[1]):
            city = 'beijing'
        else:
            city = to_pinyin(msg[1])
        if u'将' in message:
            fn = get_later_movie_info
        else:
            fn = get_current_movie_info
        for r in fn(city, app):
            ret.append(r)
        return '\n'.join([r[0] for r in ret]), [r[1] for r in ret]
    app = current_app._get_current_object()
    return _handle(data, app) 
Example #18
Source File: flask_mail.py    From flask-unchained with MIT License 5 votes vote down vote up
def send(self, message, envelope_from=None):
        """Verifies and sends message.

        :param message: Message instance.
        :param envelope_from: Email address to be used in MAIL FROM command.
        """
        if not message.send_to:
            raise ValueError("No recipients have been added")

        if message.sender is None:
            raise ValueError("The message does not specify a sender and a default "
                             "sender has not been configured")

        if message.has_bad_headers():
            raise BadHeaderError

        if message.date is None:
            message.date = time.time()

        ret = None
        if self.host:
            ret = self.host.sendmail(
                sanitize_address(envelope_from or message.sender),
                list(sanitize_addresses(message.send_to)),
                message.as_bytes(),
                message.mail_options,
                message.rcpt_options
            )

        email_dispatched.send(message, app=current_app._get_current_object())

        self.num_emails += 1

        if self.num_emails == self.mail.max_emails:
            self.num_emails = 0
            if self.host:
                self.host.quit()
                self.host = self.configure_host()

        return ret 
Example #19
Source File: case.py    From AutoLink with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('data', type=str)
        self.parser.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files', action='append')
        self.app = current_app._get_current_object() 
Example #20
Source File: suite.py    From AutoLink with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('method', type=str)
        self.parser.add_argument('name', type=str)
        self.parser.add_argument('new_name', type=str)
        self.parser.add_argument('project_name', type=str)
        self.app = current_app._get_current_object() 
Example #21
Source File: login.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def signin():
    json = request.get_json()
    if "username" not in json or "password" not in json:
        raise InvalidUsage("Must supply username or password.")
    user = User.query.filter(User.username == json["username"]).first()
    if user is not None:
        current_app.logger.debug(
            "Login attempt", username=user.username, user_id=user.id
        )
        if user.is_correct_password(json["password"]):
            two_factor = user.two_factor_auth
            if two_factor is not None and two_factor.enabled:
                if "two_factor_code" not in json or json["two_factor_code"] == "":
                    raise InvalidUsage(
                        "Must supply a two-factor authentication code.",
                        payload={"need_two_factor": True},
                    )
                try:
                    two_factor.validate(json["two_factor_code"])
                except (Unauthorized, binascii.Error):
                    two_factor.validate_backup_code(json["two_factor_code"])
            login_user(user, remember=False)
            identity_changed.send(
                current_app._get_current_object(), identity=Identity(user.id)
            )
            session.modified = True
            return jsonify(
                {
                    "logged_in": True,
                    "is_admin": user.is_admin,
                    "require_two_factor_setup": current_user.two_factor_setup_required,
                }
            )
    current_app.logger.debug("Failed login attempt", username=json["username"])
    raise Unauthorized("Incorrect username or password.") 
Example #22
Source File: task.py    From AutoLink with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('method', type=str)
        self.parser.add_argument('name', type=str)
        self.parser.add_argument('cron', type=str)
        self.app = current_app._get_current_object() 
Example #23
Source File: login.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def signout():
    logout_user()
    for key in ("identity.name", "identity.auth_type"):
        session.pop(key, None)
    session.modified = True
    # Tell Flask-Principal the user is anonymous
    identity_changed.send(
        current_app._get_current_object(), identity=AnonymousIdentity()
    )
    return jsonify({"logged_in": False}) 
Example #24
Source File: security_service.py    From flask-unchained with MIT License 5 votes vote down vote up
def confirm_user(self, user):
        """
        Confirms the specified user. Returns False if the user has already been
        confirmed, True otherwise.

        :param user: The user to confirm.
        """
        if user.confirmed_at is not None:
            return False
        user.confirmed_at = self.security.datetime_factory()
        user.active = True
        self.user_manager.save(user)

        user_confirmed.send(app._get_current_object(), user=user)
        return True 
Example #25
Source File: mail.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail(self, sync=False):
        """
        执行发送
        同步/异步(默认)

        :param sync: bool, True 同步发送
        :return:
        """
        if sync:
            mail.send(self)
        else:
            self._async_send(current_app._get_current_object()) 
Example #26
Source File: emails.py    From flask-pycon2014 with MIT License 5 votes vote down vote up
def start_email_thread():
    if not current_app.config['TESTING']:
        global _email_thread
        if _email_thread is None:
            print("Starting email thread...")
            _email_thread = Thread(target=flush_pending,
                                   args=[current_app._get_current_object()])
            _email_thread.start() 
Example #27
Source File: auth.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def logout():
    logout_user()

    # Notify flask principal that the user has logged out
    identity_changed.send(current_app._get_current_object(),
                          identity=AnonymousIdentity())

    return redirect(url_for('index.render_feed')) 
Example #28
Source File: auth_provider.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def _perform_login(self, user):
        user = prepare_user(user)
        login_user(user)

        # Notify flask principal that the identity has changed
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(user.id)) 
Example #29
Source File: models.py    From maple-bbs with GNU General Public License v3.0 5 votes vote down vote up
def login(self, remember=True):
        login_user(self, remember)
        identity_changed.send(
            current_app._get_current_object(), identity=Identity(self.id)) 
Example #30
Source File: __init__.py    From flask-sqlalchemy-session with MIT License 5 votes vote down vote up
def _get_session():
    # pylint: disable=missing-docstring, protected-access
    context = _app_ctx_stack.top
    if context is None:
        raise RuntimeError(
            "Cannot access current_session when outside of an application "
            "context.")
    app = current_app._get_current_object()
    if not hasattr(app, "scoped_session"):
        raise AttributeError(
            "{0} has no 'scoped_session' attribute. You need to initialize it "
            "with a flask_scoped_session.".format(app))
    return app.scoped_session