Changeset - 5c310b7b01ce
[Not reviewed]
beta
0 3 0
Marcin Kuzminski - 13 years ago 2013-02-25 21:27:52
marcin@python-works.com
moved out password reset tasks from celery, it doesn't make any sense to keep them there, additionally they are broken
in when executing _(), and url() calls. This fixes issue #572
3 files changed with 60 insertions and 76 deletions:
0 comments (0 inline, 0 general)
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -242,90 +242,24 @@ def get_commits_stats(repo_name, ts_min_
 
        # execute another task if celery is enabled
 
        if len(repo.revisions) > 1 and CELERY_ON and recurse_limit > 0:
 
            recurse_limit -= 1
 
            run_task(get_commits_stats, repo_name, ts_min_y, ts_max_y,
 
                     recurse_limit)
 
        if recurse_limit <= 0:
 
            log.debug('Breaking recursive mode due to reach of recurse limit')
 
        return True
 
    except LockHeld:
 
        log.info('LockHeld')
 
        return 'Task with key %s already running' % lockkey
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def send_password_link(user_email):
 
    from rhodecode.model.notification import EmailNotificationModel
 

	
 
    log = get_logger(send_password_link)
 
    DBS = get_session()
 

	
 
    try:
 
        user = User.get_by_email(user_email)
 
        if user:
 
            log.debug('password reset user found %s' % user)
 
            link = url('reset_password_confirmation', key=user.api_key,
 
                       qualified=True)
 
            reg_type = EmailNotificationModel.TYPE_PASSWORD_RESET
 
            body = EmailNotificationModel().get_email_tmpl(reg_type,
 
                                                **{'user':user.short_contact,
 
                                                   'reset_url':link})
 
            log.debug('sending email')
 
            run_task(send_email, user_email,
 
                     _("password reset link"), body)
 
            log.info('send new password mail to %s' % user_email)
 
        else:
 
            log.debug("password reset email %s not found" % user_email)
 
    except:
 
        log.error(traceback.format_exc())
 
        return False
 

	
 
    return True
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def reset_user_password(user_email):
 
    from rhodecode.lib import auth
 

	
 
    log = get_logger(reset_user_password)
 
    DBS = get_session()
 

	
 
    try:
 
        try:
 
            user = User.get_by_email(user_email)
 
            new_passwd = auth.PasswordGenerator().gen_password(8,
 
                             auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
 
            if user:
 
                user.password = auth.get_crypt_password(new_passwd)
 
                user.api_key = auth.generate_api_key(user.username)
 
                DBS.add(user)
 
                DBS.commit()
 
                log.info('change password for %s' % user_email)
 
            if new_passwd is None:
 
                raise Exception('unable to generate new password')
 
        except:
 
            log.error(traceback.format_exc())
 
            DBS.rollback()
 

	
 
        run_task(send_email, user_email,
 
                 'Your new password',
 
                 'Your new RhodeCode password:%s' % (new_passwd))
 
        log.info('send new password mail to %s' % user_email)
 

	
 
    except:
 
        log.error('Failed to update user password')
 
        log.error(traceback.format_exc())
 

	
 
    return True
 

	
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def send_email(recipients, subject, body, html_body=''):
 
    """
 
    Sends an email with defined parameters from the .ini files.
 

	
 
    :param recipients: list of recipients, it this is empty the defined email
 
        address from field 'email_to' is used instead
 
    :param subject: subject of the mail
 
    :param body: body of the mail
 
    :param html_body: html version of body
rhodecode/model/user.py
Show inline comments
 
@@ -33,24 +33,25 @@ from pylons.i18n.translation import _
 
from sqlalchemy.exc import DatabaseError
 
from sqlalchemy.orm import joinedload
 

	
 
from rhodecode.lib.utils2 import safe_unicode, generate_api_key
 
from rhodecode.lib.caching_query import FromCache
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import User, UserRepoToPerm, Repository, Permission, \
 
    UserToPerm, UsersGroupRepoToPerm, UsersGroupToPerm, UsersGroupMember, \
 
    Notification, RepoGroup, UserRepoGroupToPerm, UsersGroupRepoGroupToPerm, \
 
    UserEmailMap, UserIpMap
 
from rhodecode.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from rhodecode.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
PERM_WEIGHTS = Permission.PERM_WEIGHTS
 

	
 

	
 
class UserModel(BaseModel):
 
    cls = User
 

	
 
    def get(self, user_id, cache=False):
 
        user = self.sa.query(User)
 
@@ -307,29 +308,79 @@ class UserModel(BaseModel):
 
                raise UserOwnsReposException(
 
                    _(u'user "%s" still owns %s repositories and cannot be '
 
                      'removed. Switch owners or remove those repositories. %s')
 
                    % (user.username, len(repos), ', '.join(repos))
 
                )
 
            self.sa.delete(user)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def reset_password_link(self, data):
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.send_password_link, data['email'])
 
        from rhodecode.model.notification import EmailNotificationModel
 
        user_email = data['email']
 
        try:
 
            user = User.get_by_email(user_email)
 
            if user:
 
                log.debug('password reset user found %s' % user)
 
                link = url('reset_password_confirmation', key=user.api_key,
 
                           qualified=True)
 
                reg_type = EmailNotificationModel.TYPE_PASSWORD_RESET
 
                body = EmailNotificationModel().get_email_tmpl(reg_type,
 
                                                    **{'user': user.short_contact,
 
                                                       'reset_url': link})
 
                log.debug('sending email')
 
                run_task(tasks.send_email, user_email,
 
                         _("password reset link"), body, body)
 
                log.info('send new password mail to %s' % user_email)
 
            else:
 
                log.debug("password reset email %s not found" % user_email)
 
        except:
 
            log.error(traceback.format_exc())
 
            return False
 

	
 
        return True
 

	
 
    def reset_password(self, data):
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.reset_user_password, data['email'])
 
        from rhodecode.lib import auth
 
        user_email = data['email']
 
        try:
 
            try:
 
                user = User.get_by_email(user_email)
 
                new_passwd = auth.PasswordGenerator().gen_password(8,
 
                                 auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
 
                if user:
 
                    user.password = auth.get_crypt_password(new_passwd)
 
                    user.api_key = auth.generate_api_key(user.username)
 
                    Session().add(user)
 
                    Session().commit()
 
                    log.info('change password for %s' % user_email)
 
                if new_passwd is None:
 
                    raise Exception('unable to generate new password')
 
            except:
 
                log.error(traceback.format_exc())
 
                Session().rollback()
 

	
 
            run_task(tasks.send_email, user_email,
 
                     _('Your new password'),
 
                     _('Your new RhodeCode password:%s') % (new_passwd))
 
            log.info('send new password mail to %s' % user_email)
 

	
 
        except:
 
            log.error('Failed to update user password')
 
            log.error(traceback.format_exc())
 

	
 
        return True
 

	
 
    def fill_data(self, auth_user, user_id=None, api_key=None):
 
        """
 
        Fetches auth_user by user_id,or api_key if present.
 
        Fills auth_user attributes with those taken from database.
 
        Additionally set's is_authenitated if lookup fails
 
        present in database
 

	
 
        :param auth_user: instance of user to set attributes
 
        :param user_id: user id to fetch by
 
        :param api_key: api key to fetch by
 
        """
rhodecode/templates/email_templates/password_reset.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="main.html"/>
 

	
 
${_('Hello')} ${user}
 

	
 
${_('We received a request to create a new password for your account.')}
 

	
 
${_('You can generate it by clicking following URL')}:
 

	
 
<h4>${_('Hello %s') % user}</h4>
 
<div>${_('We received a request to create a new password for your account.')}</div>
 
<div>${_('You can generate it by clicking following URL')}:</div>
 
<pre>
 
${reset_url}
 

	
 
${_("If you didn't request new password please ignore this email.")}
 
</pre>
 
<br/>
 
${_("If you did not request new password please ignore this email.")}
0 comments (0 inline, 0 general)