Changeset - 8ecc6b8229a5
[Not reviewed]
beta
0 38 0
Marcin Kuzminski - 14 years ago 2011-12-02 21:31:13
marcin@python-works.com
commit less models
- models don't do any commits(with few exceptions)
- all db transactions should be handled by higher level modules like controllers, celery tasks
38 files changed with 298 insertions and 325 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/permissions.py
Show inline comments
 
@@ -99,13 +99,13 @@ class PermissionsController(BaseControll
 
                                       [x[0] for x in self.create_choices])()
 

	
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            form_result.update({'perm_user_name': id})
 
            permission_model.update(form_result)
 
            Session().commit()
 
            Session.commit()
 
            h.flash(_('Default permissions updated successfully'),
 
                    category='success')
 

	
 
        except formencode.Invalid, errors:
 
            c.perms_choices = self.perms_choices
 
            c.register_choices = self.register_choices
rhodecode/controllers/admin/repos.py
Show inline comments
 
@@ -147,13 +147,13 @@ class ReposController(BaseController):
 
                # created by regular non admin user
 
                action_logger(self.rhodecode_user, 'user_created_repo',
 
                              form_result['repo_name_full'], '', self.sa)
 
            else:
 
                action_logger(self.rhodecode_user, 'admin_created_repo',
 
                              form_result['repo_name_full'], '', self.sa)
 
            Session().commit()
 
            Session.commit()
 
        except formencode.Invalid, errors:
 

	
 
            c.new_repo = errors.value['repo_name']
 

	
 
            if request.POST.get('user_created'):
 
                r = render('admin/repos/repo_add_create_repository.html')
 
@@ -205,13 +205,13 @@ class ReposController(BaseController):
 
            invalidate_cache('get_repo_cached_%s' % repo_name)
 
            h.flash(_('Repository %s updated successfully' % repo_name),
 
                    category='success')
 
            changed_name = repo.repo_name
 
            action_logger(self.rhodecode_user, 'admin_updated_repo',
 
                              changed_name, '', self.sa)
 
            Session().commit()
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            defaults = self.__load_data(repo_name)
 
            defaults.update(errors.value)
 
            return htmlfill.render(
 
                render('admin/repos/repo_edit.html'),
 
                defaults=defaults,
 
@@ -249,13 +249,13 @@ class ReposController(BaseController):
 
        try:
 
            action_logger(self.rhodecode_user, 'admin_deleted_repo',
 
                              repo_name, '', self.sa)
 
            repo_model.delete(repo)
 
            invalidate_cache('get_repo_cached_%s' % repo_name)
 
            h.flash(_('deleted repository %s') % repo_name, category='success')
 
            Session().commit()
 
            Session.commit()
 
        except IntegrityError, e:
 
            if e.message.find('repositories_fork_id_fkey'):
 
                log.error(traceback.format_exc())
 
                h.flash(_('Cannot delete %s it still contains attached '
 
                          'forks') % repo_name,
 
                        category='warning')
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
@@ -68,13 +68,13 @@ class ReposGroupsController(BaseControll
 
        self.__load_defaults()
 
        repos_group_form = ReposGroupForm(available_groups=
 
                                          c.repo_groups_choices)()
 
        try:
 
            form_result = repos_group_form.to_python(dict(request.POST))
 
            ReposGroupModel().create(form_result)
 
            Session().commit()
 
            Session.commit()
 
            h.flash(_('created repos group %s') \
 
                    % form_result['group_name'], category='success')
 
            #TODO: in futureaction_logger(, '', '', '', self.sa)
 
        except formencode.Invalid, errors:
 

	
 
            return htmlfill.render(
 
@@ -115,13 +115,13 @@ class ReposGroupsController(BaseControll
 
                                          old_data=c.repos_group.get_dict(),
 
                                          available_groups=
 
                                            c.repo_groups_choices)()
 
        try:
 
            form_result = repos_group_form.to_python(dict(request.POST))
 
            ReposGroupModel().update(id, form_result)
 
            Session().commit()
 
            Session.commit()
 
            h.flash(_('updated repos group %s') \
 
                    % form_result['group_name'], category='success')
 
            #TODO: in futureaction_logger(, '', '', '', self.sa)
 
        except formencode.Invalid, errors:
 

	
 
            return htmlfill.render(
 
@@ -155,13 +155,13 @@ class ReposGroupsController(BaseControll
 
                      'deleted' % len(repos)),
 
                    category='error')
 
            return redirect(url('repos_groups'))
 

	
 
        try:
 
            ReposGroupModel().delete(id)
 
            Session().commit()
 
            Session.commit()
 
            h.flash(_('removed repos group %s' % gr.group_name), category='success')
 
            #TODO: in future action_logger(, '', '', '', self.sa)
 
        except IntegrityError, e:
 
            if e.message.find('groups_group_parent_id_fkey'):
 
                log.error(traceback.format_exc())
 
                h.flash(_('Cannot delete this group it still contains '
rhodecode/controllers/admin/settings.py
Show inline comments
 
@@ -45,12 +45,13 @@ from rhodecode.model.db import RhodeCode
 
from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
 
    ApplicationUiSettingsForm
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.db import User
 
from rhodecode.model.notification import EmailNotificationModel
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class SettingsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
@@ -244,13 +245,13 @@ class SettingsController(BaseController)
 
                for k, v in zip(_d.get('hook_ui_key', []), _d.get('hook_ui_value_new', [])):
 
                    RhodeCodeUi.create_or_update_hook(k, v)
 
                    update = True
 

	
 
                if update:
 
                    h.flash(_('Updated hooks'), category='success')
 

	
 
                Session.commit()
 
            except:
 
                log.error(traceback.format_exc())
 
                h.flash(_('error occurred during hook creation'),
 
                        category='error')
 

	
 
            return redirect(url('admin_edit_setting', setting_id='hooks'))
 
@@ -350,13 +351,13 @@ class SettingsController(BaseController)
 
        form_result = {}
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            user_model.update_my_account(uid, form_result)
 
            h.flash(_('Your account was updated successfully'),
 
                    category='success')
 

	
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            c.user = User.get(self.rhodecode_user.user_id)
 
            all_repos = self.sa.query(Repository)\
 
                .filter(Repository.user_id == c.user.user_id)\
 
                .order_by(func.lower(Repository.repo_name))\
 
                .all()
rhodecode/controllers/admin/users.py
Show inline comments
 
@@ -38,12 +38,13 @@ from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
 
from rhodecode.lib.base import BaseController, render
 

	
 
from rhodecode.model.db import User, UserRepoToPerm, UserToPerm, Permission
 
from rhodecode.model.forms import UserForm
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
@@ -74,12 +75,13 @@ class UsersController(BaseController):
 
        user_form = UserForm()()
 
        try:
 
            form_result = user_form.to_python(dict(request.POST))
 
            user_model.create(form_result)
 
            h.flash(_('created user %s') % form_result['username'],
 
                    category='success')
 
            Session.commit()
 
            #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
 
        except formencode.Invalid, errors:
 
            return htmlfill.render(
 
                render('admin/users/user_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
@@ -111,17 +113,17 @@ class UsersController(BaseController):
 
                                              'email': c.user.email})()
 
        form_result = {}
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            user_model.update(id, form_result)
 
            h.flash(_('User updated successfully'), category='success')
 

	
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            e = errors.error_dict or {}
 
            perm = Permission.get_by_key('hg.create.repository')
 
            e.update({'create_repo_perm': UserToPerm.has_perm(id, perm)})
 
            e.update({'create_repo_perm': user_model.has_perm(id, perm)})
 
            return htmlfill.render(
 
                render('admin/users/user_edit.html'),
 
                defaults=errors.value,
 
                errors=e,
 
                prefix_error=False,
 
                encoding="UTF-8")
 
@@ -141,12 +143,13 @@ class UsersController(BaseController):
 
        #           method='delete')
 
        # url('user', id=ID)
 
        user_model = UserModel()
 
        try:
 
            user_model.delete(id)
 
            h.flash(_('successfully deleted user'), category='success')
 
            Session.commit()
 
        except (UserOwnsReposException, DefaultUserException), e:
 
            h.flash(str(e), category='warning')
 
        except Exception:
 
            h.flash(_('An error occurred during deletion of user'),
 
                    category='error')
 
        return redirect(url('users'))
 
@@ -155,26 +158,25 @@ class UsersController(BaseController):
 
        """GET /users/id: Show a specific item"""
 
        # url('user', id=ID)
 

	
 
    def edit(self, id, format='html'):
 
        """GET /users/id/edit: Form to edit an existing item"""
 
        # url('edit_user', id=ID)
 
        user_model = UserModel()
 
        c.user = user_model.get(id)
 
        c.user = User.get(id)
 
        if not c.user:
 
            return redirect(url('users'))
 
        if c.user.username == 'default':
 
            h.flash(_("You can't edit this user"), category='warning')
 
            return redirect(url('users'))
 
        c.user.permissions = {}
 
        c.granted_permissions = user_model.fill_perms(c.user)\
 
        c.granted_permissions = UserModel().fill_perms(c.user)\
 
            .permissions['global']
 

	
 
        defaults = c.user.get_dict()
 
        perm = Permission.get_by_key('hg.create.repository')
 
        defaults.update({'create_repo_perm': UserToPerm.has_perm(id, perm)})
 
        defaults.update({'create_repo_perm': UserModel().has_perm(id, perm)})
 

	
 
        return htmlfill.render(
 
            render('admin/users/user_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
@@ -182,26 +184,27 @@ class UsersController(BaseController):
 

	
 
    def update_perm(self, id):
 
        """PUT /users_perm/id: Update an existing item"""
 
        # url('user_perm', id=ID, method='put')
 

	
 
        grant_perm = request.POST.get('create_repo_perm', False)
 
        user_model = UserModel()
 

	
 
        if grant_perm:
 
            perm = Permission.get_by_key('hg.create.none')
 
            UserToPerm.revoke_perm(id, perm)
 
            user_model.revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UserToPerm.grant_perm(id, perm)
 
            user_model.grant_perm(id, perm)
 
            h.flash(_("Granted 'repository create' permission to user"),
 
                    category='success')
 

	
 
        else:
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UserToPerm.revoke_perm(id, perm)
 
            user_model.revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.none')
 
            UserToPerm.grant_perm(id, perm)
 
            user_model.grant_perm(id, perm)
 
            h.flash(_("Revoked 'repository create' permission to user"),
 
                    category='success')
 

	
 
        return redirect(url('edit_user', id=id))
rhodecode/controllers/admin/users_groups.py
Show inline comments
 
@@ -30,18 +30,21 @@ import formencode
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, config
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib import helpers as h, safe_unicode
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
 
from rhodecode.lib.base import BaseController, render
 

	
 
from rhodecode.model.users_group import UsersGroupModel
 

	
 
from rhodecode.model.db import User, UsersGroup, Permission, UsersGroupToPerm
 
from rhodecode.model.forms import UserForm, UsersGroupForm
 
from rhodecode.model.forms import UsersGroupForm
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersGroupsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
@@ -67,16 +70,18 @@ class UsersGroupsController(BaseControll
 
        """POST /users_groups: Create a new item"""
 
        # url('users_groups')
 

	
 
        users_group_form = UsersGroupForm()()
 
        try:
 
            form_result = users_group_form.to_python(dict(request.POST))
 
            UsersGroup.create(form_result)
 
            UsersGroupModel().create(name=form_result['users_group_name'],
 
                                     active=form_result['users_group_active'])
 
            h.flash(_('created users group %s') \
 
                    % form_result['users_group_name'], category='success')
 
            #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            return htmlfill.render(
 
                render('admin/users_groups/users_group_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
@@ -105,30 +110,33 @@ class UsersGroupsController(BaseControll
 
        c.users_group = UsersGroup.get(id)
 
        c.group_members = [(x.user_id, x.user.username) for x in
 
                           c.users_group.members]
 

	
 
        c.available_members = [(x.user_id, x.username) for x in
 
                               self.sa.query(User).all()]
 
        
 
        available_members = [safe_unicode(x[0]) for x in c.available_members]
 
        
 
        users_group_form = UsersGroupForm(edit=True,
 
                                          old_data=c.users_group.get_dict(),
 
                                          available_members=[str(x[0]) for x
 
                                                in c.available_members])()
 
                                          available_members=available_members)()
 

	
 
        try:
 
            form_result = users_group_form.to_python(request.POST)
 
            UsersGroup.update(id, form_result)
 
            UsersGroupModel().update(c.users_group, form_result)
 
            h.flash(_('updated users group %s') \
 
                        % form_result['users_group_name'],
 
                    category='success')
 
            #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            e = errors.error_dict or {}
 

	
 
            perm = Permission.get_by_key('hg.create.repository')
 
            e.update({'create_repo_perm':
 
                         UsersGroupToPerm.has_perm(id, perm)})
 
                         UsersGroupModel().has_perm(id, perm)})
 

	
 
            return htmlfill.render(
 
                render('admin/users_groups/users_group_edit.html'),
 
                defaults=errors.value,
 
                errors=e,
 
                prefix_error=False,
 
@@ -147,14 +155,15 @@ class UsersGroupsController(BaseControll
 
        # Or using helpers:
 
        #    h.form(url('users_group', id=ID),
 
        #           method='delete')
 
        # url('users_group', id=ID)
 

	
 
        try:
 
            UsersGroup.delete(id)
 
            UsersGroupModel().delete(id)
 
            h.flash(_('successfully deleted users group'), category='success')
 
            Session.commit()
 
        except UsersGroupsAssignedException, e:
 
            h.flash(e, category='error')
 
        except Exception:
 
            h.flash(_('An error occurred during deletion of users group'),
 
                    category='error')
 
        return redirect(url('users_groups'))
 
@@ -176,13 +185,13 @@ class UsersGroupsController(BaseControll
 
                           c.users_group.members]
 
        c.available_members = [(x.user_id, x.username) for x in
 
                               self.sa.query(User).all()]
 
        defaults = c.users_group.get_dict()
 
        perm = Permission.get_by_key('hg.create.repository')
 
        defaults.update({'create_repo_perm':
 
                         UsersGroupToPerm.has_perm(id, perm)})
 
                         UsersGroupModel().has_perm(c.users_group, perm)})
 
        return htmlfill.render(
 
            render('admin/users_groups/users_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )
 
@@ -192,23 +201,24 @@ class UsersGroupsController(BaseControll
 
        # url('users_group_perm', id=ID, method='put')
 

	
 
        grant_perm = request.POST.get('create_repo_perm', False)
 

	
 
        if grant_perm:
 
            perm = Permission.get_by_key('hg.create.none')
 
            UsersGroupToPerm.revoke_perm(id, perm)
 
            UsersGroupModel().revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UsersGroupToPerm.grant_perm(id, perm)
 
            UsersGroupModel().grant_perm(id, perm)
 
            h.flash(_("Granted 'repository create' permission to user"),
 
                    category='success')
 

	
 
            Session.commit()
 
        else:
 
            perm = Permission.get_by_key('hg.create.repository')
 
            UsersGroupToPerm.revoke_perm(id, perm)
 
            UsersGroupModel().revoke_perm(id, perm)
 

	
 
            perm = Permission.get_by_key('hg.create.none')
 
            UsersGroupToPerm.grant_perm(id, perm)
 
            UsersGroupModel().grant_perm(id, perm)
 
            h.flash(_("Revoked 'repository create' permission to user"),
 
                    category='success')
 

	
 
            Session.commit()
 
        return redirect(url('edit_users_group', id=id))
rhodecode/controllers/api/api.py
Show inline comments
 
@@ -117,13 +117,13 @@ class ApiController(JSONRPCController):
 
        if User.get_by_username(username):
 
            raise JSONRPCError("user %s already exist" % username)
 

	
 
        try:
 
            UserModel().create_or_update(username, password, email, firstname,
 
                                         lastname, active, admin, ldap_dn)
 
            Session().commit()
 
            Session.commit()
 
            return dict(msg='created new user %s' % username)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to create user %s' % username)
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
@@ -195,13 +195,13 @@ class ApiController(JSONRPCController):
 

	
 
        if self.get_users_group(apiuser, name):
 
            raise JSONRPCError("users group %s already exist" % name)
 

	
 
        try:
 
            ug = UsersGroupModel().create(name=name, active=active)
 
            Session().commit()
 
            Session.commit()
 
            return dict(id=ug.users_group_id,
 
                        msg='created new users group %s' % name)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to create group %s' % name)
 

	
 
@@ -223,13 +223,13 @@ class ApiController(JSONRPCController):
 
            try:
 
                user = User.get_by_username(user_name)
 
            except NoResultFound:
 
                raise JSONRPCError('unknown user %s' % user_name)
 

	
 
            ugm = UsersGroupModel().add_user_to_group(users_group, user)
 
            Session().commit()
 
            Session.commit()
 
            return dict(id=ugm.users_group_member_id,
 
                        msg='created new users group member')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to create users group member')
 

	
 
@@ -239,16 +239,15 @@ class ApiController(JSONRPCController):
 
        Get repository by name
 

	
 
        :param apiuser
 
        :param repo_name
 
        """
 

	
 
        try:
 
            repo = Repository.get_by_repo_name(repo_name)
 
        except NoResultFound:
 
            return None
 
        if repo is None:
 
            raise JSONRPCError('unknown repository %s' % repo)
 

	
 
        members = []
 
        for user in repo.repo_to_perm:
 
            perm = user.permission.permission_name
 
            user = user.user
 
            members.append(dict(type_="user",
 
@@ -331,13 +330,13 @@ class ApiController(JSONRPCController):
 
                                     repo_name_full=name,
 
                                     description=description,
 
                                     private=private,
 
                                     repo_type=repo_type,
 
                                     repo_group=parent_id,
 
                                     clone_uri=None), owner)
 
            Session().commit()
 
            Session.commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to create repository %s' % name)
 

	
 
    @HasPermissionAnyDecorator('hg.admin')
 
    def add_user_to_repo(self, apiuser, repo_name, user_name, perm):
 
@@ -348,24 +347,23 @@ class ApiController(JSONRPCController):
 
        :param repo_name
 
        :param user_name
 
        :param perm
 
        """
 

	
 
        try:
 
            try:
 
                repo = Repository.get_by_repo_name(repo_name)
 
            except NoResultFound:
 
            if repo is None:
 
                raise JSONRPCError('unknown repository %s' % repo)
 

	
 
            try:
 
                user = User.get_by_username(user_name)
 
            except NoResultFound:
 
                raise JSONRPCError('unknown user %s' % user)
 

	
 
            RepositoryPermissionModel()\
 
                .update_or_delete_user_permission(repo, user, perm)
 
            Session().commit()
 
            Session.commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to edit permission %(repo)s for %(user)s'
 
                            % dict(user=user_name, repo=repo_name))
 

	
rhodecode/controllers/changeset.py
Show inline comments
 
@@ -277,21 +277,21 @@ class ChangesetController(BaseRepoContro
 
        ChangesetCommentsModel().create(text=request.POST.get('text'),
 
                                        repo_id=c.rhodecode_db_repo.repo_id,
 
                                        user_id=c.rhodecode_user.user_id,
 
                                        revision=revision,
 
                                        f_path=request.POST.get('f_path'),
 
                                        line_no=request.POST.get('line'))
 
        Session().commit()
 
        Session.commit()
 
        return redirect(h.url('changeset_home', repo_name=repo_name,
 
                              revision=revision))
 

	
 
    @jsonify
 
    def delete_comment(self, repo_name, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        owner = lambda : co.author.user_id == c.rhodecode_user.user_id
 
        if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
            ChangesetCommentsModel().delete(comment=co)
 
            Session().commit()
 
            Session.commit()
 
            return True
 
        else:
 
            raise HTTPForbidden()
 

	
rhodecode/controllers/journal.py
Show inline comments
 
@@ -131,23 +131,23 @@ class JournalController(BaseController):
 

	
 
            user_id = request.POST.get('follows_user_id')
 
            if user_id:
 
                try:
 
                    self.scm_model.toggle_following_user(user_id,
 
                                                self.rhodecode_user.user_id)
 
                    Session().commit()
 
                    Session.commit()
 
                    return 'ok'
 
                except:
 
                    raise HTTPBadRequest()
 

	
 
            repo_id = request.POST.get('follows_repo_id')
 
            if repo_id:
 
                try:
 
                    self.scm_model.toggle_following_repo(repo_id,
 
                                                self.rhodecode_user.user_id)
 
                    Session().commit()
 
                    Session.commit()
 
                    return 'ok'
 
                except:
 
                    raise HTTPBadRequest()
 

	
 
        log.debug('token mismatch %s vs %s', cur_token, token)
 
        raise HTTPBadRequest()
rhodecode/controllers/login.py
Show inline comments
 
@@ -72,12 +72,13 @@ class LoginController(BaseController):
 
                session['rhodecode_user'] = cs
 
                session.save()
 

	
 
                log.info('user %s is now authenticated and stored in '
 
                         'session, session attrs %s' % (username, cs))
 
                user.update_lastlogin()
 
                Session.commit()
 

	
 
                if c.came_from:
 
                    return redirect(c.came_from)
 
                else:
 
                    return redirect(url('home'))
 

	
 
@@ -91,29 +92,28 @@ class LoginController(BaseController):
 

	
 
        return render('/login.html')
 

	
 
    @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
 
                               'hg.register.manual_activate')
 
    def register(self):
 
        user_model = UserModel()
 
        c.auto_active = False
 
        for perm in User.get_by_username('default').user_perms:
 
            if perm.permission.permission_name == 'hg.register.auto_activate':
 
                c.auto_active = True
 
                break
 

	
 
        if request.POST:
 

	
 
            register_form = RegisterForm()()
 
            try:
 
                form_result = register_form.to_python(dict(request.POST))
 
                form_result['active'] = c.auto_active
 
                user_model.create_registration(form_result)
 
                UserModel().create_registration(form_result)
 
                h.flash(_('You have successfully registered into rhodecode'),
 
                            category='success')
 
                Session().commit()
 
                Session.commit()
 
                return redirect(url('login_home'))
 

	
 
            except formencode.Invalid, errors:
 
                return htmlfill.render(
 
                    render('/register.html'),
 
                    defaults=errors.value,
 
@@ -121,19 +121,17 @@ class LoginController(BaseController):
 
                    prefix_error=False,
 
                    encoding="UTF-8")
 

	
 
        return render('/register.html')
 

	
 
    def password_reset(self):
 
        user_model = UserModel()
 
        if request.POST:
 

	
 
            password_reset_form = PasswordResetForm()()
 
            try:
 
                form_result = password_reset_form.to_python(dict(request.POST))
 
                user_model.reset_password_link(form_result)
 
                UserModel().reset_password_link(form_result)
 
                h.flash(_('Your password reset link was sent'),
 
                            category='success')
 
                return redirect(url('login_home'))
 

	
 
            except formencode.Invalid, errors:
 
                return htmlfill.render(
 
@@ -143,19 +141,17 @@ class LoginController(BaseController):
 
                    prefix_error=False,
 
                    encoding="UTF-8")
 

	
 
        return render('/password_reset.html')
 

	
 
    def password_reset_confirmation(self):
 

	
 
        if request.GET and request.GET.get('key'):
 
            try:
 
                user_model = UserModel()
 
                user = User.get_by_api_key(request.GET.get('key'))
 
                data = dict(email=user.email)
 
                user_model.reset_password(data)
 
                UserModel().reset_password(data)
 
                h.flash(_('Your password reset was successful, '
 
                          'new password has been sent to your email'),
 
                            category='success')
 
            except Exception, e:
 
                log.error(e)
 
                return redirect(url('reset_password'))
rhodecode/controllers/settings.py
Show inline comments
 
@@ -102,13 +102,13 @@ class SettingsController(BaseRepoControl
 
            invalidate_cache('get_repo_cached_%s' % repo_name)
 
            h.flash(_('Repository %s updated successfully' % repo_name),
 
                    category='success')
 
            changed_name = form_result['repo_name_full']
 
            action_logger(self.rhodecode_user, 'user_updated_repo',
 
                          changed_name, '', self.sa)
 
            Session().commit()
 
            Session.commit()
 
        except formencode.Invalid, errors:
 
            c.repo_info = repo_model.get_by_repo_name(repo_name)
 
            c.users_array = repo_model.get_users_js()
 
            errors.value.update({'user': c.repo_info.user.username})
 
            return htmlfill.render(
 
                render('settings/repo_settings.html'),
 
@@ -146,13 +146,13 @@ class SettingsController(BaseRepoControl
 
        try:
 
            action_logger(self.rhodecode_user, 'user_deleted_repo',
 
                              repo_name, '', self.sa)
 
            repo_model.delete(repo)
 
            invalidate_cache('get_repo_cached_%s' % repo_name)
 
            h.flash(_('deleted repository %s') % repo_name, category='success')
 
            Session().commit()
 
            Session.commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of %s') % repo_name,
 
                    category='error')
 

	
 
        return redirect(url('home'))
rhodecode/lib/auth.py
Show inline comments
 
@@ -32,12 +32,13 @@ from decorator import decorator
 

	
 
from pylons import config, session, url, request
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode import __platform__, PLATFORM_WIN, PLATFORM_OTHERS
 
from rhodecode.model.meta import Session
 

	
 
if __platform__ in PLATFORM_WIN:
 
    from hashlib import sha256
 
if __platform__ in PLATFORM_OTHERS:
 
    import bcrypt
 

	
 
@@ -223,38 +224,40 @@ def authenticate(username, password):
 
                }
 

	
 
                if user_model.create_ldap(username, password, user_dn,
 
                                          user_attrs):
 
                    log.info('created new ldap user %s', username)
 

	
 
                Session.commit()    
 
                return True
 
            except (LdapUsernameError, LdapPasswordError,):
 
                pass
 
            except (Exception,):
 
                log.error(traceback.format_exc())
 
                pass
 
    return False
 

	
 
def login_container_auth(username):
 
    user = User.get_by_username(username)
 
    if user is None:
 
        user_model = UserModel()
 
        user_attrs = {
 
            'name': username,
 
            'lastname': None,
 
            'email': None,
 
        }
 
        user = user_model.create_for_container_auth(username, user_attrs)
 
        user = UserModel().create_for_container_auth(username, user_attrs)
 
        if not user:
 
            return None
 
        log.info('User %s was created by container authentication', username)
 

	
 
    if not user.active:
 
        return None
 

	
 
    user.update_lastlogin()
 
    Session.commit()
 
    
 
    log.debug('User %s is now logged in by container authentication',
 
              user.username)
 
    return user
 

	
 
def get_container_username(environ, config):
 
    username = None
 
@@ -377,13 +380,13 @@ def set_available_permissions(config):
 

	
 
    :param config: current pylons config instance
 

	
 
    """
 
    log.info('getting information about all available permissions')
 
    try:
 
        sa = meta.Session()
 
        sa = meta.Session
 
        all_perms = sa.query(Permission).all()
 
    except:
 
        pass
 
    finally:
 
        meta.Session.remove()
 

	
rhodecode/lib/base.py
Show inline comments
 
@@ -32,13 +32,13 @@ class BaseController(WSGIController):
 
        c.repo_name = get_repo_slug(request)
 
        c.backends = BACKENDS.keys()
 
        c.unread_notifications = NotificationModel()\
 
                        .get_unread_cnt_for_user(c.rhodecode_user.user_id)
 
        self.cut_off_limit = int(config.get('cut_off_limit'))
 

	
 
        self.sa = meta.Session()
 
        self.sa = meta.Session
 
        self.scm_model = ScmModel(self.sa)
 

	
 
    def __call__(self, environ, start_response):
 
        """Invoke the Controller"""
 
        # WSGIController.__call__ dispatches to the Controller method
 
        # the request is routed to. This routing information is
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -61,13 +61,13 @@ __all__ = ['whoosh_index', 'get_commits_
 

	
 

	
 
def get_session():
 
    if CELERY_ON:
 
        engine = engine_from_config(config, 'sqlalchemy.db1.')
 
        init_model(engine)
 
    sa = meta.Session()
 
    sa = meta.Session
 
    return sa
 

	
 
def get_logger(cls):
 
    if CELERY_ON:
 
        try:
 
            log = cls.get_logger()
 
@@ -106,13 +106,17 @@ def get_commits_stats(repo_name, ts_min_
 

	
 
        # for js data compatibilty cleans the key for person from '
 
        akc = lambda k: person(k).replace('"', "")
 

	
 
        co_day_auth_aggr = {}
 
        commits_by_day_aggregate = {}
 
        repo = Repository.get_by_repo_name(repo_name).scm_instance
 
        repo = Repository.get_by_repo_name(repo_name)
 
        if repo is None:
 
            return True
 
        
 
        repo = repo.scm_instance
 
        repo_size = len(repo.revisions)
 
        #return if repo have no revisions
 
        if repo_size < 1:
 
            lock.release()
 
            return True
 

	
rhodecode/lib/db_manage.py
Show inline comments
 
@@ -54,13 +54,13 @@ class DbManage(object):
 
        self.db_exists = False
 
        self.init_db()
 

	
 
    def init_db(self):
 
        engine = create_engine(self.dburi, echo=self.log_sql)
 
        init_model(engine)
 
        self.sa = meta.Session()
 
        self.sa = meta.Session
 

	
 
    def create_tables(self, override=False):
 
        """Create a auth database
 
        """
 

	
 
        log.info("Any existing database is going to be destroyed")
rhodecode/lib/dbmigrate/schema/db_1_2_0.py
Show inline comments
 
@@ -1058,13 +1058,13 @@ class CacheInvalidation(Base, BaseModel)
 
        Mark this Cache key for invalidation
 
        
 
        :param key:
 
        """
 

	
 
        log.debug('marking %s for invalidation' % key)
 
        inv_obj = Session().query(cls)\
 
        inv_obj = Session.query(cls)\
 
            .filter(cls.cache_key == key).scalar()
 
        if inv_obj:
 
            inv_obj.cache_active = False
 
        else:
 
            log.debug('cache key not found in invalidation db -> creating one')
 
            inv_obj = CacheInvalidation(key)
 
@@ -1080,13 +1080,13 @@ class CacheInvalidation(Base, BaseModel)
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 
        :param key:
 
        """
 
        inv_obj = Session().query(CacheInvalidation)\
 
        inv_obj = Session.query(CacheInvalidation)\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session.add(inv_obj)
 
        Session.commit()
 

	
 
class DbMigrateVersion(Base, BaseModel):
rhodecode/lib/utils.py
Show inline comments
 
@@ -107,13 +107,13 @@ def action_logger(user, action, repo, ip
 
    :param ipaddr: optional ip address from what the action was made
 
    :param sa: optional sqlalchemy session
 

	
 
    """
 

	
 
    if not sa:
 
        sa = meta.Session()
 
        sa = meta.Session
 

	
 
    try:
 
        if hasattr(user, 'user_id'):
 
            user_obj = user
 
        elif isinstance(user, basestring):
 
            user_obj = User.get_by_username(user)
 
@@ -268,13 +268,13 @@ def make_ui(read_from='file', path=None,
 
        for section in ui_sections:
 
            for k, v in cfg.items(section):
 
                log.debug('settings ui from file[%s]%s:%s', section, k, v)
 
                baseui.setconfig(section, k, v)
 

	
 
    elif read_from == 'db':
 
        sa = meta.Session()
 
        sa = meta.Session
 
        ret = sa.query(RhodeCodeUi)\
 
            .options(FromCache("sql_cache_short",
 
                               "get_hg_ui_settings")).all()
 

	
 
        hg_ui = ret
 
        for ui_ in hg_ui:
 
@@ -359,13 +359,13 @@ def map_groups(groups):
 
    """
 
    Checks for groups existence, and creates groups structures.
 
    It returns last group in structure
 

	
 
    :param groups: list of groups structure
 
    """
 
    sa = meta.Session()
 
    sa = meta.Session
 

	
 
    parent = None
 
    group = None
 

	
 
    # last element is repo in nested groups structure
 
    groups = groups[:-1]
 
@@ -389,13 +389,13 @@ def repo2db_mapper(initial_repo_list, re
 
    that are not in initial_repo_list and removes them.
 

	
 
    :param initial_repo_list: list of repositories found by scanning methods
 
    :param remove_obsolete: check for obsolete entries in database
 
    """
 
    from rhodecode.model.repo import RepoModel
 
    sa = meta.Session()
 
    sa = meta.Session
 
    rm = RepoModel()
 
    user = sa.query(User).filter(User.admin == True).first()
 
    if user is None:
 
        raise Exception('Missing administrative account !')
 
    added = []
 

	
 
@@ -507,13 +507,13 @@ def create_test_env(repos_test_path, con
 
    dbmanage.create_tables(override=True)
 
    dbmanage.create_settings(dbmanage.config_prompt(repos_test_path))
 
    dbmanage.create_default_user()
 
    dbmanage.admin_prompt()
 
    dbmanage.create_permissions()
 
    dbmanage.populate_default_permissions()
 
    Session().commit()
 
    Session.commit()
 
    # PART TWO make test repo
 
    log.debug('making test vcs repositories')
 

	
 
    idx_path = config['app_conf']['index_dir']
 
    data_path = config['app_conf']['cache_dir']
 

	
rhodecode/model/__init__.py
Show inline comments
 
@@ -68,13 +68,13 @@ class BaseModel(object):
 
    """
 

	
 
    def __init__(self, sa=None):
 
        if sa is not None:
 
            self.sa = sa
 
        else:
 
            self.sa = meta.Session()
 
            self.sa = meta.Session
 

	
 
    def _get_instance(self, cls, instance):
 
        """
 
        Get's instance of given cls using some simple lookup mechanism
 
        
 
        :param cls: class to fetch
rhodecode/model/db.py
Show inline comments
 
@@ -115,13 +115,13 @@ class BaseModel(object):
 
        for k in self._get_keys():
 
            if k in populate_dict:
 
                setattr(self, k, populate_dict[k])
 

	
 
    @classmethod
 
    def query(cls):
 
        return Session().query(cls)
 
        return Session.query(cls)
 

	
 
    @classmethod
 
    def get(cls, id_):
 
        if id_:
 
            return cls.query().get(id_)
 

	
 
@@ -129,13 +129,13 @@ class BaseModel(object):
 
    def getAll(cls):
 
        return cls.query().all()
 

	
 
    @classmethod
 
    def delete(cls, id_):
 
        obj = cls.query().get(id_)
 
        Session().delete(obj)
 
        Session.delete(obj)
 

	
 

	
 
class RhodeCodeSetting(Base, BaseModel):
 
    __tablename__ = 'rhodecode_settings'
 
    __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
 
    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
@@ -249,14 +249,13 @@ class RhodeCodeUi(Base, BaseModel):
 
        new_ui = cls.get_by_key(key).scalar() or cls()
 
        new_ui.ui_section = 'hooks'
 
        new_ui.ui_active = True
 
        new_ui.ui_key = key
 
        new_ui.ui_value = val
 

	
 
        Session().add(new_ui)
 
        Session().commit()
 
        Session.add(new_ui)
 

	
 

	
 
class User(Base, BaseModel):
 
    __tablename__ = 'users'
 
    __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
 
    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
@@ -332,16 +331,14 @@ class User(Base, BaseModel):
 
            q = q.options(FromCache("sql_cache_short",
 
                                    "get_api_key_%s" % email))
 
        return q.scalar()
 

	
 
    def update_lastlogin(self):
 
        """Update user lastlogin"""
 

	
 
        self.last_login = datetime.datetime.now()
 
        Session().add(self)
 
        Session().commit()
 
        Session.add(self)
 
        log.debug('updated user %s lastlogin', self.username)
 

	
 

	
 
class UserLog(Base, BaseModel):
 
    __tablename__ = 'user_logs'
 
    __table_args__ = {'extend_existing':True}
 
@@ -383,83 +380,20 @@ class UsersGroup(Base, BaseModel):
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
            q = q.options(FromCache("sql_cache_short",
 
                                    "get_user_%s" % group_name))
 
        return q.scalar()
 

	
 

	
 
    @classmethod
 
    def get(cls, users_group_id, cache=False):
 
        users_group = cls.query()
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                    "get_users_group_%s" % users_group_id))
 
        return users_group.get(users_group_id)
 

	
 
    @classmethod
 
    def create(cls, form_data):
 
        try:
 
            new_users_group = cls()
 
            for k, v in form_data.items():
 
                setattr(new_users_group, k, v)
 

	
 
            Session().add(new_users_group)
 
            Session().commit()
 
            return new_users_group
 
        except:
 
            log.error(traceback.format_exc())
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def update(cls, users_group_id, form_data):
 

	
 
        try:
 
            users_group = cls.get(users_group_id, cache=False)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    Session().flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            Session().add(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def delete(cls, users_group_id):
 
        try:
 

	
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group_id ==
 
                        users_group_id).all()
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 

	
 
            users_group = cls.get(users_group_id, cache=False)
 
            Session().delete(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session().rollback()
 
            raise
 

	
 
class UsersGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = {'extend_existing':True}
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
@@ -474,14 +408,14 @@ class UsersGroupMember(Base, BaseModel):
 

	
 
    @staticmethod
 
    def add_user_to_group(group, user):
 
        ugm = UsersGroupMember()
 
        ugm.users_group = group
 
        ugm.user = user
 
        Session().add(ugm)
 
        Session().commit()
 
        Session.add(ugm)
 
        Session.commit()
 
        return ugm
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
 

	
 
@@ -518,30 +452,30 @@ class Repository(Base, BaseModel):
 
    @classmethod
 
    def url_sep(cls):
 
        return '/'
 

	
 
    @classmethod
 
    def get_by_repo_name(cls, repo_name):
 
        q = Session().query(cls).filter(cls.repo_name == repo_name)
 
        q = Session.query(cls).filter(cls.repo_name == repo_name)
 
        q = q.options(joinedload(Repository.fork))\
 
                .options(joinedload(Repository.user))\
 
                .options(joinedload(Repository.group))
 
        return q.one()
 
        return q.scalar()
 

	
 
    @classmethod
 
    def get_repo_forks(cls, repo_id):
 
        return cls.query().filter(Repository.fork_id == repo_id)
 

	
 
    @classmethod
 
    def base_path(cls):
 
        """
 
        Returns base path when all repos are stored
 

	
 
        :param cls:
 
        """
 
        q = Session().query(RhodeCodeUi)\
 
        q = Session.query(RhodeCodeUi)\
 
            .filter(RhodeCodeUi.ui_key == cls.url_sep())
 
        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def just_name(self):
 
@@ -571,13 +505,13 @@ class Repository(Base, BaseModel):
 
    @LazyProperty
 
    def repo_path(self):
 
        """
 
        Returns base full path for that repository means where it actually
 
        exists on a filesystem
 
        """
 
        q = Session().query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
        q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
                                              Repository.url_sep())
 
        q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def repo_full_path(self):
 
@@ -848,13 +782,13 @@ class Permission(Base, BaseModel):
 
    @classmethod
 
    def get_by_key(cls, key):
 
        return cls.query().filter(cls.permission_name == key).scalar()
 

	
 
    @classmethod
 
    def get_default_perms(cls, default_user_id):
 
        q = Session().query(UserRepoToPerm, Repository, cls)\
 
        q = Session.query(UserRepoToPerm, Repository, cls)\
 
            .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
 
            .join((cls, UserRepoToPerm.permission_id == cls.permission_id))\
 
            .filter(UserRepoToPerm.user_id == default_user_id)
 

	
 
        return q.all()
 

	
 
@@ -874,13 +808,13 @@ class UserRepoToPerm(Base, BaseModel):
 
    @classmethod
 
    def create(cls, user, repository, permission):
 
        n = cls()
 
        n.user = user
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        Session.add(n)
 
        return n
 

	
 
    def __repr__(self):
 
        return '<user:%s => %s >' % (self.user, self.repository)
 

	
 
class UserToPerm(Base, BaseModel):
 
@@ -890,47 +824,12 @@ class UserToPerm(Base, BaseModel):
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 
    @classmethod
 
    def has_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        return cls.query().filter(cls.user_id == user_id)\
 
            .filter(cls.permission == perm).scalar() is not None
 

	
 
    @classmethod
 
    def grant_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.user_id = user_id
 
        new.permission = perm
 
        try:
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            obj = cls.query().filter(cls.user_id == user_id)\
 
                    .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session().rollback()
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), {'extend_existing':True})
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
@@ -944,13 +843,13 @@ class UsersGroupRepoToPerm(Base, BaseMod
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        Session.add(n)
 
        return n
 

	
 
    def __repr__(self):
 
        return '<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
@@ -960,51 +859,12 @@ class UsersGroupToPerm(Base, BaseModel):
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
    @classmethod
 
    def has_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        return cls.query().filter(cls.users_group_id ==
 
                                         users_group_id)\
 
                                         .filter(cls.permission == perm)\
 
                                         .scalar() is not None
 

	
 
    @classmethod
 
    def grant_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.users_group_id = users_group_id
 
        new.permission = perm
 
        try:
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            obj = cls.query().filter(cls.users_group_id == users_group_id)\
 
                .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session().rollback()
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'group_to_perm'
 
    __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
@@ -1100,39 +960,39 @@ class CacheInvalidation(Base, BaseModel)
 
        Mark this Cache key for invalidation
 
        
 
        :param key:
 
        """
 

	
 
        log.debug('marking %s for invalidation' % key)
 
        inv_obj = Session().query(cls)\
 
        inv_obj = Session.query(cls)\
 
            .filter(cls.cache_key == key).scalar()
 
        if inv_obj:
 
            inv_obj.cache_active = False
 
        else:
 
            log.debug('cache key not found in invalidation db -> creating one')
 
            inv_obj = CacheInvalidation(key)
 

	
 
        try:
 
            Session().add(inv_obj)
 
            Session().commit()
 
            Session.add(inv_obj)
 
            Session.commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            Session().rollback()
 
            Session.rollback()
 

	
 
    @classmethod
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 
        :param key:
 
        """
 
        inv_obj = CacheInvalidation.query()\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session().add(inv_obj)
 
        Session().commit()
 
        Session.add(inv_obj)
 
        Session.commit()
 

	
 

	
 
class ChangesetComment(Base, BaseModel):
 
    __tablename__ = 'changeset_comments'
 
    __table_args__ = ({'extend_existing':True},)
 
    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
 
@@ -1154,13 +1014,13 @@ class ChangesetComment(Base, BaseModel):
 
        Returns user associated with this changesetComment. ie those
 
        who actually commented
 
        
 
        :param cls:
 
        :param revision:
 
        """
 
        return Session().query(User)\
 
        return Session.query(User)\
 
                .filter(cls.revision == revision)\
 
                .join(ChangesetComment.author).all()
 

	
 

	
 
class Notification(Base, BaseModel):
 
    __tablename__ = 'notifications'
 
@@ -1200,13 +1060,13 @@ class Notification(Base, BaseModel):
 
        notification.created_on = datetime.datetime.now()
 

	
 
        for u in recipients:
 
            assoc = UserNotification()
 
            assoc.notification = notification
 
            u.notifications.append(assoc)
 
        Session().add(notification)
 
        Session.add(notification)
 
        return notification
 

	
 
    @property
 
    def description(self):
 
        from rhodecode.model.notification import NotificationModel
 
        return NotificationModel().make_description(self)
 
@@ -1223,13 +1083,13 @@ class UserNotification(Base, BaseModel):
 
    user = relationship('User', lazy="joined")
 
    notification = relationship('Notification', lazy="joined",
 
                            order_by=lambda:Notification.created_on.desc(),)
 

	
 
    def mark_as_read(self):
 
        self.read = True
 
        Session().add(self)
 
        Session.add(self)
 

	
 
class DbMigrateVersion(Base, BaseModel):
 
    __tablename__ = 'db_migrate_version'
 
    __table_args__ = {'extend_existing':True}
 
    repository_id = Column('repository_id', String(250), primary_key=True)
 
    repository_path = Column('repository_path', Text)
rhodecode/model/forms.py
Show inline comments
 
@@ -33,15 +33,13 @@ from pylons.i18n.translation import _
 
from webhelpers.pylonslib.secure_form import authentication_token
 

	
 
from rhodecode.config.routing import ADMIN_PREFIX
 
from rhodecode.lib.utils import repo_name_slug
 
from rhodecode.lib.auth import authenticate, get_crypt_password
 
from rhodecode.lib.exceptions import LdapImportError
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.db import User, UsersGroup, RepoGroup
 
from rhodecode.model.db import User, UsersGroup, RepoGroup, Repository
 
from rhodecode import BACKENDS
 

	
 
log = logging.getLogger(__name__)
 

	
 
#this is needed to translate the messages using _() in validators
 
class State_obj(object):
 
@@ -65,13 +63,13 @@ def ValidUsername(edit, old_data):
 
        def validate_python(self, value, state):
 
            if value in ['default', 'new_user']:
 
                raise formencode.Invalid(_('Invalid username'), value, state)
 
            #check if user is unique
 
            old_un = None
 
            if edit:
 
                old_un = UserModel().get(old_data.get('user_id')).username
 
                old_un = User.get(old_data.get('user_id')).username
 

	
 
            if old_un != value or not edit:
 
                if User.get_by_username(value, case_insensitive=True):
 
                    raise formencode.Invalid(_('This username already '
 
                                               'exists') , value, state)
 

	
 
@@ -265,26 +263,26 @@ def ValidRepoName(edit, old_data):
 
            value['repo_name_full'] = repo_name_full
 
            rename = old_data.get('repo_name') != repo_name_full
 
            create = not edit
 
            if  rename or create:
 

	
 
                if group_path != '':
 
                    if RepoModel().get_by_repo_name(repo_name_full,):
 
                    if Repository.get_by_repo_name(repo_name_full):
 
                        e_dict = {'repo_name':_('This repository already '
 
                                                'exists in a group "%s"') %
 
                                  gr.group_name}
 
                        raise formencode.Invalid('', value, state,
 
                                                 error_dict=e_dict)
 
                elif RepoGroup.get_by_group_name(repo_name_full):
 
                        e_dict = {'repo_name':_('There is a group with this'
 
                                                ' name already "%s"') %
 
                                  repo_name_full}
 
                        raise formencode.Invalid('', value, state,
 
                                                 error_dict=e_dict)
 

	
 
                elif RepoModel().get_by_repo_name(repo_name_full):
 
                elif Repository.get_by_repo_name(repo_name_full):
 
                        e_dict = {'repo_name':_('This repository '
 
                                                'already exists')}
 
                        raise formencode.Invalid('', value, state,
 
                                                 error_dict=e_dict)
 

	
 
            return value
rhodecode/model/repo.py
Show inline comments
 
@@ -201,17 +201,15 @@ class RepoModel(BaseModel):
 
            self.sa.add(cur_repo)
 

	
 
            if repo_name != new_name:
 
                # rename repository
 
                self.__rename_repo(old=repo_name, new=new_name)
 

	
 
            self.sa.commit()
 
            return cur_repo
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def create(self, form_data, cur_user, just_db=False, fork=False):
 
        from rhodecode.model.scm import ScmModel
 

	
 
        try:
 
@@ -309,43 +307,37 @@ class RepoModel(BaseModel):
 
        run_task(tasks.create_repo_fork, form_data, cur_user)
 

	
 
    def delete(self, repo):
 
        try:
 
            self.sa.delete(repo)
 
            self.__delete_repo(repo)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_user(self, form_data, repo_name):
 
        try:
 
            obj = self.sa.query(UserRepoToPerm)\
 
                .filter(UserRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UserRepoToPerm.user_id == form_data['user_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_users_group(self, form_data, repo_name):
 
        try:
 
            obj = self.sa.query(UsersGroupRepoToPerm)\
 
                .filter(UsersGroupRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UsersGroupRepoToPerm.users_group_id
 
                        == form_data['users_group_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_stats(self, repo_name):
 
        """
 
        removes stats for given repo
 
        
 
@@ -353,16 +345,14 @@ class RepoModel(BaseModel):
 
        """
 
        try:
 
            obj = self.sa.query(Statistics)\
 
                    .filter(Statistics.repository == \
 
                        self.get_by_repo_name(repo_name)).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def __create_repo(self, repo_name, alias, new_parent_id, clone_uri=False):
 
        """
 
        makes repository on filesystem. It's group aware means it'll create
 
        a repository within a group, and alter the paths accordingly of
rhodecode/model/user.py
Show inline comments
 
@@ -51,12 +51,15 @@ PERM_WEIGHTS = {'repository.none': 0,
 
                'repository.write': 3,
 
                'repository.admin': 3}
 

	
 

	
 
class UserModel(BaseModel):
 

	
 
    def __get_user(self, user):
 
        return self._get_instance(User, user)
 

	
 
    def get(self, user_id, cache=False):
 
        user = self.sa.query(User)
 
        if cache:
 
            user = user.options(FromCache("sql_cache_short",
 
                                          "get_user_%s" % user_id))
 
        return user.get(user_id)
 
@@ -81,17 +84,15 @@ class UserModel(BaseModel):
 
            new_user = User()
 
            for k, v in form_data.items():
 
                setattr(new_user, k, v)
 

	
 
            new_user.api_key = generate_api_key(form_data['username'])
 
            self.sa.add(new_user)
 
            self.sa.commit()
 
            return new_user
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 

	
 
    def create_or_update(self, username, password, email, name, lastname,
 
                         active=True, admin=False, ldap_dn=None):
 
        """
 
@@ -156,13 +157,12 @@ class UserModel(BaseModel):
 
                new_user.email = attrs['email']
 
                new_user.active = attrs.get('active', True)
 
                new_user.name = attrs['name'] or generate_email(username)
 
                new_user.lastname = attrs['lastname']
 

	
 
                self.sa.add(new_user)
 
                self.sa.commit()
 
                return new_user
 
            except (DatabaseError,):
 
                log.error(traceback.format_exc())
 
                self.sa.rollback()
 
                raise
 
        log.debug('User %s already exists. Skipping creation of account'
 
@@ -197,13 +197,12 @@ class UserModel(BaseModel):
 
                new_user.active = attrs.get('active', True)
 
                new_user.ldap_dn = safe_unicode(user_dn)
 
                new_user.name = attrs['name']
 
                new_user.lastname = attrs['lastname']
 

	
 
                self.sa.add(new_user)
 
                self.sa.commit()
 
                return new_user
 
            except (DatabaseError,):
 
                log.error(traceback.format_exc())
 
                self.sa.rollback()
 
                raise
 
        log.debug('this %s user exists skipping creation of ldap account',
 
@@ -255,16 +254,14 @@ class UserModel(BaseModel):
 
                    user.password = v
 
                    user.api_key = generate_api_key(user.username)
 
                else:
 
                    setattr(user, k, v)
 

	
 
            self.sa.add(user)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def update_my_account(self, user_id, form_data):
 
        try:
 
            user = self.get(user_id, cache=False)
 
            if user.username == 'default':
 
@@ -277,16 +274,14 @@ class UserModel(BaseModel):
 
                    user.api_key = generate_api_key(user.username)
 
                else:
 
                    if k not in ['admin', 'active']:
 
                        setattr(user, k, v)
 

	
 
            self.sa.add(user)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete(self, user_id):
 
        try:
 
            user = self.get(user_id, cache=False)
 
            if user.username == 'default':
 
@@ -297,16 +292,14 @@ class UserModel(BaseModel):
 
                raise UserOwnsReposException(_('This user still owns %s '
 
                                               'repositories and cannot be '
 
                                               'removed. Switch owners or '
 
                                               'remove those repositories') \
 
                                               % user.repositories)
 
            self.sa.delete(user)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def reset_password_link(self, data):
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.send_password_link, data['email'])
 

	
 
@@ -474,6 +467,38 @@ class UserModel(BaseModel):
 
                if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm]:
 
                    user.permissions['repositories'][perm.UsersGroupRepoToPerm.
 
                                                     repository.repo_name] = p
 

	
 
        return user
 

	
 

	
 

	
 
    def has_perm(self, user, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        user = self.__get_user(user)
 

	
 
        return UserToPerm.query().filter(UserToPerm.user == user.user)\
 
            .filter(UserToPerm.permission == perm).scalar() is not None
 

	
 
    def grant_perm(self, user, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        user = self.__get_user(user)
 

	
 
        new = UserToPerm()
 
        new.user = user.user
 
        new.permission = perm
 
        self.sa.add(new)
 

	
 

	
 
    def revoke_perm(self, user, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 
        
 
        user = self.__get_user(user)
 
        
 
        obj = UserToPerm.query().filter(UserToPerm.user == user.user)\
 
                .filter(UserToPerm.permission == perm).one()
 
        self.sa.delete(obj)
rhodecode/model/users_group.py
Show inline comments
 
@@ -24,13 +24,15 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 

	
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import UsersGroupMember, UsersGroup
 
from rhodecode.model.db import UsersGroupMember, UsersGroup,\
 
    UsersGroupRepoToPerm, Permission, UsersGroupToPerm
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersGroupModel(BaseModel):
 

	
 
@@ -41,21 +43,61 @@ class UsersGroupModel(BaseModel):
 
        return UsersGroup.get(users_group_id)
 

	
 
    def get_by_name(self, name, cache=False, case_insensitive=False):
 
        return UsersGroup.get_by_group_name(name, cache, case_insensitive)
 

	
 
    def create(self, name, active=True):
 
        try:
 
        new = UsersGroup()
 
        new.users_group_name = name
 
        new.users_group_active = active
 
        self.sa.add(new)
 
        return new
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def update(self, users_group, form_data):
 

	
 
        try:
 
            users_group = self.__get_users_group(users_group)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    self.sa.flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group.users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            self.sa.add(users_group)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete(self, users_group):
 
        obj = self.__get_users_group(users_group)
 
        self.sa.delete(obj)
 
        try:
 
            users_group = self.__get_users_group(users_group)
 
            
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group == users_group).all()
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 
            
 
            self.sa.delete(users_group)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def add_user_to_group(self, users_group, user):
 
        for m in users_group.members:
 
            u = m.user
 
            if u.user_id == user.user_id:
 
                return m
 
@@ -70,6 +112,41 @@ class UsersGroupModel(BaseModel):
 

	
 
            self.sa.add(users_group_member)
 
            return users_group_member
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def has_perm(self, users_group, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        users_group = self.__get_users_group(users_group)
 

	
 
        return UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm).scalar() is not None
 

	
 
    def grant_perm(self, users_group, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        users_group = self.__get_users_group(users_group)
 

	
 
        new = UsersGroupToPerm()
 
        new.users_group = users_group
 
        new.permission = perm
 
        self.sa.add(new)
 

	
 

	
 
    def revoke_perm(self, users_group, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 
        
 
        users_group = self.__get_users_group(users_group)
 
        
 
        obj = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm).one()
 
        self.sa.delete(obj)
 

	
 

	
rhodecode/templates/files/files.html
Show inline comments
 
@@ -36,13 +36,13 @@
 
		</div>    
 
    </div>
 
</div>    
 
<script type="text/javascript">
 
var YPJAX_TITLE = "${c.repo_name} ${_('Files')} - ${c.rhodecode_name}";
 
var current_url = "${h.url.current()}";
 
var node_list_url = '${h.url("files_home",repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.file.path)}';
 
var node_list_url = '${h.url("files_home",repo_name=c.repo_name,revision=c.changeset.raw_id,f_path='__FPATH__')}';
 
var url_base = '${h.url("files_nodelist_home",repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.file.path)}';
 
var truncated_lbl = "${_('search truncated')}";
 
var nomatch_lbl = "${_('no matching files')}";
 
fileBrowserListeners(current_url, node_list_url, url_base, truncated_lbl, nomatch_lbl);
 
</script>
 
</%def>
 
\ No newline at end of file
rhodecode/tests/_test_concurency.py
Show inline comments
 
@@ -78,13 +78,13 @@ class Command(object):
 
            print stdout, stderr
 
        return stdout, stderr
 

	
 
def get_session():
 
    engine = engine_from_config(conf, 'sqlalchemy.db1.')
 
    init_model(engine)
 
    sa = meta.Session()
 
    sa = meta.Session
 
    return sa
 

	
 

	
 
def create_test_user(force=True):
 
    print 'creating test user'
 
    sa = get_session()
rhodecode/tests/functional/test_admin_notifications.py
Show inline comments
 
@@ -8,14 +8,14 @@ from rhodecode.model.meta import Session
 
class TestNotificationsController(TestController):
 

	
 

	
 
    def tearDown(self):
 
        for n in Notification.query().all():
 
            inst = Notification.get(n.notification_id)
 
            Session().delete(inst)
 
        Session().commit()
 
            Session.delete(inst)
 
        Session.commit()
 

	
 
    def test_index(self):
 
        self.log_user()
 

	
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
@@ -27,13 +27,13 @@ class TestNotificationsController(TestCo
 

	
 
        cur_user = self._get_logged_user()
 

	
 
        NotificationModel().create(created_by=u1, subject=u'test_notification_1',
 
                                   body=u'notification_1',
 
                                   recipients=[cur_user])
 
        Session().commit()
 
        Session.commit()
 
        response = self.app.get(url('notifications'))
 
        self.assertTrue(u'test_notification_1' in response.body)
 

	
 
#    def test_index_as_xml(self):
 
#        response = self.app.get(url('formatted_notifications', format='xml'))
 
#
 
@@ -65,13 +65,13 @@ class TestNotificationsController(TestCo
 

	
 
        # make notifications
 
        notification = NotificationModel().create(created_by=cur_user,
 
                                                  subject=u'test',
 
                                                  body=u'hi there',
 
                                                  recipients=[cur_user, u1, u2])
 
        Session().commit()
 
        Session.commit()
 
        u1 = User.get(u1.user_id)
 
        u2 = User.get(u2.user_id)
 

	
 
        # check DB
 
        get_notif = lambda un:[x.notification for x in un]
 
        self.assertEqual(get_notif(cur_user.notifications), [notification])
rhodecode/tests/functional/test_admin_repos.py
Show inline comments
 
@@ -29,17 +29,16 @@ class TestAdminReposController(TestContr
 
        response = self.app.post(url('repos'), {'repo_name':repo_name,
 
                                                'repo_type':'hg',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 

	
 
        self.checkSessionFlash(response, 'created repository %s' % (repo_name))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session.query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
@@ -70,13 +69,13 @@ class TestAdminReposController(TestContr
 
                                                'description':description,
 
                                                'private':private})
 
        self.checkSessionFlash(response,
 
                               'created repository %s' % (repo_name_unicode))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session.query(Repository).filter(Repository.repo_name ==
 
                                                repo_name_unicode).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name_unicode)
 
        self.assertEqual(new_repo.description, description_unicode)
 

	
 
        #test if repository is visible in the list ?
 
@@ -110,13 +109,13 @@ class TestAdminReposController(TestContr
 

	
 

	
 
        #test if we have a message for that repository
 
        assert '''created repository %s''' % (repo_name) in response.session['flash'][0], 'No flash message about new repo'
 

	
 
        #test if the fork was created in the database
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name == repo_name).one()
 
        new_repo = self.Session.query(Repository).filter(Repository.repo_name == repo_name).one()
 

	
 
        assert new_repo.repo_name == repo_name, 'wrong name of repo name in db'
 
        assert new_repo.description == description, 'wrong description'
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 
@@ -159,13 +158,13 @@ class TestAdminReposController(TestContr
 

	
 
        #test if we have a message for that repository
 
        self.assertTrue('''created repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session.query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
@@ -179,13 +178,13 @@ class TestAdminReposController(TestContr
 
        self.assertTrue('''deleted repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        response.follow()
 

	
 
        #check if repo was deleted from db
 
        deleted_repo = self.Session().query(Repository).filter(Repository.repo_name
 
        deleted_repo = self.Session.query(Repository).filter(Repository.repo_name
 
                                                        == repo_name).scalar()
 

	
 
        self.assertEqual(deleted_repo, None)
 

	
 

	
 
    def test_delete_repo_with_group(self):
rhodecode/tests/functional/test_admin_settings.py
Show inline comments
 
@@ -142,13 +142,13 @@ class TestAdminSettingsController(TestCo
 
                                             name=new_name,
 
                                             lastname=new_lastname,
 
                                             email=new_email,))
 
        response.follow()
 

	
 
        assert 'Your account was updated successfully' in response.session['flash'][0][1], 'no flash message about success of change'
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session.query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == new_email , 'incorrect user email after update got %s vs %s' % (user.email, new_email)
 
        assert user.name == new_name, 'updated field mismatch %s vs %s' % (user.name, new_name)
 
        assert user.lastname == new_lastname, 'updated field mismatch %s vs %s' % (user.lastname, new_lastname)
 
        assert check_password(new_password, user.password) is True, 'password field mismatch %s vs %s' % (user.password, new_password)
 

	
 
        #bring back the admin settings
 
@@ -168,13 +168,13 @@ class TestAdminSettingsController(TestCo
 
                                                            email=old_email,))
 

	
 
        response.follow()
 
        self.checkSessionFlash(response,
 
                               'Your account was updated successfully')
 

	
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session.query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 

	
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 
        assert user.name == old_name, 'updated field mismatch %s vs %s' % (user.name, old_name)
 
        assert user.lastname == old_lastname, 'updated field mismatch %s vs %s' % (user.lastname, old_lastname)
 
        assert check_password(old_password, user.password) is True , 'password updated field mismatch %s vs %s' % (user.password, old_password)
rhodecode/tests/functional/test_admin_users.py
Show inline comments
 
@@ -29,13 +29,13 @@ class TestAdminUsersController(TestContr
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 

	
 
        assert '''created user %s''' % (username) in response.session['flash'][0], 'No flash message about new user'
 

	
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 
        new_user = self.Session.query(User).filter(User.username == username).one()
 

	
 

	
 
        assert new_user.username == username, 'wrong info about username'
 
        assert check_password(password, new_user.password) == True , 'wrong info about password'
 
        assert new_user.name == name, 'wrong info about name'
 
        assert new_user.lastname == lastname, 'wrong info about lastname'
 
@@ -63,13 +63,13 @@ class TestAdminUsersController(TestContr
 

	
 
        assert """<span class="error-message">Invalid username</span>""" in response.body
 
        assert """<span class="error-message">Please enter a value</span>""" in response.body
 
        assert """<span class="error-message">An email address must contain a single @</span>""" in response.body
 

	
 
        def get_user():
 
            self.Session().query(User).filter(User.username == username).one()
 
            self.Session.query(User).filter(User.username == username).one()
 

	
 
        self.assertRaises(NoResultFound, get_user), 'found user in database'
 

	
 
    def test_new(self):
 
        response = self.app.get(url('new_user'))
 

	
 
@@ -97,13 +97,13 @@ class TestAdminUsersController(TestContr
 
                                               'active':True,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 
        response = response.follow()
 

	
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 
        new_user = self.Session.query(User).filter(User.username == username).one()
 
        response = self.app.delete(url('user', id=new_user.user_id))
 

	
 
        assert """successfully deleted user""" in response.session['flash'][0], 'No info about user deletion'
 

	
 

	
 
    def test_delete_browser_fakeout(self):
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
@@ -20,16 +20,12 @@ class TestAdminUsersGroupsController(Tes
 
                                  'active':True})
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % TEST_USERS_GROUP)
 

	
 

	
 

	
 

	
 

	
 
    def test_new(self):
 
        response = self.app.get(url('new_users_group'))
 

	
 
    def test_new_as_xml(self):
 
        response = self.app.get(url('formatted_new_users_group', format='xml'))
 

	
 
@@ -49,19 +45,19 @@ class TestAdminUsersGroupsController(Tes
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 

	
 

	
 
        gr = self.Session().query(UsersGroup)\
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).one()
 

	
 
        response = self.app.delete(url('users_group', id=gr.users_group_id))
 

	
 
        gr = self.Session().query(UsersGroup)\
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 

	
 

	
rhodecode/tests/functional/test_changeset_comments.py
Show inline comments
 
@@ -3,27 +3,27 @@ from rhodecode.model.db import Changeset
 
    UserNotification
 

	
 
class TestChangeSetCommentrController(TestController):
 

	
 
    def setUp(self):
 
        for x in ChangesetComment.query().all():
 
            self.Session().delete(x)
 
        self.Session().commit()
 
            self.Session.delete(x)
 
        self.Session.commit()
 

	
 
        for x in Notification.query().all():
 
            self.Session().delete(x)
 
        self.Session().commit()
 
            self.Session.delete(x)
 
        self.Session.commit()
 

	
 
    def tearDown(self):
 
        for x in ChangesetComment.query().all():
 
            self.Session().delete(x)
 
        self.Session().commit()
 
            self.Session.delete(x)
 
        self.Session.commit()
 

	
 
        for x in Notification.query().all():
 
            self.Session().delete(x)
 
        self.Session().commit()
 
            self.Session.delete(x)
 
        self.Session.commit()
 

	
 
    def test_create(self):
 
        self.log_user()
 
        rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc'
 
        text = u'CommentOnRevision'
 

	
rhodecode/tests/functional/test_files.py
Show inline comments
 
@@ -308,6 +308,19 @@ removed extra unicode conversion in diff
 
        response = self.app.get(url(controller='files', action='raw',
 
                                    repo_name=HG_REPO,
 
                                    revision=rev,
 
                                    f_path=f_path))
 

	
 
        assert "There is no file nor directory at the given path: %r at revision %r" % (f_path, rev[:12]) in response.session['flash'][0][1], 'No flash message'
 

	
 
    def test_ajaxed_files_list(self):
 
        self.log_user()
 
        rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc' 
 
        response = self.app.get(url('files_nodelist_home',repo_name=HG_REPO,
 
                                    f_path='/',
 
                                    revision=rev),
 
                                extra_environ={'HTTP_X_PARTIAL_XHR':'1'},
 
                                )
 
        self.assertTrue("vcs/web/simplevcs/views/repository.py" in response.body)
 

	
 

	
 

	
rhodecode/tests/functional/test_forks.py
Show inline comments
 
@@ -62,13 +62,13 @@ class TestForksController(TestController
 

	
 
        #test if we have a message that fork is ok
 
        self.assertTrue('forked %s repository as %s' \
 
                      % (repo_name, fork_name) in response.session['flash'][0])
 

	
 
        #test if the fork was created in the database
 
        fork_repo = self.Session().query(Repository)\
 
        fork_repo = self.Session.query(Repository)\
 
            .filter(Repository.repo_name == fork_name).one()
 

	
 
        self.assertEqual(fork_repo.repo_name, fork_name)
 
        self.assertEqual(fork_repo.fork.repo_name, repo_name)
 

	
 

	
rhodecode/tests/functional/test_journal.py
Show inline comments
 
@@ -13,16 +13,16 @@ class TestJournalController(TestControll
 
        assert """ <span id="follow_toggle_1" class="following" title="Stop following this repository""" in response.body, 'no info about stop follwoing repo id 1'
 

	
 
        assert """<div class="journal_day">%s</div>""" % datetime.date.today() in response.body, 'no info about action journal day'
 

	
 
    def test_stop_following_repository(self):
 
        session = self.log_user()
 
#        usr = self.Session().query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.Session().query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#        usr = self.Session.query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.Session.query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#
 
#        followings = self.Session().query(UserFollowing)\
 
#        followings = self.Session.query(UserFollowing)\
 
#            .filter(UserFollowing.user == usr)\
 
#            .filter(UserFollowing.follows_repository == repo).all()
 
#
 
#        assert len(followings) == 1, 'Not following any repository'
 
#
 
#        response = self.app.post(url(controller='journal',
rhodecode/tests/functional/test_login.py
Show inline comments
 
@@ -6,15 +6,15 @@ from rhodecode.lib.auth import check_pas
 
from rhodecode.model.meta import Session
 

	
 
class TestLoginController(TestController):
 

	
 
    def tearDown(self):
 
        for n in Notification.query().all():
 
            Session().delete(n)
 
            Session.delete(n)
 

	
 
        Session().commit()
 
        Session.commit()
 
        self.assertEqual(Notification.query().all(), [])
 

	
 
    def test_index(self):
 
        response = self.app.get(url(controller='login', action='index'))
 
        self.assertEqual(response.status, '200 OK')
 
        # Test response...
 
@@ -196,13 +196,13 @@ class TestLoginController(TestController
 
                                             'email':email,
 
                                             'name':name,
 
                                             'lastname':lastname})
 
        self.assertEqual(response.status , '302 Found')
 
        assert 'You have successfully registered into rhodecode' in response.session['flash'][0], 'No flash message about user registration'
 

	
 
        ret = self.Session().query(User).filter(User.username == 'test_regular4').one()
 
        ret = self.Session.query(User).filter(User.username == 'test_regular4').one()
 
        assert ret.username == username , 'field mismatch %s %s' % (ret.username, username)
 
        assert check_password(password, ret.password) == True , 'password mismatch'
 
        assert ret.email == email , 'field mismatch %s %s' % (ret.email, email)
 
        assert ret.name == name , 'field mismatch %s %s' % (ret.name, name)
 
        assert ret.lastname == lastname , 'field mismatch %s %s' % (ret.lastname, lastname)
 

	
 
@@ -228,14 +228,14 @@ class TestLoginController(TestController
 
        new.username = username
 
        new.password = password
 
        new.email = email
 
        new.name = name
 
        new.lastname = lastname
 
        new.api_key = generate_api_key(username)
 
        self.Session().add(new)
 
        self.Session().commit()
 
        self.Session.add(new)
 
        self.Session.commit()
 

	
 
        response = self.app.post(url(controller='login',
 
                                     action='password_reset'),
 
                                 {'email':email, })
 

	
 
        self.checkSessionFlash(response, 'Your password reset link was sent')
rhodecode/tests/functional/test_summary.py
Show inline comments
 
@@ -34,14 +34,14 @@ class TestSummaryController(TestControll
 
                        """"Makefile"]}, "cfg": {"count": 1, "desc": ["Ini"]},"""
 
                        """ "css": {"count": 1, "desc": ["Css"]}, "bat": """
 
                        """{"count": 1, "desc": ["Batch"]}};"""
 
                        in response.body)
 

	
 
        # clone url...
 
        self.assertTrue("""<input type="text" id="clone_url" readonly="readonly" value="hg clone http://test_admin@localhost:80/%s" size="70"/>""" % HG_REPO in response.body)
 
        self.assertTrue("""<input type="text" id="clone_url" readonly="readonly" value="http://test_admin@localhost:80/%s" size="70"/>""" % HG_REPO in response.body)
 

	
 

	
 
    def _enable_stats(self):
 
        r = Repository.get_by_repo_name(HG_REPO)
 
        r.enable_statistics = True
 
        self.Session().add(r)
 
        self.Session().commit()
 
        self.Session.add(r)
 
        self.Session.commit()
rhodecode/tests/test_models.py
Show inline comments
 
@@ -63,13 +63,13 @@ class TestReposGroups(unittest.TestCase)
 

	
 
        self.assertTrue(self.__check_path('newGroup'))
 

	
 

	
 
    def test_create_same_name_group(self):
 
        self.assertRaises(IntegrityError, lambda:self.__make_group('newGroup'))
 
        Session().rollback()
 
        Session.rollback()
 

	
 
    def test_same_subgroup(self):
 
        sg1 = self.__make_group('sub1', parent_id=self.g1.group_id)
 
        self.assertEqual(sg1.parent_group, self.g1)
 
        self.assertEqual(sg1.full_path, 'test1/sub1')
 
        self.assertTrue(self.__check_path('test1', 'sub1'))
 
@@ -160,26 +160,26 @@ class TestReposGroups(unittest.TestCase)
 
class TestUser(unittest.TestCase):
 

	
 
    def test_create_and_remove(self):
 
        usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe',
 
                                     email=u'u232@rhodecode.org',
 
                                     name=u'u1', lastname=u'u1')
 
        Session().commit()
 
        Session.commit()
 
        self.assertEqual(User.get_by_username(u'test_user'), usr)
 

	
 
        # make users group
 
        users_group = UsersGroupModel().create('some_example_group')
 
        Session().commit()
 
        Session.commit()
 

	
 
        UsersGroupModel().add_user_to_group(users_group, usr)
 
        Session().commit()
 
        Session.commit()
 

	
 
        self.assertEqual(UsersGroup.get(users_group.users_group_id), users_group)
 
        self.assertEqual(UsersGroupMember.query().count(), 1)
 
        UserModel().delete(usr.user_id)
 
        Session().commit()
 
        Session.commit()
 

	
 
        self.assertEqual(UsersGroupMember.query().all(), [])
 

	
 

	
 
class TestNotifications(unittest.TestCase):
 

	
 
@@ -206,27 +206,27 @@ class TestNotifications(unittest.TestCas
 
        self.u3 = self.u3.user_id
 

	
 
        super(TestNotifications, self).__init__(methodName=methodName)
 

	
 
    def _clean_notifications(self):
 
        for n in Notification.query().all():
 
            Session().delete(n)
 
            Session.delete(n)
 

	
 
        Session().commit()
 
        Session.commit()
 
        self.assertEqual(Notification.query().all(), [])
 

	
 

	
 
    def test_create_notification(self):
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        usrs = [self.u1, self.u2]
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'subj', body=u'hi there',
 
                                           recipients=usrs)
 
        Session().commit()
 
        Session.commit()
 
        u1 = User.get(self.u1)
 
        u2 = User.get(self.u2)
 
        u3 = User.get(self.u3)
 
        notifications = Notification.query().all()
 
        self.assertEqual(len(notifications), 1)
 

	
 
@@ -245,36 +245,36 @@ class TestNotifications(unittest.TestCas
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification1 = NotificationModel().create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there1',
 
                                            recipients=[self.u3])
 
        Session().commit()
 
        Session.commit()
 
        notification2 = NotificationModel().create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there2',
 
                                            recipients=[self.u3])
 
        Session().commit()
 
        u3 = Session().query(User).get(self.u3)
 
        Session.commit()
 
        u3 = Session.query(User).get(self.u3)
 

	
 
        self.assertEqual(sorted([x.notification for x in u3.notifications]),
 
                         sorted([notification2, notification1]))
 
        self._clean_notifications()
 

	
 
    def test_delete_notifications(self):
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session().commit()
 
        Session.commit()
 
        notifications = Notification.query().all()
 
        self.assertTrue(notification in notifications)
 

	
 
        Notification.delete(notification.notification_id)
 
        Session().commit()
 
        Session.commit()
 

	
 
        notifications = Notification.query().all()
 
        self.assertFalse(notification in notifications)
 

	
 
        un = UserNotification.query().filter(UserNotification.notification
 
                                             == notification).all()
 
@@ -287,25 +287,25 @@ class TestNotifications(unittest.TestCas
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session().commit()
 
        Session.commit()
 

	
 
        unotification = UserNotification.query()\
 
                            .filter(UserNotification.notification ==
 
                                    notification)\
 
                            .filter(UserNotification.user_id == self.u3)\
 
                            .scalar()
 

	
 
        self.assertEqual(unotification.user_id, self.u3)
 

	
 
        NotificationModel().delete(self.u3,
 
                                   notification.notification_id)
 
        Session().commit()
 
        Session.commit()
 

	
 
        u3notification = UserNotification.query()\
 
                            .filter(UserNotification.notification ==
 
                                    notification)\
 
                            .filter(UserNotification.user_id == self.u3)\
 
                            .scalar()
 
@@ -336,25 +336,25 @@ class TestNotifications(unittest.TestCas
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        NotificationModel().create(created_by=self.u1,
 
                            subject=u'title', body=u'hi there_delete',
 
                            recipients=[self.u3, self.u1])
 
        Session().commit()
 
        Session.commit()
 

	
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u1), 1)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u2), 0)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u3), 1)
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session().commit()
 
        Session.commit()
 

	
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u1), 2)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u2), 1)
 
        self.assertEqual(NotificationModel()
rhodecode/websetup.py
Show inline comments
 
@@ -43,8 +43,8 @@ def setup_app(command, conf, vars):
 
    dbmanage.set_db_version()
 
    dbmanage.create_settings(dbmanage.config_prompt(None))
 
    dbmanage.create_default_user()
 
    dbmanage.admin_prompt()
 
    dbmanage.create_permissions()
 
    dbmanage.populate_default_permissions()
 
    Session().commit()
 
    Session.commit()
 
    load_environment(conf.global_conf, conf.local_conf, initial=True)
0 comments (0 inline, 0 general)