def permission_ips(self):
        c.active = 'ips'
        c.user = User.get_default_user()
        c.user_ip_map = (UserIpMap.query().filter(
            UserIpMap.user == c.user).all())

        return render('admin/permissions/permissions.html')
示例#2
0
    def edit(self, id, format='html'):
        """GET /permissions/id/edit: Form to edit an existing item"""
        #url('edit_permission', id=ID)

        #this form can only edit default user permissions
        if id == 'default':
            c.user = default_user = User.get_by_username('default')
            defaults = {'anonymous': default_user.active}
            c.perm_user = AuthUser(user_id=default_user.user_id)
            c.user_ip_map = UserIpMap.query()\
                            .filter(UserIpMap.user == default_user).all()
            for p in default_user.user_perms:
                if p.permission.permission_name.startswith('repository.'):
                    defaults['default_repo_perm'] = p.permission.permission_name

                if p.permission.permission_name.startswith('group.'):
                    defaults['default_group_perm'] = p.permission.permission_name

                if p.permission.permission_name.startswith('hg.register.'):
                    defaults['default_register'] = p.permission.permission_name

                if p.permission.permission_name.startswith('hg.create.'):
                    defaults['default_create'] = p.permission.permission_name

                if p.permission.permission_name.startswith('hg.fork.'):
                    defaults['default_fork'] = p.permission.permission_name

            return htmlfill.render(
                render('admin/permissions/permissions.html'),
                defaults=defaults,
                encoding="UTF-8",
                force_defaults=False
            )
        else:
            return redirect(url('admin_home'))
示例#3
0
    def edit(self, id, format='html'):
        """GET /users/id/edit: Form to edit an existing item"""
        # url('edit_user', id=ID)
        c.user = User.get_or_404(id)

        if c.user.username == 'default':
            h.flash(_("You can't edit this user"), category='warning')
            return redirect(url('users'))

        c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr)
        c.user.permissions = {}
        c.granted_permissions = UserModel().fill_perms(c.user)\
            .permissions['global']
        c.user_email_map = UserEmailMap.query()\
                        .filter(UserEmailMap.user == c.user).all()
        c.user_ip_map = UserIpMap.query()\
                        .filter(UserIpMap.user == c.user).all()
        umodel = UserModel()
        c.ldap_dn = c.user.ldap_dn
        defaults = c.user.get_dict()
        defaults.update({
            'create_repo_perm':
            umodel.has_perm(c.user, 'hg.create.repository'),
            'create_user_group_perm':
            umodel.has_perm(c.user, 'hg.usergroup.create.true'),
            'fork_repo_perm':
            umodel.has_perm(c.user, 'hg.fork.repository'),
        })

        return htmlfill.render(render('admin/users/user_edit.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
示例#4
0
    def edit(self, id, format='html'):
        """GET /users/id/edit: Form to edit an existing item"""
        # url('edit_user', id=ID)
        c.user = User.get_or_404(id)

        if c.user.username == 'default':
            h.flash(_("You can't edit this user"), category='warning')
            return redirect(url('users'))

        c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr)
        c.user.permissions = {}
        c.granted_permissions = UserModel().fill_perms(c.user)\
            .permissions['global']
        c.user_email_map = UserEmailMap.query()\
                        .filter(UserEmailMap.user == c.user).all()
        c.user_ip_map = UserIpMap.query()\
                        .filter(UserIpMap.user == c.user).all()
        user_model = UserModel()
        c.ldap_dn = c.user.ldap_dn
        defaults = c.user.get_dict()
        defaults.update({
            'create_repo_perm': user_model.has_perm(id, 'hg.create.repository'),
            'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'),
        })

        return htmlfill.render(
            render('admin/users/user_edit.html'),
            defaults=defaults,
            encoding="UTF-8",
            force_defaults=False
        )
    def test_add_delete_ips(self):
        self.log_user()
        clear_all_caches()

        # ADD
        default_user_id = User.get_default_user().user_id
        response = self.app.post(url('edit_user_ips', user_id=default_user_id),
                                 params={
                                     'new_ip': '127.0.0.0/24',
                                     '_method': 'put',
                                     'csrf_token': self.csrf_token
                                 })

        response = self.app.get(url('admin_permissions_ips'))
        response.mustcontain('127.0.0.0/24')
        response.mustcontain('127.0.0.0 - 127.0.0.255')

        # DELETE
        default_user_id = User.get_default_user().user_id
        del_ip_id = UserIpMap.query().filter(
            UserIpMap.user_id == default_user_id).first().ip_id

        response = self.app.post(url('edit_user_ips', user_id=default_user_id),
                                 params={
                                     '_method': 'delete',
                                     'del_ip_id': del_ip_id,
                                     'csrf_token': self.csrf_token
                                 })
        clear_all_caches()
        response = self.app.get(url('admin_permissions_ips'))
        response.mustcontain('All IP addresses are allowed')
        response.mustcontain(no=['127.0.0.0/24'])
        response.mustcontain(no=['127.0.0.0 - 127.0.0.255'])
示例#6
0
    def add_extra_ip(self, user, ip):
        """
        Adds ip address to UserIpMap

        :param user:
        :param ip:
        """
        from rhodecode.model import forms
        form = forms.UserExtraIpForm()()
        data = form.to_python(dict(ip=ip))
        user = self._get_user(user)

        obj = UserIpMap()
        obj.user = user
        obj.ip_addr = data['ip']
        self.sa.add(obj)
        return obj
示例#7
0
    def add_extra_ip(self, user, ip):
        """
        Adds ip address to UserIpMap

        :param user:
        :param ip:
        """
        from rhodecode.model import forms
        form = forms.UserExtraIpForm()()
        data = form.to_python(dict(ip=ip))
        user = self._get_user(user)

        obj = UserIpMap()
        obj.user = user
        obj.ip_addr = data['ip']
        self.sa.add(obj)
        return obj
def test_user_delete_cascades_ip_whitelist(test_user):
    sample_ip = '1.1.1.1'
    uid_map = UserIpMap(user_id=test_user.user_id, ip_addr=sample_ip)
    Session().add(uid_map)
    Session().delete(test_user)
    try:
        Session().flush()
    finally:
        Session().rollback()
示例#9
0
    def add_extra_ip(self, user, ip, description=None):
        """
        Adds ip address to UserIpMap

        :param user:
        :param ip:
        """
        from rhodecode.model import forms
        form = forms.UserExtraIpForm()()
        data = form.to_python({'ip': ip})
        user = self._get_user(user)

        obj = UserIpMap()
        obj.user = user
        obj.ip_addr = data['ip']
        obj.description = description
        self.sa.add(obj)
        return obj
示例#10
0
    def edit_ips(self, user_id):
        user_id = safe_int(user_id)
        c.user = User.get_or_404(user_id)
        if c.user.username == User.DEFAULT_USER:
            h.flash(_("You can't edit this user"), category='warning')
            return redirect(url('users'))

        c.active = 'ips'
        c.user_ip_map = UserIpMap.query() \
            .filter(UserIpMap.user == c.user).all()

        c.inherit_default_ips = c.user.inherit_default_permissions
        c.default_user_ip_map = UserIpMap.query() \
            .filter(UserIpMap.user == User.get_default_user()).all()

        defaults = c.user.get_dict()
        return htmlfill.render(render('admin/users/user_edit.html'),
                               defaults=defaults,
                               encoding="UTF-8",
                               force_defaults=False)
示例#11
0
文件: user.py 项目: nzinfo/rhodecode
    def delete_extra_ip(self, user, ip_id):
        """
        Removes ip address from UserIpMap

        :param user:
        :param ip_id:
        """
        user = self._get_user(user)
        obj = UserIpMap.query().get(ip_id)
        if obj:
            self.sa.delete(obj)
示例#12
0
    def delete_extra_ip(self, user, ip_id):
        """
        Removes ip address from UserIpMap

        :param user:
        :param ip_id:
        """
        user = self._get_user(user)
        obj = UserIpMap.query().get(ip_id)
        if obj:
            self.sa.delete(obj)
示例#13
0
    def show_ip(self, apiuser, userid):
        """
        Shows IP address as seen from RhodeCode server, together with all
        defined IP addresses for given user

        :param apiuser:
        :param userid:
        """
        user = get_user_or_error(userid)
        ips = UserIpMap.query().filter(UserIpMap.user == user).all()
        return dict(ip_addr_server=self.ip_addr, user_ips=ips)
示例#14
0
    def test_ip_restriction_git(self):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            clone_url = _construct_url(GIT_REPO)
            stdout, stderr = Command('/tmp').execute('git clone', clone_url)
            msg = ("""The requested URL returned error: 403""")
            assert msg in stderr
        finally:
            #release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)
        clone_url = _construct_url(GIT_REPO)
        stdout, stderr = Command('/tmp').execute('git clone', clone_url)

        assert 'Cloning into' in stdout
        assert stderr == ''
    def test_ip_restriction_hg(self, rc_web_server, tmpdir):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            time.sleep(2)
            clone_url = rc_web_server.repo_clone_url(HG_REPO)
            stdout, stderr = Command('/tmp').execute('hg clone', clone_url,
                                                     tmpdir.strpath)
            assert 'abort: HTTP Error 403: Forbidden' in stderr
        finally:
            # release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)

        stdout, stderr = Command('/tmp').execute('hg clone', clone_url,
                                                 tmpdir.strpath)
        _check_proper_clone(stdout, stderr, 'hg')
    def test_ip_restriction_git(self):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            clone_url = _construct_url(GIT_REPO)
            stdout, stderr = Command('/tmp').execute('git clone', clone_url)
            msg = ("""The requested URL returned error: 403""")
            assert msg in stderr
        finally:
            #release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)
        clone_url = _construct_url(GIT_REPO)
        stdout, stderr = Command('/tmp').execute('git clone', clone_url)

        assert 'Cloning into' in stdout
        assert stderr == ''
示例#17
0
 def get_allowed_ips(cls, user_id, cache=False):
     _set = set()
     user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
     if cache:
         user_ips = user_ips.options(
             FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
     for ip in user_ips:
         try:
             _set.add(ip.ip_addr)
         except ObjectDeletedError:
             # since we use heavy caching sometimes it happens that we get
             # deleted objects here, we just skip them
             pass
     return _set or set(['0.0.0.0/0', '::/0'])
示例#18
0
    def show_ip(self, apiuser, userid):
        """
        Shows IP address as seen from RhodeCode server, together with all
        defined IP addresses for given user

        :param apiuser:
        :param userid:
        """
        user = get_user_or_error(userid)
        ips = UserIpMap.query().filter(UserIpMap.user == user).all()
        return dict(
            ip_addr_server=self.ip_addr,
            user_ips=ips
        )
示例#19
0
 def update(self, id):
     """PUT /users/id: Update an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="PUT" />
     # Or using helpers:
     #    h.form(url('update_user', id=ID),
     #           method='put')
     # url('user', id=ID)
     user_model = UserModel()
     c.user = user_model.get(id)
     c.ldap_dn = c.user.ldap_dn
     c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr)
     _form = UserForm(edit=True,
                      old_data={
                          'user_id': id,
                          'email': c.user.email
                      })()
     form_result = {}
     try:
         form_result = _form.to_python(dict(request.POST))
         skip_attrs = []
         if c.ldap_dn:
             #forbid updating username for ldap accounts
             skip_attrs = ['username']
         user_model.update(id, form_result, skip_attrs=skip_attrs)
         usr = form_result['username']
         action_logger(self.rhodecode_user, 'admin_updated_user:%s' % usr,
                       None, self.ip_addr, self.sa)
         h.flash(_('User updated successfully'), category='success')
         Session().commit()
     except formencode.Invalid, errors:
         c.user_email_map = UserEmailMap.query()\
                         .filter(UserEmailMap.user == c.user).all()
         c.user_ip_map = UserIpMap.query()\
                         .filter(UserIpMap.user == c.user).all()
         defaults = errors.value
         e = errors.error_dict or {}
         defaults.update({
             'create_repo_perm':
             user_model.has_perm(id, 'hg.create.repository'),
             'fork_repo_perm':
             user_model.has_perm(id, 'hg.fork.repository'),
             '_method':
             'put'
         })
         return htmlfill.render(render('admin/users/user_edit.html'),
                                defaults=defaults,
                                errors=e,
                                prefix_error=False,
                                encoding="UTF-8")
示例#20
0
 def get_allowed_ips(cls, user_id, cache=False):
     _set = set()
     user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
     if cache:
         user_ips = user_ips.options(FromCache("sql_cache_short",
                                               "get_user_ips_%s" % user_id))
     for ip in user_ips:
         try:
             _set.add(ip.ip_addr)
         except ObjectDeletedError:
             # since we use heavy caching sometimes it happens that we get
             # deleted objects here, we just skip them
             pass
     return _set or set(['0.0.0.0/0', '::/0'])
    def test_ip_restriction_git(self, rc_web_server, tmpdir):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            time.sleep(2)
            clone_url = rc_web_server.repo_clone_url(GIT_REPO)
            stdout, stderr = Command('/tmp').execute('git clone', clone_url,
                                                     tmpdir.strpath)
            msg = "The requested URL returned error: 403"
            assert msg in stderr
        finally:
            # release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)

        cmd = Command('/tmp')
        stdout, stderr = cmd.execute('git clone', clone_url, tmpdir.strpath)
        cmd.assert_returncode_success()
        _check_proper_clone(stdout, stderr, 'git')
    def test_ip_restriction_hg(self):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            clone_url = _construct_url(HG_REPO)
            stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
            assert 'abort: HTTP Error 403: Forbidden' in stderr
        finally:
            #release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)
        clone_url = _construct_url(HG_REPO)
        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)

        assert 'requesting all changes' in stdout
        assert 'adding changesets' in stdout
        assert 'adding manifests' in stdout
        assert 'adding file changes' in stdout

        assert stderr == ''
示例#23
0
    def test_ip_restriction_hg(self):
        user_model = UserModel()
        try:
            user_model.add_extra_ip(TEST_USER_ADMIN_LOGIN, '10.10.10.10/32')
            Session().commit()
            clone_url = _construct_url(HG_REPO)
            stdout, stderr = Command('/tmp').execute('hg clone', clone_url)
            assert 'abort: HTTP Error 403: Forbidden' in stderr
        finally:
            #release IP restrictions
            for ip in UserIpMap.getAll():
                UserIpMap.delete(ip.ip_id)
            Session().commit()

        time.sleep(2)
        clone_url = _construct_url(HG_REPO)
        stdout, stderr = Command('/tmp').execute('hg clone', clone_url)

        assert 'requesting all changes' in stdout
        assert 'adding changesets' in stdout
        assert 'adding manifests' in stdout
        assert 'adding file changes' in stdout

        assert stderr == ''
def get_ip(request, apiuser, userid=Optional(OAttr('apiuser'))):
    """
    Displays the IP Address as seen from the |RCE| server.

    * This command displays the IP Address, as well as all the defined IP
      addresses for the specified user. If the ``userid`` is not set, the
      data returned is for the user calling the method.

    This command can only be run using an |authtoken| with admin rights to
    the specified repository.

    This command takes the following options:

    :param apiuser: This is filled automatically from |authtoken|.
    :type apiuser: AuthUser
    :param userid: Sets the userid for which associated IP Address data
        is returned.
    :type userid: Optional(str or int)

    Example output:

    .. code-block:: bash

        id : <id_given_in_input>
        result : {
                     "server_ip_addr": "<ip_from_clien>",
                     "user_ips": [
                                    {
                                       "ip_addr": "<ip_with_mask>",
                                       "ip_range": ["<start_ip>", "<end_ip>"],
                                    },
                                    ...
                                 ]
        }

    """
    if not has_superadmin_permission(apiuser):
        raise JSONRPCForbidden()

    userid = Optional.extract(userid, evaluate_locals=locals())
    userid = getattr(userid, 'user_id', userid)

    user = get_user_or_error(userid)
    ips = UserIpMap.query().filter(UserIpMap.user == user).all()
    return {
        'server_ip_addr': request.rpc_ip_addr,
        'user_ips': ips
    }
示例#25
0
    def update(self, id):
        """PUT /permissions/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('permission', id=ID),
        #           method='put')
        # url('permission', id=ID)
        if id == 'default':
            c.user = default_user = User.get_default_user()
            c.perm_user = AuthUser(user_id=default_user.user_id)
            c.user_ip_map = UserIpMap.query()\
                            .filter(UserIpMap.user == default_user).all()

            _form = DefaultPermissionsForm(
                [x[0] for x in c.repo_perms_choices],
                [x[0] for x in c.group_perms_choices],
                [x[0] for x in c.user_group_perms_choices],
                [x[0] for x in c.repo_create_choices],
                [x[0] for x in c.repo_group_create_choices],
                [x[0] for x in c.user_group_create_choices],
                [x[0] for x in c.fork_choices],
                [x[0] for x in c.register_choices],
                [x[0] for x in c.extern_activate_choices],
            )()

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

            except formencode.Invalid, errors:
                defaults = errors.value

                return htmlfill.render(
                    render('admin/permissions/permissions.html'),
                    defaults=defaults,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8")
            except Exception:
                log.error(traceback.format_exc())
                h.flash(_('Error occurred during update of permissions'),
                        category='error')
示例#26
0
    def update(self, id):
        """PUT /permissions/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('permission', id=ID),
        #           method='put')
        # url('permission', id=ID)
        if id == 'default':
            c.user = default_user = User.get_default_user()
            c.perm_user = AuthUser(user_id=default_user.user_id)
            c.user_ip_map = UserIpMap.query()\
                            .filter(UserIpMap.user == default_user).all()

            _form = DefaultPermissionsForm(
                    [x[0] for x in c.repo_perms_choices],
                    [x[0] for x in c.group_perms_choices],
                    [x[0] for x in c.user_group_perms_choices],
                    [x[0] for x in c.repo_create_choices],
                    [x[0] for x in c.repo_group_create_choices],
                    [x[0] for x in c.user_group_create_choices],
                    [x[0] for x in c.fork_choices],
                    [x[0] for x in c.register_choices],
                    [x[0] for x in c.extern_activate_choices],
            )()

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

            except formencode.Invalid, errors:
                defaults = errors.value

                return htmlfill.render(
                    render('admin/permissions/permissions.html'),
                    defaults=defaults,
                    errors=errors.error_dict or {},
                    prefix_error=False,
                    encoding="UTF-8")
            except Exception:
                log.error(traceback.format_exc())
                h.flash(_('Error occurred during update of permissions'),
                        category='error')
示例#27
0
 def update(self, id):
     """PUT /users/id: Update an existing item"""
     # Forms posted to this method should contain a hidden field:
     #    <input type="hidden" name="_method" value="PUT" />
     # Or using helpers:
     #    h.form(url('update_user', id=ID),
     #           method='put')
     # url('user', id=ID)
     user_model = UserModel()
     c.user = user_model.get(id)
     c.ldap_dn = c.user.ldap_dn
     c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr)
     _form = UserForm(edit=True, old_data={'user_id': id,
                                           'email': c.user.email})()
     form_result = {}
     try:
         form_result = _form.to_python(dict(request.POST))
         skip_attrs = []
         if c.ldap_dn:
             #forbid updating username for ldap accounts
             skip_attrs = ['username']
         user_model.update(id, form_result, skip_attrs=skip_attrs)
         usr = form_result['username']
         action_logger(self.rhodecode_user, 'admin_updated_user:%s' % usr,
                       None, self.ip_addr, self.sa)
         h.flash(_('User updated successfully'), category='success')
         Session().commit()
     except formencode.Invalid, errors:
         c.user_email_map = UserEmailMap.query()\
                         .filter(UserEmailMap.user == c.user).all()
         c.user_ip_map = UserIpMap.query()\
                         .filter(UserIpMap.user == c.user).all()
         defaults = errors.value
         e = errors.error_dict or {}
         defaults.update({
             'create_repo_perm': user_model.has_perm(id, 'hg.create.repository'),
             'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'),
             '_method': 'put'
         })
         return htmlfill.render(
             render('admin/users/user_edit.html'),
             defaults=defaults,
             errors=e,
             prefix_error=False,
             encoding="UTF-8")
示例#28
0
def ip_range(ip_addr):
    from rhodecode.model.db import UserIpMap
    s, e = UserIpMap._get_ip_range(ip_addr)
    return '%s - %s' % (s, e)
示例#29
0
def ip_range(ip_addr):
    from rhodecode.model.db import UserIpMap
    s, e = UserIpMap._get_ip_range(ip_addr)
    return '%s - %s' % (s, e)