示例#1
0
def login_handler(response, provider, query):
    """Shared method to handle the signin process"""

    connection = _datastore.find_connection(**query)

    if connection:
        after_this_request(_commit)
        token_pair = get_token_pair_from_oauth_response(provider, response)
        if (token_pair['access_token'] != connection.access_token or
                token_pair['secret'] != connection.secret):
            connection.access_token = token_pair['access_token']
            connection.secret = token_pair['secret']
            _datastore.put(connection)
        user = connection.user
        login_user(user)
        key = _social.post_oauth_login_session_key
        redirect_url = session.pop(key, get_post_login_redirect())

        login_completed.send(current_app._get_current_object(),
                             provider=provider, user=user)

        return redirect(redirect_url)

    login_failed.send(current_app._get_current_object(),
                      provider=provider,
                      oauth_response=response)

    next_url = get_url(_security.login_manager.login_view)
    msg = '%s account not associated with an existing user' % provider.name
    do_flash(msg, 'error')
    return redirect(next_url)
示例#2
0
def connect_handler(cv, provider):
    """Shared method to handle the connection process
    :param connection_values: A dictionary containing the connection values
    :param provider_id: The provider ID the connection shoudl be made to
    """
    cv.setdefault('user_id', current_user.get_id())
    connection = _datastore.find_connection(
        provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id'])

    if connection is None:
        after_this_request(_commit)
        connection = _datastore.create_connection(**cv)
        msg = ('Connection established to %s' % provider.name, 'success')
        connection_created.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                connection=connection)
    else:
        msg = ('A connection is already established with %s '
               'to your account' % provider.name, 'notice')
        connection_failed.send(current_app._get_current_object(),
                               user=current_user._get_current_object())

    next_url = request.form.get('next', get_post_login_redirect())
    redirect_url = (next_url or
                    session.pop(
                        config_value('POST_OAUTH_CONNECT_SESSION_KEY'),
                        get_url(config_value('CONNECT_ALLOW_VIEW'))))

    do_flash(*msg)
    return redirect(redirect_url)
示例#3
0
    def change_password():
        """View function which handles a change password request."""

        has_error = False
        form_class = _security.change_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            try:
                change_user_password(current_user, form.new_password.data)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP Socket error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:
                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(
                        u'Error: {}\n'
                        u'Your password has not been changed.'
                    ).format(e),
                    'danger'
                )
                has_error = True

            if request.json is None and not has_error:
                after_this_request(_commit)
                do_flash(*get_message('PASSWORD_CHANGE'))
                return redirect(get_url(_security.post_change_view) or
                                get_url(_security.post_login_view))

        if request.json and not has_error:
            form.user = current_user
            return _render_json(form)

        return _security.render_template(
            config_value('CHANGE_PASSWORD_TEMPLATE'),
            change_password_form=form,
            **_ctx('change_password'))
    def no_connection(self, profile, provider):
        try:
            connection = self.create_connection(profile, provider)
        except Exception as ex:
            logging.warn(ex, exc_info=True)
            do_flash(_("Could not register: {}").format(ex.message), "warning")
            return self.login_failed_redirect(profile, provider)

        return self.login_connection(connection, profile, provider)
示例#5
0
def delete_question(opportunity_id, question_id):
    question = Question.query.get(question_id)
    if question:
        if not question.opportunity.can_edit(current_user):
            sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED'))
            return redirect('/')
        question.delete()
        flash('Question successfully deleted', 'alert-info')
        return redirect(url_for('beacon_admin.questions', opportunity_id=opportunity_id))
示例#6
0
def token_login(token):
    """View function that handles passwordless login via a token"""

    try:
        user, next = login_by_token(token)
    except PasswordlessLoginError, e:
        if e.user:
            send_login_instructions(e.user, e.next)
        do_flash(str(e), 'error')
        return redirect(request.referrer or url_for('login'))
 def login(self, raw_data, provider):
     logger.debug("raw_data: %s" % raw_data)
     if not raw_data:
         do_flash(_("OAuth authorization failed"), "danger")
         abort(400)
     profile = provider.get_profile(raw_data)
     connection = self.connection_adapter.by_profile(profile)
     if not connection:
         return self.no_connection(profile, provider)
     return self.login_connection(connection, profile, provider)
示例#8
0
def renderFacebook(user):
    json=None
    error=None
    template='/facebook.html'
    if(user.provider!='Facebook'):
         error="Use a Facebook users profile id not "+ user.provider
         do_flash(_(error), "error")
    else:
        token=user.access_token.encode('ascii','ignore')
        json=fbs.getPosts('me', token)
    return render_template(template, data=json, error=error)
示例#9
0
def renderTwitter(user):
    jason=None
    error=None
    template='/twitter.html'
    if(user.provider!='Twitter'):
         error="Use a Twitter users profile id not "+ user.provider
         do_flash(_(error), "error")
    else:
        token=user.access_token.encode('ascii','ignore')
        secret=user.secret.encode('ascii','ignore')
        jason=tw.json_for_twitter(token, secret)
    return render_template(template, data=jason, error=error)
示例#10
0
    def forgot_password():
        """View function that handles a forgotten password request."""
        has_error = False
        form_class = _security.forgot_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            try:
                send_reset_password_instructions(form.user)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP Socket error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:

                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'Error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True

            if request.json is None and not has_error:
                do_flash(*get_message('PASSWORD_RESET_REQUEST',
                                      email=form.user.email))

        if request.json and not has_error:
            return _render_json(form, include_user=False)

        return _security.render_template(
            config_value('FORGOT_PASSWORD_TEMPLATE'),
            forgot_password_form=form,
            **_ctx('forgot_password'))
示例#11
0
def confirm_email(token):
    """View function which handles a email confirmation request."""
    after_this_request(_commit)

    try:
        user = confirm_by_token(token)
    except ConfirmationError, e:
        _logger.debug('Confirmation error: %s' % e)
        if e.user:
            send_confirmation_instructions(e.user)
        do_flash(str(e), 'error')
        confirm_error_url = get_url(_security.confirm_error_view)
        return redirect(confirm_error_url or url_for('send_confirmation'))
示例#12
0
    def login(response):
        _logger.debug('Received login response from '
                      '%s: %s' % (provider.name, response))

        if response is None:
            do_flash('Access was denied to your %s '
                     'account' % provider.name, 'error')
            return _security.login_manager.unauthorized(), None

        query = dict(provider_user_id=module.get_provider_user_id(response),
                     provider_id=provider_id)

        return response, query
示例#13
0
def renderInstagram(user1, user2):
    score=None
    error=None
    template='/instagram.html'
    if(user1.provider!='Instagram' or user2.provider!='Instagram'):
         error="Use  profile ids of Instagram users not %s %s" % (user1.provider , user2.provider )
         do_flash(_(error), "error")
    else:
        token1=user1.access_token.encode('ascii','ignore')
        token2=user2.secret.encode('ascii','ignore')
        # score=insta.similarity(token1, token2)
        score=0.5
    return render_template(template, score=score, error=error)
示例#14
0
def connect_callback(provider_id):
    provider = get_provider_or_404(provider_id)

    def connect(response):
        cv = get_connection_values_from_oauth_response(provider, response)
        return cv

    cv = provider.authorized_handler(connect)()
    if cv is None:
        do_flash('Access was denied by %s' % provider.name, 'error')
        return redirect(get_url(config_value('CONNECT_DENY_VIEW')))

    return connect_handler(cv, provider)
示例#15
0
def forgot_password():
    """View function that handles a forgotten password request."""

    form = ForgotPasswordForm(csrf_enabled=not app.testing)

    if form.validate_on_submit():
        user = _datastore.find_user(**form.to_dict())
        send_reset_password_instructions(user)
        _logger.debug('%s requested to reset their password' % user)
        do_flash(*get_message('PASSWORD_RESET_REQUEST', email=user.email))

    return render_template('security/forgot_password.html',
                           forgot_password_form=form,
                           **_ctx('forgot_password'))
示例#16
0
def questions(opportunity_id):
    opportunity = Opportunity.query.get(opportunity_id)
    if opportunity:
        if not opportunity.can_edit(current_user):
            sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED'))
            return redirect('/')
        answered, unanswered = [], []
        for question in opportunity.questions:
            if question.answer_text:
                answered.append(question)
            else:
                unanswered.append(question)
        return render_template(
            'beacon/admin/questions.html', unanswered=unanswered,
            answered=answered, opportunity=opportunity,
        )
    abort(404)
示例#17
0
def send_login():
    """View function that sends login instructions for passwordless login"""

    form = PasswordlessLoginForm(csrf_enabled=not app.testing)

    if form.validate_on_submit():
        user = _datastore.find_user(**form.to_dict())

        if user.is_active():
            send_login_instructions(user, form.next.data)
            do_flash(*get_message('LOGIN_EMAIL_SENT', email=user.email))
        else:
            form.email.errors.append(get_message('DISABLED_ACCOUNT')[0])

    return render_template('security/send_login.html',
                           login_form=form,
                           **_ctx('send_login'))
示例#18
0
def send_confirmation():
    """View function which sends confirmation instructions."""

    form = SendConfirmationForm(csrf_enabled=not app.testing)

    if form.validate_on_submit():
        user = _datastore.find_user(**form.to_dict())
        if user.confirmed_at is None:
            send_confirmation_instructions(user)
            msg = get_message('CONFIRMATION_REQUEST', email=user.email)
            _logger.debug('%s request confirmation instructions' % user)
        else:
            msg = get_message('ALREADY_CONFIRMED')
        do_flash(*msg)

    return render_template('security/send_confirmation.html',
                           reset_confirmation_form=form,
                           **_ctx('send_confirmation'))
示例#19
0
def answer_question(opportunity_id, question_id):
    question = Question.query.get(question_id)
    if question:
        if not question.opportunity.can_edit(current_user):
            sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED'))
            return redirect('/')
        form = AnswerForm(obj=question)
        if form.validate_on_submit():
            answer = {'answer_text': form.answer_text.data}
            if question.answer_text:
                answer['edited'] = True
                answer['edited_at'] = datetime.datetime.utcnow()
                question.update(**answer)
                flash('Answer successfully edited.')
            else:
                answer['answered_at'] = datetime.datetime.utcnow()
                answer['answered_by'] = current_user
                question.update(**answer)
                flash('This question has been answered! The Vendor has been notified and the question and answer are now public.')

                to_email = set([
                    question.opportunity.created_by.email,
                    question.opportunity.contact.email,
                    question.asked_by.email
                ]).difference(set([current_user.email]))

                Notification(
                    to_email=list(to_email),
                    subject='New answer to a questio on Beacon',
                    html_template='beacon/emails/answered_question.html',
                    question=question
                ).send(multi=True)

            return redirect(
                url_for('beacon_admin.questions', opportunity_id=opportunity_id)
            )

        return render_template(
            'beacon/admin/answer_question.html', form=form,
            question=question, opportunity_id=opportunity_id
        )
    abort(404)
示例#20
0
def remove_all_connections(provider_id):
    """Remove all connections for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name, user=current_user)

    deleted = _datastore.delete_connections(user_id=current_user.get_id(),
                                            provider_id=provider_id)
    if deleted:
        after_this_request(_commit)
        msg = ('All connections to %s removed' % provider.name, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unable to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer)
示例#21
0
def contact():
    form = ContactForm()
    if request.method == 'POST':
        if form.validate_on_submit() == False:
            for field, errors in form.errors.items():
                for error in errors:
                    do_flash(i18n.gettext(error), 'danger')
        else:
            msg = Message(
                form.subject.data,
                sender=current_app.config.get('MAIL_DEFAULT_SENDER'),
                recipients=[current_app.config.get('MAIL_DEFAULT_RECEIVER')])
            msg.body = """
            From: %s <%s>
            %s
            """ % (form.name.data, form.email.data, form.message.data)
            try:
                mail = current_app.extensions.get('mail')
                mail.send(msg)
            except Exception, e:
                do_flash("Server Error : " + str(e), 'danger')
            else:
                do_flash(
                    i18n.gettext(
                        u"Thank you for your message. We'll get back to you shortly."
                    ), 'success')
def reset_password(token):
    """View function that handles a reset password request."""

    expired, invalid, user = reset_password_token_status(token)

    if invalid:
        do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
    if expired:
        do_flash(*get_message('PASSWORD_RESET_EXPIRED',
                              email=user.email,
                              within=config_value('RESET_PASSWORD_WITHIN')))
    if invalid or expired:
        return redirect(url_for('login.forgot_password'))

    form = ResetPasswordForm()

    if form.validate_on_submit():
        update_password(user, form.new_password.data)
        do_flash(*get_message('PASSWORD_RESET'))
        login_user(user)
        return redirect(
            get_url(config_value('POST_RESET_VIEW'))
            or get_url(config_value('POST_LOGIN_VIEW')))

    else:
        current_app.logger.error('Form did not validate: {}'.format(
            form.errors))
        flash(form.errors, 'error')

    return render_template('login/reset_password.html',
                           reset_password_form=form,
                           reset_password_token=token)
示例#23
0
def register_user(**kwargs):
    if kwargs.pop('random_password', False) or len(kwargs['password']) == 0:
        kwargs['password'] = _randompassword()

    # hash password so that we never store the original
    kwargs['password'] = hash_password(kwargs['password'])

    # pop ask_confirm value before kwargs is presented to create_user()
    ask_confirm = kwargs.pop('ask_confirm', False)

    # generate a User record and commit it
    kwargs['active'] = True
    roles = kwargs.get('roles', [])
    roles_step1 = [db.session.query(Role).filter_by(name=r).first() for r in roles]
    roles_step2 = [x for x in roles_step1 if x is not None]
    kwargs['roles'] = roles_step2
    kwargs['fs_uniquifier'] = uuid.uuid4().hex

    user = User(**kwargs)

    db.session.add(user)
    db.session.commit()

    # send confirmation email if we have been asked to
    if ask_confirm:
        confirmation_link, token = generate_confirmation_link(user)
        do_flash(*get_message('CONFIRM_REGISTRATION', email=user.email))

        user_registered.send(current_app._get_current_object(),
                             user=user, confirm_token=token)

        if config_value('SEND_REGISTER_EMAIL'):
            send_mail(config_value('EMAIL_SUBJECT_REGISTER'), user.email,
                      'welcome', user=user, confirmation_link=confirmation_link)

    else:
        user.confirmed_at = datetime.now()
        db.session.commit()

    return user
示例#24
0
    def reset_password(token):
        """View function that handles a reset password request."""
        expired, invalid, user = reset_password_token_status(token)

        if invalid:
            do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
        if expired:
            do_flash(*get_message('PASSWORD_RESET_EXPIRED',
                                  email=user.email,
                                  within=_security.reset_password_within))
        if invalid or expired:
            return redirect(url_for('browser.forgot_password'))
        has_error = False
        form = _security.reset_password_form()

        if form.validate_on_submit():
            try:
                update_password(user, form.password.data)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'SMTP Socket error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:

                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'SMTP error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'Error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True

            if not has_error:
                after_this_request(_commit)
                do_flash(*get_message('PASSWORD_RESET'))
                login_user(user)
                return redirect(
                    get_url(_security.post_reset_view)
                    or get_url(_security.post_login_view))

        return _security.render_template(
            config_value('RESET_PASSWORD_TEMPLATE'),
            reset_password_form=form,
            reset_password_token=token,
            **_ctx('reset_password'))
def confirm_change_email(token):
    """View function which handles a change email confirmation request.
    Based on confirm_email in Flask-Security."""
    expired, invalid, user, new_email = (
        confirm_change_email_token_status(token))

    if not user or invalid:
        invalid = True
        do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
    if expired:
        send_change_email_confirmation_instructions(user, new_email)
        do_flash(*(('You did not confirm your change of email within {0}. '
                    'New instructions to confirm your change of email have '
                    'been sent to {1}.'
                    ).format(_security.confirm_email_within, new_email),
                   'error'))
    if invalid or expired:
        return redirect(url_for('home'))

    if user != current_user:
        logout_user()
        login_user(user)

    if change_user_email(user, new_email):
        after_this_request(_commit)
        msg = ('Thank you. Your change of email has been confirmed.',
               'success')
    else:
        msg = ('Your change of email has already been confirmed.' 'info')

    do_flash(*msg)
    return redirect(url_for('home'))
示例#26
0
def reset_password(token):
    """View function that handles a reset password request."""

    next = None
    form = ResetPasswordForm(csrf_enabled=not app.testing)

    if form.validate_on_submit():
        try:
            user = reset_by_token(token=token, **form.to_dict())
            msg = get_message('PASSWORD_RESET')
            next = (get_url(_security.post_reset_view) or
                    get_url(_security.post_login_view))
        except ResetPasswordError, e:
            msg = (str(e), 'error')
            if e.user:
                send_reset_password_instructions(e.user)
                msg = get_message('PASSWORD_RESET_EXPIRED',
                                  within=_security.reset_password_within,
                                  email=e.user.email)
            _logger.debug('Password reset error: ' + msg[0])

        do_flash(*msg)
示例#27
0
    def reset_password(token):
        """View function that handles a reset password request."""

        expired, invalid, user = reset_password_token_status(token)

        if invalid:
            do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
        if expired:
            do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
                                  within=_security.reset_password_within))
        if invalid or expired:
            return redirect(url_for('browser.forgot_password'))
        has_error = False
        form = _security.reset_password_form()

        if form.validate_on_submit():
            try:
                update_password(user, form.password.data)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP Socket error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:

                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'SMTP error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(u'Error: {}\n'
                              u'Your password has not been changed.'
                              ).format(e),
                      'danger')
                has_error = True

            if not has_error:
                after_this_request(_commit)
                do_flash(*get_message('PASSWORD_RESET'))
                login_user(user)
                return redirect(get_url(_security.post_reset_view) or
                                get_url(_security.post_login_view))

        return _security.render_template(
            config_value('RESET_PASSWORD_TEMPLATE'),
            reset_password_form=form,
            reset_password_token=token,
            **_ctx('reset_password'))
示例#28
0
def faq(section):
    r = get_redis_connection()
    lang_code = g.get('lang_code', current_app.config['DEFAULT_LANGUAGE'])
    lang = lang_code if lang_code == current_app.config[
        'DEFAULT_LANGUAGE'] else 'en'
    try:
        giturl = "https://raw.githubusercontent.com/amagovpt/docs.dados.gov.pt/master/faqs_{0}/{1}.md".format(
            lang, section)
        response = urllib2.urlopen(giturl, timeout=2).read().decode('utf-8')
        content = Markup(markdown.markdown(response))
    except urllib2.URLError:
        cached_page = r.get(section + lang)
        if cached_page:
            response = cached_page.decode('utf-8')
            content = Markup(markdown.markdown(response))
            do_flash("Viewing cached content.", 'info')
            return theme.render('faqs.html',
                                page_name=section,
                                content=content)
        else:
            abort(404)
    else:
        r.set(section + lang, response.encode('utf-8'))
        return theme.render('faqs.html', page_name=section, content=content)
示例#29
0
def remove_connection(provider_id, provider_user_id):
    """Remove a specific connection for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name, user=current_user,
               provider_user_id=provider_user_id)

    deleted = _datastore.delete_connection(user_id=current_user.get_id(),
                                           provider_id=provider_id,
                                           provider_user_id=provider_user_id)

    if deleted:
        after_this_request(_commit)
        msg = ('Connection to %(provider)s removed' % ctx, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unabled to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer or get_post_login_redirect())
示例#30
0
    def change_password():
        """View function which handles a change password request."""

        has_error = False
        form_class = _security.change_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            try:
                change_user_password(current_user, form.new_password.data)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'SMTP Socket error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:
                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'SMTP error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(
                    gettext(u'Error: {}\n'
                            u'Your password has not been changed.').format(e),
                    'danger')
                has_error = True

            if request.json is None and not has_error:
                after_this_request(_commit)
                do_flash(*get_message('PASSWORD_CHANGE'))

                old_key = get_crypt_key()[1]
                set_crypt_key(form.new_password.data, False)

                from pgadmin.browser.server_groups.servers.utils \
                    import reencrpyt_server_passwords
                reencrpyt_server_passwords(current_user.id, old_key,
                                           form.new_password.data)

                return redirect(
                    get_url(_security.post_change_view)
                    or get_url(_security.post_login_view))

        if request.json and not has_error:
            form.user = current_user
            return default_render_json(form)

        return _security.render_template(
            config_value('CHANGE_PASSWORD_TEMPLATE'),
            change_password_form=form,
            **_ctx('change_password'))
示例#31
0
        if user:
            if login_user(user, remember=form.remember.data):
                after_this_request(_commit)
                if request.json:
                    return _json_auth_ok(user)
                return redirect(get_post_login_redirect())
            form.email.errors.append(get_message('DISABLED_ACCOUNT')[0])

        _logger.debug('Unsuccessful authentication attempt: %s' % msg)

        if request.json:
            return _json_auth_error(msg)

        if confirm_url:
            do_flash(msg, 'error')
            return redirect(confirm_url)

    return render_template('security/login.html',
                           login_form=form,
                           **_ctx('login'))


@login_required
def logout():
    """View function which handles a logout request."""

    logout_user()
    _logger.debug('User logged out')
    next_url = request.args.get('next', None)
    post_logout_url = get_url(_security.post_logout_view)
示例#32
0
def idp_initiated():

    user_email = None
    user_nic = None
    first_name = None
    last_name = None

    auth_servers = current_app.config.get('SECURITY_SAML_IDP_METADATA').split(
        ',')

    for server in auth_servers:
        saml_client = saml_client_for(server)
        try:
            authn_response = saml_client.parse_authn_request_response(
                request.form['SAMLResponse'], entity.BINDING_HTTP_POST)
        except sigver.MissingKey:
            continue
        else:
            break

    root = ET.fromstring(str(authn_response))
    ns = {
        'assertion': 'urn:oasis:names:tc:SAML:2.0:assertion',
        'atributos': 'http://autenticacao.cartaodecidadao.pt/atributos'
    }

    for child in root.find('assertion:Assertion',
                           ns).find('assertion:AttributeStatement', ns):
        try:
            if child.attrib[
                    'Name'] == 'http://interop.gov.pt/MDC/Cidadao/CorreioElectronico':
                user_email = child.find('assertion:AttributeValue', ns).text
            elif child.attrib[
                    'Name'] == 'http://interop.gov.pt/MDC/Cidadao/NICCifrado':
                user_nic = child.find('assertion:AttributeValue', ns).text
            elif child.attrib[
                    'Name'] == 'http://interop.gov.pt/MDC/Cidadao/NomeProprio':
                first_name = child.find('assertion:AttributeValue', ns).text
            elif child.attrib[
                    'Name'] == 'http://interop.gov.pt/MDC/Cidadao/NomeApelido':
                last_name = child.find('assertion:AttributeValue', ns).text
            else:
                pass
        except AttributeError:
            pass

    data = {'email': user_email}
    extras = {'extras': {'auth_nic': user_nic}}
    userUdata = datastore.find_user(**extras) or datastore.find_user(**data)

    if not userUdata:
        # Redirects to new custom registration form
        session['user_email'] = user_email
        session['user_nic'] = user_nic
        session['first_name'] = first_name
        session['last_name'] = last_name
        return redirect(url_for('saml.register'))

    elif requires_confirmation(userUdata):
        do_flash(*get_message('CONFIRMATION_REQUIRED'))
        return redirect(url_for('security.login'))

    elif userUdata.deleted:
        do_flash(*get_message('DISABLED_ACCOUNT'))
        return redirect(url_for('site.home'))

    else:
        login_user(userUdata)
        session['saml_login'] = True
        # do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
        return redirect(url_for('site.home'))
示例#33
0
    def forgot_password():
        """View function that handles a forgotten password request."""
        has_error = False
        form_class = _security.forgot_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            # Check the Authentication source of the User
            user = User.query.filter_by(
                email=form.data['email'],
                auth_source=current_app.PGADMIN_DEFAULT_AUTH_SOURCE).first()

            if user is None:
                # If the user is not an internal user, raise the exception
                flash(
                    gettext(
                        'Your account is authenticated using an '
                        'external {} source. '
                        'Please contact the administrators of this '
                        'service if you need to reset your password.').format(
                            form.user.auth_source), 'danger')
                has_error = True
            if not has_error:
                try:
                    send_reset_password_instructions(form.user)
                except SOCKETErrorException as e:
                    # Handle socket errors which are not
                    # covered by SMTPExceptions.
                    logging.exception(str(e), exc_info=True)
                    flash(
                        gettext(
                            u'SMTP Socket error: {}\n'
                            u'Your password has not been changed.').format(e),
                        'danger')
                    has_error = True
                except (SMTPConnectError, SMTPResponseException,
                        SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                        SMTPException, SMTPAuthenticationError,
                        SMTPSenderRefused, SMTPRecipientsRefused) as e:

                    # Handle smtp specific exceptions.
                    logging.exception(str(e), exc_info=True)
                    flash(
                        gettext(
                            u'SMTP error: {}\n'
                            u'Your password has not been changed.').format(e),
                        'danger')
                    has_error = True
                except Exception as e:
                    # Handle other exceptions.
                    logging.exception(str(e), exc_info=True)
                    flash(
                        gettext(
                            u'Error: {}\n'
                            u'Your password has not been changed.').format(e),
                        'danger')
                    has_error = True

            if request.json is None and not has_error:
                do_flash(*get_message('PASSWORD_RESET_REQUEST',
                                      email=form.user.email))

        if request.json and not has_error:
            return default_render_json(form, include_user=False)

        return _security.render_template(
            config_value('FORGOT_PASSWORD_TEMPLATE'),
            forgot_password_form=form,
            **_ctx('forgot_password'))
示例#34
0
 def check_any_role(*roles):
     if CurrentUser.has_any_role_permission(*roles).can():
         return True
     else:
         utils.do_flash(*utils.get_message('UNAUTHORIZED'))
         return False
示例#35
0
                                      request.form.get('new_password'))

            if status:
                password_changed.send(current_app._get_current_object(),
                                      user=current_user._get_current_object())
                do_flash(*get_message('PASSWORD_CHANGE'))
                print "password changed"
                return {"status": True}

        else:
            do_flash(*get_message('RETYPE_PASSWORD_MISMATCH'))
            print "passwords dont match"

    else:
        if request.form.get('new_password'):
            do_flash(*get_message('PASSWORD_NOT_PROVIDED'))
        return {"status": False}


@app.login_manager.request_loader
def load_user_from_request(request):

    if request.method == 'POST' and "/outputs/" not in request.base_url:
        username = request.form.get('email')
        password = request.form.get('password')

        if LOGIN_METHOD != "None":
            try:
                result = User.try_login(username, password)

                if not result:
示例#36
0
def load_user_from_request(request):

    if request.method == 'POST' and "/outputs/" not in request.base_url:
        username = request.form.get('email')
        password = request.form.get('password')

        if LOGIN_METHOD != "None":
            try:
                result = User.try_login(username, password)

                if not result:
                    do_flash(*get_message('INVALID_PASSWORD'))
                    return None

            except ldap.INVALID_CREDENTIALS, e:
                do_flash(*get_message('INVALID_PASSWORD'))
                return None

            user = User.query.filter_by(username=result['uid'][0]).first()

            if not user:
                encrypted_password = utils.encrypt_password(password)

                if not user_datastore.get_user(result['mail'][0]):
                    user = user_datastore.create_user(
                        email=result['mail'][0],
                        password=encrypted_password,
                        username=result['uid'][0],
                        name=result['cn'][0],
                        gid=result['gidNumber'][0],
                        homedir=result['homeDirectory'][0])

                    db.session.commit()

            user = User.query.filter_by(username=result['uid'][0]).first()

        else:
            user = User.query.filter_by(username=LOGIN_USERNAME).first()

            if username != LOGIN_USERNAME or LOGIN_PASSWORD != password:
                do_flash(*get_message('INVALID_PASSWORD'))
                return None

            if not user:
                encrypted_password_config = utils.encrypt_password(
                    LOGIN_PASSWORD)

                if not user_datastore.get_user(LOGIN_EMAIL):
                    user = user_datastore.create_user(
                        email=LOGIN_EMAIL,
                        password=encrypted_password_config,
                        username=LOGIN_USERNAME,
                        name=LOGIN_USERNAME,
                        gid=LOGIN_GID,
                        homedir=LOGIN_HOMEDIR)

                    db.session.commit()

            if not os.path.exists(os.path.join(LOGIN_HOMEDIR, "jobs")):
                os.makedirs(os.path.join(LOGIN_HOMEDIR, "jobs"))

            user = User.query.filter_by(username=LOGIN_USERNAME).first()

        login_user(user)
        return user
示例#37
0
    def reset_password(token):
        """View function that handles a reset password request."""
        expired, invalid, user = reset_password_token_status(token)

        if invalid:
            do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
        if expired:
            do_flash(*get_message('PASSWORD_RESET_EXPIRED',
                                  email=user.email,
                                  within=_security.reset_password_within))
        if invalid or expired:
            return redirect(url_for('browser.forgot_password'))
        has_error = False
        form = _security.reset_password_form()

        if form.validate_on_submit():
            try:
                update_password(user, form.password.data)
            except SOCKETErrorException as e:
                # Handle socket errors which are not covered by SMTPExceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(SMTP_SOCKET_ERROR).format(e), 'danger')
                has_error = True
            except (SMTPConnectError, SMTPResponseException,
                    SMTPServerDisconnected, SMTPDataError, SMTPHeloError,
                    SMTPException, SMTPAuthenticationError, SMTPSenderRefused,
                    SMTPRecipientsRefused) as e:

                # Handle smtp specific exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(SMTP_ERROR).format(e), 'danger')
                has_error = True
            except Exception as e:
                # Handle other exceptions.
                logging.exception(str(e), exc_info=True)
                flash(gettext(PASS_ERROR).format(e), 'danger')
                has_error = True

            if not has_error:
                after_this_request(view_commit)
                auth_obj = AuthSourceManager(form, [INTERNAL])
                session['_auth_source_manager_obj'] = auth_obj.as_dict()

                if user.login_attempts >= config.MAX_LOGIN_ATTEMPTS > 0:
                    flash(
                        gettext('You successfully reset your password but'
                                ' your account is locked. Please contact '
                                'the Administrator.'), 'warning')
                    return redirect(get_post_logout_redirect())
                do_flash(*get_message('PASSWORD_RESET'))
                login_user(user)
                auth_obj = AuthSourceManager(form, [INTERNAL])
                session['auth_source_manager'] = auth_obj.as_dict()

                return redirect(
                    get_url(_security.post_reset_view)
                    or get_url(_security.post_login_view))

        return _security.render_template(
            config_value('RESET_PASSWORD_TEMPLATE'),
            reset_password_form=form,
            reset_password_token=token,
            **_ctx('reset_password'))
示例#38
0
def change_password():
    """View function which handles a change password request."""

    if request.form.get('password'):
        try:
            result = User.try_login(current_user.username,
                                    request.form.get('password'))

            if not result:
                do_flash(*get_message('INVALID_PASSWORD'))
                return {"status": False}

        except ldap.INVALID_CREDENTIALS, e:
            print e
            do_flash(*get_message('INVALID_PASSWORD'))
            return {"status": False}

        if request.form.get('new_password') == request.form.get('password'):
            do_flash(*get_message('PASSWORD_IS_THE_SAME'))
            return {"status": False}

        if request.form.get('new_password') == request.form.get(
                'new_password_confirm'):

            if len(request.form.get('new_password_confirm')) < 6:
                do_flash(*get_message('PASSWORD_INVALID_LENGTH'))
                return {"status": False}

            status = User.change_pass(current_user.username,
                                      request.form.get('password'),
                                      request.form.get('new_password'))

            if status:
                password_changed.send(current_app._get_current_object(),
                                      user=current_user._get_current_object())
                do_flash(*get_message('PASSWORD_CHANGE'))
                print "password changed"
                return {"status": True}

        else:
            do_flash(*get_message('RETYPE_PASSWORD_MISMATCH'))
            print "passwords dont match"