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 312 insertions and 339 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/permissions.py
Show inline comments
 
@@ -93,25 +93,25 @@ class PermissionsController(BaseControll
 
        # url('permission', id=ID)
 

	
 
        permission_model = PermissionModel()
 

	
 
        _form = DefaultPermissionsForm([x[0] for x in self.perms_choices],
 
                                       [x[0] for x in self.register_choices],
 
                                       [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
 
            c.create_choices = self.create_choices
 
            defaults = errors.value
 

	
 
            return htmlfill.render(
 
                render('admin/permissions/permissions.html'),
 
                defaults=defaults,
rhodecode/controllers/admin/repos.py
Show inline comments
 
@@ -141,25 +141,25 @@ class ReposController(BaseController):
 
                    category='success')
 
            else:
 
                h.flash(_('created repository %s') % form_result['repo_name'],
 
                    category='success')
 

	
 
            if request.POST.get('user_created'):
 
                # 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')
 
            else:
 
                r = render('admin/repos/repo_add.html')
 

	
 
            return htmlfill.render(
 
                r,
 
                defaults=errors.value,
 
@@ -199,25 +199,25 @@ class ReposController(BaseController):
 
        changed_name = repo_name
 
        _form = RepoForm(edit=True, old_data={'repo_name': repo_name},
 
                         repo_groups=c.repo_groups_choices)()
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 
            repo = repo_model.update(repo_name, form_result)
 
            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,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
@@ -243,25 +243,25 @@ class ReposController(BaseController):
 
                      ' it was moved or renamed  from the filesystem'
 
                      ' please run the application again'
 
                      ' in order to rescan repositories') % repo_name,
 
                      category='error')
 

	
 
            return redirect(url('repos'))
 
        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')
 
            else:
 
                log.error(traceback.format_exc())
 
                h.flash(_('An error occurred during '
 
                          'deletion of %s') % repo_name,
 
                        category='error')
 

	
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
@@ -62,25 +62,25 @@ class ReposGroupsController(BaseControll
 
        return render('admin/repos_groups/repos_groups_show.html')
 

	
 
    @HasPermissionAnyDecorator('hg.admin')
 
    def create(self):
 
        """POST /repos_groups: Create a new item"""
 
        # url('repos_groups')
 
        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(
 
                render('admin/repos_groups/repos_groups_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
@@ -109,25 +109,25 @@ class ReposGroupsController(BaseControll
 
        # url('repos_group', id=ID)
 

	
 
        self.__load_defaults()
 
        c.repos_group = RepoGroup.get(id)
 

	
 
        repos_group_form = ReposGroupForm(edit=True,
 
                                          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(
 
                render('admin/repos_groups/repos_groups_edit.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
@@ -149,25 +149,25 @@ class ReposGroupsController(BaseControll
 
        # url('repos_group', id=ID)
 

	
 
        gr = RepoGroup.get(id)
 
        repos = gr.repositories.all()
 
        if repos:
 
            h.flash(_('This group contains %s repositores and cannot be '
 
                      '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 '
 
                          'subgroups'),
 
                        category='warning')
 
            else:
 
                log.error(traceback.format_exc())
 
                h.flash(_('error occurred during deletion of repos '
 
                          'group %s' % gr.group_name), category='error')
rhodecode/controllers/admin/settings.py
Show inline comments
 
@@ -39,24 +39,25 @@ from rhodecode.lib.auth import LoginRequ
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.lib.celerylib import tasks, run_task
 
from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
 
    set_rhodecode_config, repo_name_slug
 
from rhodecode.model.db import RhodeCodeUi, Repository, RepoGroup, \
 
    RhodeCodeSetting
 
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"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings',
 
    #         path_prefix='/admin', name_prefix='admin_')
 

	
 
    @LoginRequired()
 
@@ -238,25 +239,25 @@ class SettingsController(BaseController)
 
                    h.flash(_('Added new hook'),
 
                            category='success')
 

	
 
                # check for edits
 
                update = False
 
                _d = request.POST.dict_of_lists()
 
                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'))
 

	
 

	
 

	
 
        if setting_id == 'email':
 
            test_email = request.POST.get('test_email')
 
            test_email_subj = 'RhodeCode TestEmail'
 
@@ -344,25 +345,25 @@ class SettingsController(BaseController)
 
        # url('admin_settings_my_account_update', id=ID)
 
        user_model = UserModel()
 
        uid = self.rhodecode_user.user_id
 
        _form = UserForm(edit=True,
 
                         old_data={'user_id': uid,
 
                                   'email': self.rhodecode_user.email})()
 
        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()
 
            c.user_repos = ScmModel().get_repos(all_repos)
 

	
 
            return htmlfill.render(
 
                render('admin/users/user_edit_my_account.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
rhodecode/controllers/admin/users.py
Show inline comments
 
@@ -32,24 +32,25 @@ from pylons import request, session, tmp
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
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"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('user', 'users')
 

	
 
    @LoginRequired()
 
    @HasPermissionAllDecorator('hg.admin')
 
@@ -68,24 +69,25 @@ class UsersController(BaseController):
 

	
 
    def create(self):
 
        """POST /users: Create a new item"""
 
        # url('users')
 

	
 
        user_model = UserModel()
 
        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 {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during creation of user %s') \
 
                    % request.POST.get('username'), category='error')
 
@@ -105,29 +107,29 @@ class UsersController(BaseController):
 
        #           method='put')
 
        # url('user', id=ID)
 
        user_model = UserModel()
 
        c.user = user_model.get(id)
 

	
 
        _form = UserForm(edit=True, old_data={'user_id': id,
 
                                              '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")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during update of user %s') \
 
                    % form_result.get('username'), category='error')
 

	
 
        return redirect(url('users'))
 
@@ -135,73 +137,74 @@ class UsersController(BaseController):
 
    def delete(self, id):
 
        """DELETE /users/id: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # Or using helpers:
 
        #    h.form(url('delete_user', id=ID),
 
        #           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'))
 

	
 
    def show(self, id, format='html'):
 
        """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
 
        )
 

	
 
    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
 
@@ -24,30 +24,33 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 
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"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('users_group', 'users_groups')
 

	
 
    @LoginRequired()
 
    @HasPermissionAllDecorator('hg.admin')
 
@@ -61,28 +64,30 @@ class UsersGroupsController(BaseControll
 
        """GET /users_groups: All items in the collection"""
 
        # url('users_groups')
 
        c.users_groups_list = self.sa.query(UsersGroup).all()
 
        return render('admin/users_groups/users_groups.html')
 

	
 
    def create(self):
 
        """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,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during creation of users group %s') \
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
@@ -99,68 +104,72 @@ class UsersGroupsController(BaseControll
 
        #    <input type="hidden" name="_method" value="PUT" />
 
        # Or using helpers:
 
        #    h.form(url('users_group', id=ID),
 
        #           method='put')
 
        # url('users_group', id=ID)
 

	
 
        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,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during update of users group %s') \
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        return redirect(url('users_groups'))
 

	
 
    def delete(self, id):
 
        """DELETE /users_groups/id: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # 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'))
 

	
 
    def show(self, id, format='html'):
 
        """GET /users_groups/id: Show a specific item"""
 
        # url('users_group', id=ID)
 

	
 
    def edit(self, id, format='html'):
 
@@ -170,45 +179,46 @@ class UsersGroupsController(BaseControll
 
        c.users_group = self.sa.query(UsersGroup).get(id)
 
        if not c.users_group:
 
            return redirect(url('users_groups'))
 

	
 
        c.users_group.permissions = {}
 
        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()]
 
        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
 
        )
 

	
 
    def update_perm(self, id):
 
        """PUT /users_perm/id: Update an existing item"""
 
        # 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
 
@@ -111,25 +111,25 @@ class ApiController(JSONRPCController):
 
        :param email:
 
        :param active:
 
        :param admin:
 
        :param ldap_dn:
 
        """
 

	
 
        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')
 
    def get_users_group(self, apiuser, group_name):
 
        """"
 
        Get users group by name
 

	
 
        :param apiuser
 
        :param group_name
 
@@ -189,25 +189,25 @@ class ApiController(JSONRPCController):
 
        """
 
        Creates an new usergroup
 

	
 
        :param name:
 
        :param active:
 
        """
 

	
 
        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)
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def add_user_to_users_group(self, apiuser, group_name, user_name):
 
        """"
 
        Add a user to a group
 

	
 
        :param apiuser
 
@@ -217,44 +217,43 @@ class ApiController(JSONRPCController):
 

	
 
        try:
 
            users_group = UsersGroup.get_by_group_name(group_name)
 
            if not users_group:
 
                raise JSONRPCError('unknown users group %s' % group_name)
 

	
 
            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')
 

	
 
    @HasPermissionAnyDecorator('hg.admin')
 
    def get_repo(self, apiuser, repo_name):
 
        """"
 
        Get repository by name
 

	
 
        :param apiuser
 
        :param repo_name
 
        """
 

	
 
        try:
 
            repo = Repository.get_by_repo_name(repo_name)
 
        except NoResultFound:
 
            return None
 
        repo = Repository.get_by_repo_name(repo_name)
 
        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",
 
                                    id=user.user_id,
 
                                    username=user.username,
 
                                    firstname=user.name,
 
                                    lastname=user.lastname,
 
                                    email=user.email,
 
                                    active=user.active,
 
@@ -325,47 +324,46 @@ class ApiController(JSONRPCController):
 
                    group = ReposGroupModel().create(dict(group_name=g,
 
                                                  group_description='',
 
                                                  group_parent_id=parent_id))
 
                parent_id = group.group_id
 

	
 
            RepoModel().create(dict(repo_name=real_name,
 
                                     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):
 
        """
 
        Add permission for a user to a repository
 

	
 
        :param apiuser
 
        :param repo_name
 
        :param user_name
 
        :param perm
 
        """
 

	
 
        try:
 
            try:
 
                repo = Repository.get_by_repo_name(repo_name)
 
            except NoResultFound:
 
                raise JSONRPCError('unknown repository %s' % repo)
 
            repo = Repository.get_by_repo_name(repo_name)
 
            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
 
@@ -271,27 +271,27 @@ class ChangesetController(BaseRepoContro
 
        for x in c.changes:
 
            c.diffs += x[2]
 

	
 
        return render('changeset/raw_changeset.html')
 

	
 
    def comment(self, repo_name, revision):
 
        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
 
@@ -125,35 +125,35 @@ class JournalController(BaseController):
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def toggle_following(self):
 
        cur_token = request.POST.get('auth_token')
 
        token = h.get_token()
 
        if cur_token == token:
 

	
 
            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()
 

	
 
    @LoginRequired()
 
    def public_journal(self):
 
        # Return a rendered template
 
        p = int(request.params.get('page', 1))
 

	
rhodecode/controllers/login.py
Show inline comments
 
@@ -66,102 +66,98 @@ class LoginController(BaseController):
 
                # form checks for username/password, now we're authenticated
 
                username = c.form_result['username']
 
                user = User.get_by_username(username, case_insensitive=True)
 
                auth_user = AuthUser(user.user_id)
 
                auth_user.set_authenticated()
 
                cs = auth_user.get_cookie_store()
 
                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'))
 

	
 
            except formencode.Invalid, errors:
 
                return htmlfill.render(
 
                    render('/login.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    prefix_error=False,
 
                    encoding="UTF-8")
 

	
 
        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,
 
                    errors=errors.error_dict or {},
 
                    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(
 
                    render('/password_reset.html'),
 
                    defaults=errors.value,
 
                    errors=errors.error_dict or {},
 
                    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'))
 

	
 
        return redirect(url('login_home'))
 

	
 
    def logout(self):
 
        del session['rhodecode_user']
 
        session.save()
rhodecode/controllers/settings.py
Show inline comments
 
@@ -96,25 +96,25 @@ class SettingsController(BaseRepoControl
 
                                 old_data={'repo_name': repo_name},
 
                                 repo_groups=c.repo_groups_choices)()
 
        try:
 
            form_result = _form.to_python(dict(request.POST))
 

	
 
            repo_model.update(repo_name, form_result)
 
            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'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
@@ -140,19 +140,19 @@ class SettingsController(BaseRepoControl
 
                      ' it was moved or renamed  from the filesystem'
 
                      ' please run the application again'
 
                      ' in order to rescan repositories') % repo_name,
 
                      category='error')
 

	
 
            return redirect(url('home'))
 
        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
 
@@ -26,24 +26,25 @@ import random
 
import logging
 
import traceback
 
import hashlib
 

	
 
from tempfile import _RandomNameSequence
 
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
 

	
 
from rhodecode.lib import str2bool, safe_unicode
 
from rhodecode.lib.exceptions import LdapPasswordError, LdapUsernameError
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.lib.auth_ldap import AuthLdap
 

	
 
from rhodecode.model import meta
 
@@ -216,51 +217,53 @@ def authenticate(username, password):
 
                get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\
 
                                                           .get(k), [''])[0]
 

	
 
                user_attrs = {
 
                 'name': safe_unicode(get_ldap_attr('ldap_attr_firstname')),
 
                 'lastname': safe_unicode(get_ldap_attr('ldap_attr_lastname')),
 
                 'email': get_ldap_attr('ldap_attr_email'),
 
                }
 

	
 
                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
 

	
 
    if str2bool(config.get('container_auth_enabled', False)):
 
        from paste.httpheaders import REMOTE_USER
 
        username = REMOTE_USER(environ)
 

	
 
    if not username and str2bool(config.get('proxypass_auth_enabled', False)):
 
@@ -371,25 +374,25 @@ class  AuthUser(object):
 
def set_available_permissions(config):
 
    """
 
    This function will propagate pylons globals with all available defined
 
    permission given in db. We don't want to check each time from db for new
 
    permissions since adding a new permission also requires application restart
 
    ie. to decorate new views with the newly created permission
 

	
 
    :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()
 

	
 
    config['available_permissions'] = [x.permission_name for x in all_perms]
 

	
 

	
 
#==============================================================================
 
# CHECK DECORATORS
 
#==============================================================================
rhodecode/lib/base.py
Show inline comments
 
@@ -26,25 +26,25 @@ class BaseController(WSGIController):
 

	
 
    def __before__(self):
 
        c.rhodecode_version = __version__
 
        c.rhodecode_name = config.get('rhodecode_title')
 
        c.use_gravatar = str2bool(config.get('use_gravatar'))
 
        c.ga_code = config.get('rhodecode_ga_code')
 
        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
 
        # available in environ['pylons.routes_dict']
 
        start = time.time()
 
        try:
 
            # make sure that we update permissions each time we call controller
 
            api_key = request.GET.get('api_key')
 
            cookie_store = session.get('rhodecode_user') or {}
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -55,25 +55,25 @@ from rhodecode.model.db import Statistic
 
from sqlalchemy import engine_from_config
 

	
 
add_cache(config)
 

	
 
__all__ = ['whoosh_index', 'get_commits_stats',
 
           'reset_user_password', 'send_email']
 

	
 

	
 
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()
 
        except:
 
            log = logging.getLogger(__name__)
 
    else:
 
        log = logging.getLogger(__name__)
 

	
 
    return log
 
@@ -100,25 +100,29 @@ def get_commits_stats(repo_name, ts_min_
 
    lockkey_path = config['here']
 

	
 
    log.info('running task with lockkey %s', lockkey)
 
    try:
 
        sa = get_session()
 
        lock = l = DaemonLock(file_=jn(lockkey_path, lockkey))
 

	
 
        # 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
 

	
 
        skip_date_limit = True
 
        parse_limit = int(config['app_conf'].get('commit_parse_limit'))
 
        last_rev = 0
 
        last_cs = None
 
        timegetter = itemgetter('time')
 

	
rhodecode/lib/db_manage.py
Show inline comments
 
@@ -48,25 +48,25 @@ class DbManage(object):
 
    def __init__(self, log_sql, dbconf, root, tests=False):
 
        self.dbname = dbconf.split('/')[-1]
 
        self.tests = tests
 
        self.root = root
 
        self.dburi = dbconf
 
        self.log_sql = log_sql
 
        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")
 
        if self.tests:
 
            destroy = True
 
        else:
 
            destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
 
        if not destroy:
 
            sys.exit()
rhodecode/lib/dbmigrate/schema/db_1_2_0.py
Show inline comments
 
@@ -1052,47 +1052,47 @@ class CacheInvalidation(Base, BaseModel)
 
                .filter(CacheInvalidation.cache_active == False)\
 
                .scalar()
 

	
 
    @classmethod
 
    def set_invalidate(cls, key):
 
        """
 
        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()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 

	
 
    @classmethod
 
    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):
 
    __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)
 
    version = Column('version', Integer)
 

	
rhodecode/lib/utils.py
Show inline comments
 
@@ -101,25 +101,25 @@ def action_logger(user, action, repo, ip
 
    :param user: user that made this action, can be a unique username string or
 
        object containing user_id attribute
 
    :param action: action to log, should be on of predefined unique actions for
 
        easy translations
 
    :param repo: string name of repository or object containing repo_id,
 
        that action was made on
 
    :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)
 
        else:
 
            raise Exception('You have to provide user object or username')
 

	
 
        if hasattr(repo, 'repo_id'):
 
            repo_obj = Repository.get(repo.repo_id)
 
            repo_name = repo_obj.repo_name
 
@@ -262,25 +262,25 @@ def make_ui(read_from='file', path=None,
 
        if not os.path.isfile(path):
 
            log.warning('Unable to read config file %s' % path)
 
            return False
 
        log.debug('reading hgrc from %s', path)
 
        cfg = config.config()
 
        cfg.read(path)
 
        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:
 
            if ui_.ui_active:
 
                log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
 
                          ui_.ui_key, ui_.ui_value)
 
                baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)
 

	
 
        meta.Session.remove()
 
@@ -353,25 +353,25 @@ class EmptyChangeset(BaseChangeset):
 

	
 
    def get_file_size(self, path):
 
        return 0
 

	
 

	
 
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]
 

	
 
    for lvl, group_name in enumerate(groups):
 
        group_name = '/'.join(groups[:lvl] + [group_name])
 
        group = sa.query(RepoGroup).filter(RepoGroup.group_name == group_name).scalar()
 

	
 
        if group is None:
 
@@ -383,25 +383,25 @@ def map_groups(groups):
 

	
 

	
 
def repo2db_mapper(initial_repo_list, remove_obsolete=False):
 
    """
 
    maps all repos given in initial_repo_list, non existing repositories
 
    are created, if remove_obsolete is True it also check for db entries
 
    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 = []
 

	
 
    for name, repo in initial_repo_list.items():
 
        group = map_groups(name.split(Repository.url_sep()))
 
        if not rm.get_by_repo_name(name, cache=False):
 
            log.info('repository %s not found creating default', name)
 
            added.append(name)
 
            form_data = {
 
@@ -501,25 +501,25 @@ def create_test_env(repos_test_path, con
 
    if not os.path.isdir(repos_test_path):
 
        log.debug('Creating testdir %s' % repos_test_path)
 
        os.makedirs(repos_test_path)
 

	
 
    dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=config['here'],
 
                        tests=True)
 
    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']
 

	
 
    #clean index and data
 
    if idx_path and os.path.exists(idx_path):
 
        log.debug('remove %s' % idx_path)
 
        shutil.rmtree(idx_path)
 

	
 
    if data_path and os.path.exists(data_path):
rhodecode/model/__init__.py
Show inline comments
 
@@ -62,25 +62,25 @@ def init_model(engine):
 

	
 
class BaseModel(object):
 
    """Base Model for all RhodeCode models, it adds sql alchemy session
 
    into instance of model
 

	
 
    :param sa: If passed it reuses this session instead of creating a new one
 
    """
 

	
 
    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
 
        :param instance: int or Instance
 
        """
 

	
 
        if isinstance(instance, cls):
 
            return instance
 
        elif isinstance(instance, int) or str(instance).isdigit():
rhodecode/model/db.py
Show inline comments
 
@@ -109,39 +109,39 @@ class BaseModel(object):
 
            l.append((k, getattr(self, k),))
 
        return l
 

	
 
    def populate_obj(self, populate_dict):
 
        """populate model with data from given populate_dict"""
 

	
 
        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_)
 

	
 
    @classmethod
 
    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)
 
    app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    _app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    def __init__(self, k='', v=''):
 
        self.app_settings_name = k
 
        self.app_settings_value = v
 
@@ -243,26 +243,25 @@ class RhodeCodeUi(Base, BaseModel):
 
                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
 
        q = q.filter(cls.ui_section == 'hooks')
 
        return q.all()
 

	
 
    @classmethod
 
    def create_or_update_hook(cls, key, val):
 
        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)
 
    username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    active = Column("active", Boolean(), nullable=True, unique=None, default=None)
 
    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
 
    name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
@@ -326,28 +325,26 @@ class User(Base, BaseModel):
 

	
 
    @classmethod
 
    def get_by_email(cls, email, cache=False):
 
        q = cls.query().filter(cls.email == email)
 

	
 
        if cache:
 
            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}
 
    user_log_id = Column("user_log_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)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
 
    repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
@@ -377,117 +374,54 @@ class UsersGroup(Base, BaseModel):
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            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)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 
    @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},)
 

	
 
    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 
    repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
 
    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
 
@@ -512,42 +446,42 @@ class Repository(Base, BaseModel):
 
    logs = relationship('UserLog')
 

	
 
    def __repr__(self):
 
        return "<%s('%s:%s')>" % (self.__class__.__name__,
 
                                  self.repo_id, self.repo_name)
 

	
 
    @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):
 
        return self.repo_name.split(Repository.url_sep())[-1]
 

	
 
    @property
 
    def groups_with_parents(self):
 
        groups = []
 
        if self.group is None:
 
@@ -565,25 +499,25 @@ class Repository(Base, BaseModel):
 
        return groups
 

	
 
    @property
 
    def groups_and_repo(self):
 
        return self.groups_with_parents, self.just_name
 

	
 
    @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):
 
        p = [self.repo_path]
 
        # we need to split the name by / since this is how we store the
 
        # names in the database, but that eventually needs to be converted
 
        # into a valid system path
 
        p += self.repo_name.split(Repository.url_sep())
 
        return os.path.join(*p)
 
@@ -842,25 +776,25 @@ class Permission(Base, BaseModel):
 
    permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    def __repr__(self):
 
        return "<%s('%s:%s')>" % (self.__class__.__name__,
 
                                  self.permission_id, self.permission_name)
 

	
 
    @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()
 

	
 

	
 
class UserRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'repo_to_perm'
 
    __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'extend_existing':True})
 
    repo_to_perm_id = Column("repo_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)
 
@@ -868,149 +802,75 @@ class UserRepoToPerm(Base, BaseModel):
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @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):
 
    __tablename__ = 'user_to_perm'
 
    __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'extend_existing':True})
 
    user_to_perm_id = Column("user_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)
 
    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)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

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

	
 
    @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):
 
    __tablename__ = 'users_group_to_perm'
 
    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)
 
    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)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 
@@ -1094,51 +954,51 @@ class CacheInvalidation(Base, BaseModel)
 
                .filter(CacheInvalidation.cache_active == False)\
 
                .scalar()
 

	
 
    @classmethod
 
    def set_invalidate(cls, key):
 
        """
 
        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)
 
    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
 
    revision = Column('revision', String(40), nullable=False)
 
    line_no = Column('line_no', Unicode(10), nullable=True)
 
    f_path = Column('f_path', Unicode(1000), nullable=True)
 
    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
 
    text = Column('text', Unicode(25000), nullable=False)
 
@@ -1148,25 +1008,25 @@ class ChangesetComment(Base, BaseModel):
 
    repo = relationship('Repository')
 

	
 

	
 
    @classmethod
 
    def get_users(cls, revision):
 
        """
 
        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'
 
    __table_args__ = ({'extend_existing':True})
 

	
 
    TYPE_CHANGESET_COMMENT = u'cs_comment'
 
    TYPE_MESSAGE = u'message'
 
    TYPE_MENTION = u'mention'
 
    TYPE_REGISTRATION = u'registration'
 
@@ -1194,44 +1054,44 @@ class Notification(Base, BaseModel):
 

	
 
        notification = cls()
 
        notification.created_by_user = created_by
 
        notification.subject = subject
 
        notification.body = body
 
        notification.type_ = type_
 
        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)
 

	
 
class UserNotification(Base, BaseModel):
 
    __tablename__ = 'user_to_notification'
 
    __table_args__ = (UniqueConstraint('user_id', 'notification_id'),
 
                      {'extend_existing':True})
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), primary_key=True)
 
    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
 
    read = Column('read', Boolean, default=False)
 
    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
 

	
 
    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)
 
    version = Column('version', Integer)
 

	
rhodecode/model/forms.py
Show inline comments
 
@@ -27,27 +27,25 @@ import traceback
 
import formencode
 
from formencode import All
 
from formencode.validators import UnicodeString, OneOf, Int, Number, Regex, \
 
    Email, Bool, StringBoolean, Set
 

	
 
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):
 
    _ = staticmethod(_)
 

	
 
#==============================================================================
 
# VALIDATORS
 
#==============================================================================
 
class ValidAuthToken(formencode.validators.FancyValidator):
 
@@ -59,25 +57,25 @@ class ValidAuthToken(formencode.validato
 
            raise formencode.Invalid(self.message('invalid_token', state,
 
                                            search_number=value), value, state)
 

	
 
def ValidUsername(edit, old_data):
 
    class _ValidUsername(formencode.validators.FancyValidator):
 

	
 
        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)
 

	
 
            if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
 
                raise formencode.Invalid(_('Username may only contain '
 
                                           'alphanumeric characters '
 
                                           'underscores, periods or dashes '
 
                                           'and must begin with alphanumeric '
 
                                           'character'), value, state)
 
@@ -259,38 +257,38 @@ def ValidRepoName(edit, old_data):
 

	
 
            else:
 
                group_path = ''
 
                repo_name_full = repo_name
 

	
 

	
 
            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
 

	
 
    return _ValidRepoName
 

	
 
def ValidForkName(*args, **kwargs):
 
    return ValidRepoName(*args, **kwargs)
 

	
rhodecode/model/repo.py
Show inline comments
 
@@ -195,29 +195,27 @@ class RepoModel(BaseModel):
 
                else:
 
                    setattr(cur_repo, k, v)
 

	
 
            new_name = cur_repo.get_new_name(form_data['repo_name'])
 
            cur_repo.repo_name = new_name
 

	
 
            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:
 
            if fork:
 
                fork_parent_id = form_data['fork_parent_id']
 

	
 
            # repo name is just a name of repository
 
            # while repo_name_full is a full qualified name that is combined
 
            # with name and path of group
 
@@ -303,72 +301,64 @@ class RepoModel(BaseModel):
 
        Simple wrapper into executing celery task for fork creation
 
        
 
        :param form_data:
 
        :param cur_user:
 
        """
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        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
 
        
 
        :param repo_name:
 
        """
 
        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
 
        group location
 

	
 
        :param repo_name:
 
        :param alias:
 
        :param parent_id:
 
        :param clone_uri:
 
@@ -419,22 +409,22 @@ class RepoModel(BaseModel):
 

	
 
    def __delete_repo(self, repo):
 
        """
 
        removes repo from filesystem, the removal is acctually made by
 
        added rm__ prefix into dir, and rename internat .hg/.git dirs so this
 
        repository is no longer valid for rhodecode, can be undeleted later on
 
        by reverting the renames on this repository
 

	
 
        :param repo: repo object
 
        """
 
        rm_path = os.path.join(self.repos_path, repo.repo_name)
 
        log.info("Removing %s", rm_path)
 
        #disable hg/git
 
        # disable hg/git
 
        alias = repo.repo_type
 
        shutil.move(os.path.join(rm_path, '.%s' % alias),
 
                    os.path.join(rm_path, 'rm__.%s' % alias))
 
        #disable repo
 
        # disable repo
 
        shutil.move(rm_path, os.path.join(self.repos_path, 'rm__%s__%s' \
 
                                          % (datetime.today()\
 
                                             .strftime('%Y%m%d_%H%M%S_%f'),
 
                                            repo.repo_name)))
 

	
rhodecode/model/user.py
Show inline comments
 
@@ -45,24 +45,27 @@ from sqlalchemy.orm import joinedload
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
PERM_WEIGHTS = {'repository.none': 0,
 
                'repository.read': 1,
 
                '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)
 

	
 
    def get_by_username(self, username, cache=False, case_insensitive=False):
 

	
 
        if case_insensitive:
 
            user = self.sa.query(User).filter(User.username.ilike(username))
 
        else:
 
@@ -75,29 +78,27 @@ class UserModel(BaseModel):
 

	
 
    def get_by_api_key(self, api_key, cache=False):
 
        return User.get_by_api_key(api_key, cache)
 

	
 
    def create(self, form_data):
 
        try:
 
            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):
 
        """
 
        Creates a new instance if not found, or updates current one
 
        
 
        :param username:
 
        :param password:
 
        :param email:
 
        :param active:
 
@@ -150,25 +151,24 @@ class UserModel(BaseModel):
 

	
 
            try:
 
                new_user = User()
 
                new_user.username = username
 
                new_user.password = None
 
                new_user.api_key = generate_api_key(username)
 
                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'
 
                  ' for container auth.', username)
 
        return None
 

	
 
    def create_ldap(self, username, password, user_dn, attrs):
 
        """
 
        Checks if user is in database, if not creates this user marked
 
@@ -191,25 +191,24 @@ class UserModel(BaseModel):
 
                username = username.lower()
 
                # add ldap account always lowercase
 
                new_user.username = username
 
                new_user.password = get_crypt_password(password)
 
                new_user.api_key = generate_api_key(username)
 
                new_user.email = attrs['email'] or generate_email(username)
 
                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',
 
                  username)
 
        return None
 

	
 
    def create_registration(self, form_data):
 
        from rhodecode.model.notification import NotificationModel
 

	
 
@@ -249,70 +248,64 @@ class UserModel(BaseModel):
 
                raise DefaultUserException(
 
                                _("You can't Edit this user since it's"
 
                                  " crucial for entire application"))
 

	
 
            for k, v in form_data.items():
 
                if k == 'new_password' and v != '':
 
                    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':
 
                raise DefaultUserException(
 
                                _("You can't Edit this user since it's"
 
                                  " crucial for entire application"))
 
            for k, v in form_data.items():
 
                if k == 'new_password' and v != '':
 
                    user.password = v
 
                    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':
 
                raise DefaultUserException(
 
                                _("You can't remove this user since it's"
 
                                  " crucial for entire application"))
 
            if user.repositories:
 
                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'])
 

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

	
 
    def fill_data(self, auth_user, user_id=None, api_key=None):
 
        """
 
@@ -468,12 +461,44 @@ class UserModel(BaseModel):
 
                p = perm.Permission.permission_name
 
                cur_perm = user.permissions['repositories'][perm.
 
                                                    UsersGroupRepoToPerm.
 
                                                    repository.repo_name]
 
                # overwrite permission only if it's greater than permission
 
                # given from other sources
 
                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
 
@@ -18,58 +18,135 @@
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# 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):
 

	
 
    def __get_users_group(self, users_group):
 
        return self._get_instance(UsersGroup, users_group)
 

	
 
    def get(self, users_group_id, cache=False):
 
        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):
 
        new = UsersGroup()
 
        new.users_group_name = name
 
        new.users_group_active = active
 
        self.sa.add(new)
 
        return new
 
        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
 

	
 
        try:
 
            users_group_member = UsersGroupMember()
 
            users_group_member.user = user
 
            users_group_member.users_group = users_group
 

	
 
            users_group.members.append(users_group_member)
 
            user.group_member.append(users_group_member)
 

	
 
            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
 
@@ -30,19 +30,19 @@
 
	        </li>          
 
	    </ul>             
 
    </div>
 
    <div class="table">
 
		<div id="files_data">
 
			<%include file='files_ypjax.html'/>
 
		</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
 
@@ -72,25 +72,25 @@ class Command(object):
 
        log.debug('Executing %s' % command)
 
        if DEBUG:
 
            print command
 
        p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
 
        stdout, stderr = p.communicate()
 
        if DEBUG:
 
            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()
 

	
 
    user = sa.query(User).filter(User.username == USER).scalar()
 

	
 
    if force and user is not None:
 
        print 'removing current user'
 
        for repo in sa.query(Repository).filter(Repository.user == user).all():
rhodecode/tests/functional/test_admin_notifications.py
Show inline comments
 
@@ -2,44 +2,44 @@ from rhodecode.tests import *
 
from rhodecode.model.db import Notification, User, UserNotification
 

	
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.notification import NotificationModel
 
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',
 
                                               name='u1', lastname='u1').user_id
 

	
 
        response = self.app.get(url('notifications'))
 
        self.assertTrue('''<div class="table">No notifications here yet</div>'''
 
                        in response.body)
 

	
 
        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'))
 
#
 
#    def test_create(self):
 
#        response = self.app.post(url('notifications'))
 
#
 
#    def test_new(self):
 
#        response = self.app.get(url('new_notification'))
 
#
 
@@ -59,25 +59,25 @@ class TestNotificationsController(TestCo
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1')
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2')
 

	
 
        # 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])
 
        self.assertEqual(get_notif(u1.notifications), [notification])
 
        self.assertEqual(get_notif(u2.notifications), [notification])
 
        cur_usr_id = cur_user.user_id
 

	
 

	
 
        response = self.app.delete(url('notification',
rhodecode/tests/functional/test_admin_repos.py
Show inline comments
 
@@ -23,29 +23,28 @@ class TestAdminReposController(TestContr
 

	
 
    def test_create_hg(self):
 
        self.log_user()
 
        repo_name = NEW_HG_REPO
 
        description = 'description for newly created repo'
 
        private = False
 
        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 ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 

	
 
        #test if repository was created on filesystem
 
@@ -64,25 +63,25 @@ class TestAdminReposController(TestContr
 
        description_unicode = description.decode('utf8')
 
        private = False
 
        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_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 ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 
        #test if repository was created on filesystem
 
        try:
 
@@ -104,25 +103,25 @@ class TestAdminReposController(TestContr
 
        response = self.app.post(url('repos'), {'repo_name':repo_name,
 
                                                'repo_type':'git',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 

	
 

	
 
        #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()
 

	
 
        assert repo_name in response.body, 'missing new repo from the main repos list'
 

	
 
        #test if repository was created on filesystem
 
        try:
 
            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
 
@@ -153,45 +152,45 @@ class TestAdminReposController(TestContr
 
                                                'repo_type':'hg',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 
        self.assertTrue('flash' in response.session)
 

	
 
        #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 ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 

	
 
        response = self.app.delete(url('repo', repo_name=repo_name))
 

	
 
        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):
 
        #TODO:
 
        pass
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('repo', repo_name=HG_REPO),
rhodecode/tests/functional/test_admin_settings.py
Show inline comments
 
@@ -136,25 +136,25 @@ class TestAdminSettingsController(TestCo
 
        response = self.app.post(url('admin_settings_my_account_update'),
 
                                 params=dict(_method='put',
 
                                             username='test_admin',
 
                                             new_password=new_password,
 
                                             password_confirmation = new_password,
 
                                             password='',
 
                                             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
 
        old_email = 'test_admin@mail.com'
 
        old_name = 'RhodeCode'
 
        old_lastname = 'Admin'
 
        old_password = 'test12'
 

	
 
        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
 
@@ -162,25 +162,25 @@ class TestAdminSettingsController(TestCo
 
                                                            username='test_admin',
 
                                                            new_password=old_password,
 
                                                            password_confirmation = old_password,
 
                                                            password='',
 
                                                            name=old_name,
 
                                                            lastname=old_lastname,
 
                                                            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)
 

	
 

	
 
    def test_my_account_update_err_email_exists(self):
 
        self.log_user()
 

	
 
        new_email = 'test_regular@mail.com'#already exisitn email
rhodecode/tests/functional/test_admin_users.py
Show inline comments
 
@@ -23,25 +23,25 @@ class TestAdminUsersController(TestContr
 

	
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'password_confirmation':password_confirmation,
 
                                               'name':name,
 
                                               'active':True,
 
                                               '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'
 
        assert new_user.email == email, 'wrong info about email'
 

	
 

	
 
        response.follow()
 
        response = response.follow()
 
        assert """edit">newtestuser</a>""" in response.body
 
@@ -57,25 +57,25 @@ class TestAdminUsersController(TestContr
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'name':name,
 
                                               'active':False,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 
        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'))
 

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

	
 
    def test_update(self):
 
        response = self.app.put(url('user', id=1))
 

	
 
@@ -91,25 +91,25 @@ class TestAdminUsersController(TestContr
 
        email = 'todeletemail@mail.com'
 

	
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'password_confirmation':password,
 
                                               'name':name,
 
                                               '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):
 
        response = self.app.post(url('user', id=1), params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        response = self.app.get(url('user', id=1))
 

	
 
    def test_show_as_xml(self):
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
@@ -14,28 +14,24 @@ class TestAdminUsersGroupsController(Tes
 

	
 
    def test_create(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name':users_group_name,
 
                                  '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'))
 

	
 
    def test_update(self):
 
        response = self.app.put(url('users_group', id=1))
 

	
 
    def test_update_browser_fakeout(self):
 
        response = self.app.post(url('users_group', id=1),
 
                                 params=dict(_method='put'))
 
@@ -43,31 +39,31 @@ class TestAdminUsersGroupsController(Tes
 
    def test_delete(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP + 'another'
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name':users_group_name,
 
                                  'active':True})
 
        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)
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('users_group', id=1),
 
                                 params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        response = self.app.get(url('users_group', id=1))
rhodecode/tests/functional/test_changeset_comments.py
Show inline comments
 
from rhodecode.tests import *
 
from rhodecode.model.db import ChangesetComment, Notification, User, \
 
    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'
 

	
 
        params = {'text':text}
 
        response = self.app.post(url(controller='changeset', action='comment',
 
                                     repo_name=HG_REPO, revision=rev),
 
                                     params=params)
 
        # Test response...
 
        self.assertEqual(response.status, '302 Found')
rhodecode/tests/functional/test_files.py
Show inline comments
 
@@ -302,12 +302,25 @@ removed extra unicode conversion in diff
 

	
 

	
 
    def test_raw_wrong_f_path(self):
 
        self.log_user()
 
        rev = '27cd5cce30c96924232dffcd24178a07ffeb5dfc'
 
        f_path = 'vcs/ERRORnodes.py'
 
        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
 
@@ -56,25 +56,25 @@ class TestForksController(TestController
 
                                    {'repo_name':fork_name,
 
                                     'repo_group':'',
 
                                     'fork_parent_id':org_repo.repo_id,
 
                                     'repo_type':'hg',
 
                                     'description':description,
 
                                     'private':'False'})
 

	
 
        #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)
 

	
 

	
 
        #test if fork is visible in the list ?
 
        response = response.follow()
 

	
 

	
 
        # check if fork is marked as fork
 
        # wait for cache to expire
rhodecode/tests/functional/test_journal.py
Show inline comments
 
@@ -7,28 +7,28 @@ class TestJournalController(TestControll
 

	
 
    def test_index(self):
 
        self.log_user()
 
        response = self.app.get(url(controller='journal', action='index'))
 

	
 
        # Test response...
 
        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',
 
#                                     action='toggle_following'),
 
#                                     {'auth_token':get_token(session),
 
#                                      'follows_repo_id':repo.repo_id})
 

	
 
    def test_start_following_repository(self):
 
        self.log_user()
rhodecode/tests/functional/test_login.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
from rhodecode.tests import *
 
from rhodecode.model.db import User, Notification
 
from rhodecode.lib import generate_api_key
 
from rhodecode.lib.auth import check_password
 
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...
 

	
 
    def test_login_admin_ok(self):
 
        response = self.app.post(url(controller='login', action='index'),
 
                                 {'username':'test_admin',
 
                                  'password':'test12'})
 
        self.assertEqual(response.status, '302 Found')
 
@@ -190,25 +190,25 @@ class TestLoginController(TestController
 
        lastname = 'testlastname'
 

	
 
        response = self.app.post(url(controller='login', action='register'),
 
                                            {'username':username,
 
                                             'password':password,
 
                                             'password_confirmation':password,
 
                                             '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)
 

	
 

	
 
    def test_forgot_password_wrong_mail(self):
 
        response = self.app.post(url(controller='login', action='password_reset'),
 
                                            {'email':'marcin@wrongmail.org', })
 

	
 
        assert "This e-mail address doesn't exist" in response.body, 'Missing error message about wrong email'
 
@@ -222,26 +222,26 @@ class TestLoginController(TestController
 
        password = 'qweqwe'
 
        email = 'marcin@python-works.com'
 
        name = 'passwd'
 
        lastname = 'reset'
 

	
 
        new = User()
 
        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')
 

	
 
        response = response.follow()
 

	
 
        # BAD KEY
 

	
 
        key = "bad"
rhodecode/tests/functional/test_summary.py
Show inline comments
 
@@ -28,20 +28,20 @@ class TestSummaryController(TestControll
 
                                    repo_name=HG_REPO))
 

	
 
        self.assertTrue("""var data = {"py": {"count": 42, "desc": """
 
                        """["Python"]}, "rst": {"count": 11, "desc": """
 
                        """["Rst"]}, "sh": {"count": 2, "desc": ["Bash"]}, """
 
                        """"makefile": {"count": 1, "desc": ["Makefile", """
 
                        """"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
 
@@ -57,25 +57,25 @@ class TestReposGroups(unittest.TestCase)
 
        gr = ReposGroupModel().update(id_, form_data)
 
        return gr
 

	
 
    def test_create_group(self):
 
        g = self.__make_group('newGroup')
 
        self.assertEqual(g.full_path, 'newGroup')
 

	
 
        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'))
 

	
 
        ssg1 = self.__make_group('subsub1', parent_id=sg1.group_id)
 
        self.assertEqual(ssg1.parent_group, sg1)
 
        self.assertEqual(ssg1.full_path, 'test1/sub1/subsub1')
 
        self.assertTrue(self.__check_path('test1', 'sub1', 'subsub1'))
 

	
 
@@ -154,38 +154,38 @@ class TestReposGroups(unittest.TestCase)
 
        self.__update_group(g1.group_id, 'g1', parent_id=g2.group_id)
 
        self.assertTrue(self.__check_path('g2', 'g1'))
 

	
 
        # test repo
 
        self.assertEqual(r.repo_name, os.path.join('g2', 'g1', r.just_name))
 

	
 
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):
 

	
 
    def __init__(self, methodName='runTest'):
 
        self.u1 = UserModel().create_or_update(username=u'u1',
 
                                        password=u'qweqwe',
 
                                        email=u'u1@rhodecode.org',
 
                                        name=u'u1', lastname=u'u1')
 
        Session.commit()
 
@@ -200,118 +200,118 @@ class TestNotifications(unittest.TestCas
 

	
 
        self.u3 = UserModel().create_or_update(username=u'u3',
 
                                        password=u'qweqwe',
 
                                        email=u'u3@rhodecode.org',
 
                                        name=u'u3', lastname=u'u3')
 
        Session.commit()
 
        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)
 

	
 
        unotification = UserNotification.query()\
 
            .filter(UserNotification.notification == notification).all()
 

	
 
        self.assertEqual(notifications[0].recipients, [u1, u2])
 
        self.assertEqual(notification.notification_id,
 
                         notifications[0].notification_id)
 
        self.assertEqual(len(unotification), len(usrs))
 
        self.assertEqual([x.user.user_id for x in unotification], usrs)
 

	
 
        self._clean_notifications()
 

	
 
    def test_user_notifications(self):
 
        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()
 
        self.assertEqual(un, [])
 

	
 
        self._clean_notifications()
 

	
 
    def test_delete_association(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()
 

	
 
        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()
 

	
 
        self.assertEqual(u3notification, None)
 

	
 
        # notification object is still there
 
        self.assertEqual(Notification.query().all(), [notification])
 

	
 
@@ -330,33 +330,33 @@ class TestNotifications(unittest.TestCas
 
        self.assertNotEqual(u2notification, None)
 

	
 
        self._clean_notifications()
 

	
 
    def test_notification_counter(self):
 
        self._clean_notifications()
 
        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()
 
                         .get_unread_cnt_for_user(self.u3), 2)
 
        self._clean_notifications()
rhodecode/websetup.py
Show inline comments
 
@@ -37,14 +37,14 @@ log = logging.getLogger(__name__)
 
def setup_app(command, conf, vars):
 
    """Place any commands to setup rhodecode here"""
 
    dbconf = conf['sqlalchemy.db1.url']
 
    dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=conf['here'],
 
                        tests=False)
 
    dbmanage.create_tables(override=True)
 
    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)