Esempio n. 1
0
    def password_reset(self, request, **data):
        """Sends an e-mail for a password reset request."""
        if self.reset is None:
            self.logger.debug('reset attempted, but no resetcode library '
                              'installed')
            raise HTTPServiceUnavailable()

        request.response.headers.add('X-Frame-Options', 'DENY')
        user_id = self.auth.get_user_id(request.user)
        if user_id is None:
            # user not found
            raise HTTPJsonBadRequest(ERROR_INVALID_USER)

        self.auth.get_user_info(request.user, ['mail'])
        if request.user.get('mail') is None:
            raise HTTPJsonBadRequest(ERROR_NO_EMAIL_ADDRESS)

        self._check_captcha(request, data)

        try:
            # the request looks fine, let's generate the reset code
            code = self.reset.generate_reset_code(request.user)

            urlgen = URLGenerator(self.app.mapper, request.environ)
            data = {'user_name': request.user['username'],
                    'code': code,
                    'host': request.host_url,
                    'url': urlgen(controller="user",
                                  action="password_reset_form")}
            body = render_mako('password_reset_mail.mako', **data)

            sender = request.config['smtp.sender']
            host = request.config['smtp.host']
            port = int(request.config['smtp.port'])
            user = request.config.get('smtp.user')
            password = request.config.get('smtp.password')

            subject = 'Resetting your Services password'
            res, msg = send_email(sender, request.user['mail'], subject, body,
                                  host, port, user, password)

            if not res:
                raise HTTPServiceUnavailable(msg)
        except AlreadySentError:
            #backend handled the reset code email. Keep going
            pass

        return text_response('success')
    def password_reset(self, request, **data):
        """Sends an e-mail for a password reset request."""
        if self.reset is None:
            logger.debug('reset attempted, but no resetcode library installed')
            raise HTTPServiceUnavailable()

        user_id = self.auth.get_user_id(request.user)
        if user_id is None:
            # user not found
            raise HTTPJsonBadRequest(ERROR_INVALID_USER)

        self.auth.get_user_info(request.user, ['mail'])
        if request.user.get('mail') is None:
            raise HTTPJsonBadRequest(ERROR_NO_EMAIL_ADDRESS)

        self._check_captcha(request, data)

        try:
            # the request looks fine, let's generate the reset code
            code = self.reset.generate_reset_code(request.user)

            data = {
                'host': request.host_url,
                'user_name': request.user['username'],
                'code': code
            }
            body = render_mako('password_reset_mail.mako', **data)

            sender = request.config['smtp.sender']
            host = request.config['smtp.host']
            port = int(request.config['smtp.port'])
            user = request.config.get('smtp.user')
            password = request.config.get('smtp.password')

            subject = 'Resetting your Services password'
            res, msg = send_email(sender, request.user['mail'], subject, body,
                                  host, port, user, password)

            if not res:
                raise HTTPServiceUnavailable(msg)
        except AlreadySentError:
            #backend handled the reset code email. Keep going
            pass

        return text_response('success')
    def test_send_email(self):
        # let's patch smtplib and collect mails that are being produced
        # and load them into message objects

        class FakeMailer(object):

            mails = []

            def __init__(self, *args, **kw):
                pass

            def sendmail(self, sender, rcpts, msg):
                self.mails.append((sender, rcpts, msg))

            def quit(self):
                pass

        subject = u"Hello there"
        body = u"ah yeah"
        old = smtplib.SMTP
        smtplib.SMTP = FakeMailer
        try:
            # e-mail with real names
            send_email(u'Tarek Ziadé <*****@*****.**>',
                       u'John Doe <*****@*****.**>', subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(
                mail['From'],
                '=?utf-8?q?Tarek_Ziad=C3=A9?= ' + '<*****@*****.**>')

            self.assertEqual(mail['To'], 'John Doe <*****@*****.**>')

            # simple e-mail
            send_email(u'<*****@*****.**>', u'<*****@*****.**>',
                       subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '<*****@*****.**>')
            self.assertEqual(mail['To'], '<*****@*****.**>')

            # basic e-mail
            send_email(u'*****@*****.**', u'*****@*****.**', subject,
                       body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '*****@*****.**')
            self.assertEqual(mail['To'], '*****@*****.**')

            # XXX That should not happen
            # now what happens if we get strings
            send_email('*****@*****.**', '*****@*****.**', subject,
                       body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '*****@*****.**')
            self.assertEqual(mail['To'], '*****@*****.**')

            send_email('Tarek Ziadé <*****@*****.**>',
                       '*****@*****.**', subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(
                mail['From'],
                '=?utf-8?q?Tarek_Ziad=C3=A9?= ' + '<*****@*****.**>')
            self.assertEqual(mail['To'], '*****@*****.**')
        finally:
            smtplib.SMTP = old
Esempio n. 4
0
    def test_send_email(self):
        # let's patch smtplib and collect mails that are being produced
        # and load them into message objects

        class FakeMailer(object):

            mails = []

            def __init__(self, *args, **kw):
                pass

            def sendmail(self, sender, rcpts, msg):
                self.mails.append((sender, rcpts, msg))

            def quit(self):
                pass

        subject = u"Hello there"
        body = u"ah yeah"
        old = smtplib.SMTP
        smtplib.SMTP = FakeMailer
        try:
            # e-mail with real names
            send_email(u'Tarek Ziadé <*****@*****.**>',
                       u'John Doe <*****@*****.**>',
                       subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'],
                             '=?utf-8?q?Tarek_Ziad=C3=A9?= <*****@*****.**>')

            self.assertEqual(mail['To'],
                            'John Doe <*****@*****.**>')

            # simple e-mail
            send_email(u'<*****@*****.**>',
                       u'<*****@*****.**>',
                       subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '<*****@*****.**>')
            self.assertEqual(mail['To'], '<*****@*****.**>')

            # basic e-mail
            send_email(u'*****@*****.**',
                       u'*****@*****.**',
                       subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '*****@*****.**')
            self.assertEqual(mail['To'], '*****@*****.**')

            # XXX That should not happen
            # now what happens if we get strings
            send_email('*****@*****.**', '*****@*****.**',
                       subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'], '*****@*****.**')
            self.assertEqual(mail['To'], '*****@*****.**')

            send_email('Tarek Ziadé <*****@*****.**>',
                       '*****@*****.**', subject, body)

            # let's load it
            mail = message_from_string(FakeMailer.mails[-1][-1])
            self.assertEqual(mail['From'],
                             '=?utf-8?q?Tarek_Ziad=C3=A9?= <*****@*****.**>')
            self.assertEqual(mail['To'], '*****@*****.**')
        finally:
            smtplib.SMTP = old
Esempio n. 5
0
def forgot_step_2(request, **args):
    """Tries to send the email with a reset code, then lets the user know
    we've done that
    """
    data = {}
    auth = request.registry["auth"]
    username = extract_username(request.params['username'])
    request.user['username'] = username

    user_id = auth.get_user_id(request.user)
    if not user_id:
        request.errors.append(_('Unable to locate your account. '
                                'Please check your username.'))
        return render_to_response('console/password_reset1.mako',
                                  forgot_step_1(request), request)

    if not request.registry.settings['app.captcha'].check(request):
        log_cef('Captcha failed on forgot password', 3,
                request.environ,
                request.registry.settings.get('config').get_map(),
                username, signature=CAPTCHA_FAILURE)
        request.errors.append(_('The captcha did not match. '
                                'Please try again'))
        return render_to_response('console/password_reset1.mako',
                                  forgot_step_1(request), request)

    try:
        reset = request.registry.settings.get('app.console.reset')
        reset_code = reset.generate_reset_code(request.user, True)
        if not reset_code:
            request.errors.append(_('Getting a reset code failed '
                              'unexpectedly. Please try again later.'))
            logger.error("Could not generate a reset code")
            return render_to_response('console/password_reset1.mako',
                                      forgot_step_1(request), request)
        auth.get_user_info(request.user, ['mail'])
        if not valid_email(request.user['mail']):
            raise NoEmailError()

        maildata = {'forgot_url': '%s/forgot' % request.host_url,
                    'username': username,
                    'code': reset_code}
        template_path = get_template_lookup('console')
        template = \
            template_path.get_template('password_reset_mail.mako')
        body = template.render(**maildata)
        subject = _('Resetting your Mozilla Services password')
        smtp = request.registry.settings.get('config').get_map('smtp')
        #sender has a required position, so we can't pass it in in the
        #dict
        sender = smtp['sender']
        del smtp['sender']
        send_email(sender, request.user['mail'],
                   subject, body, **smtp)

    except AlreadySentError:
        #backend handled the reset code email. Keep going
        pass
    except NoEmailError:
        request.errors.append(_('We do not have an email on file for this '
                          'account and cannot send you a reset code.'))
        return render_to_response('console/password_reset1.mako',
                                  forgot_step_1(request), request)

    return data