Ejemplo n.º 1
0
class TestLdapModelFactory(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.username = "******"
        self.password = "******"

        ldap_connector = LdapConnector(username=self.username, password=self.password)
        self.ldapcon = ldap_connector.get_connection()
        self.ldmf = LdapModelFactory(self.ldapcon)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.ldapcon = None

    ################# User
    def test_getUser(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user, mematool.model.ldapmodel.Member)

    def test_getUserList(self):
        o = self.ldmf.getUserList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getActiveMemberList(self):
        o = self.ldmf.getActiveMemberList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getUserGroupList(self):
        o = self.ldmf.getUserGroupList(self.username)
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getHighestUidNumber(self):
        o = self.ldmf.getHighestUidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    def test_getUidNumberFromUid(self):
        o = self.ldmf.getUidNumberFromUid(self.username)
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    """
  def test_prepareVolatileAttribute(self):
    # @todo
    raise NotImplemented()

  def test__updateMember(self):
    # @todo
    raise NotImplemented()

  def test__addMember(self):
    # @todo
    raise NotImplemented()

  def test_deleteUser(self):
    # @todo
    raise NotImplemented()

  def test_changeUserGroup(self):
    # @todo
    raise NotImplemented()

  def test_updateAvatar(self):
    # @todo
    raise NotImplemented()
  """

    ################# Group

    def test_getGroup(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            group = self.ldmf.getGroup(g)
            self.assertIsInstance(group, mematool.model.dbmodel.Group)

    def test_getGroupList(self):
        o = self.ldmf.getGroupList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getGroupMembers(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            o = self.ldmf.getGroupMembers(g)
            self.assertIsInstance(o, list)
            self.assertGreaterEqual(len(o), 1)

    def test_addDeleteGroup(self):
        # add
        self.assertTrue(self.ldmf.addGroup("test_group"))
        o = self.ldmf.getGroupList()
        self.assertIn("test_group", o)

        # delete
        self.assertTrue(self.ldmf.deleteGroup("test_group"))
        o = self.ldmf.getGroupList()
        self.assertNotIn("test_group", o)

    def test_getHighestGidNumber(self):
        o = self.ldmf.getHighestGidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r"^\d+$")
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    ################# Domain

    def test_addDeleteDomain(self):
        res = self.ldmf.addDomain("example.com")
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertIn("example.com", res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertNotIn("example.com", res)

    def test_getDomain(self):
        res = self.ldmf.addDomain("example.com")
        self.assertTrue(res)

        d = self.ldmf.getDomain("example.com")
        self.assertIsInstance(d, mematool.model.ldapmodel.Domain)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    def test_getDomainList(self):
        res = self.ldmf.getDomainList()
        self.assertIsInstance(res, list)

    ################# Alias

    def test_getAlias(self):
        res = self.ldmf.addDomain("example.com")

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = "*****@*****.**"
        alias.mail = ["*****@*****.**"]
        alias.maildrop = ["*****@*****.**"]

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.getAlias("*****@*****.**")
        self.assertIsInstance(res, mematool.model.ldapmodel.Alias)

        res = self.ldmf.deleteAlias("*****@*****.**")
        self.assertTrue(res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    def test_getAliasList(self):
        res = self.ldmf.getAliasList("example.com")
        self.assertIsInstance(res, list)

    def test_getMaildropList(self):
        res = self.ldmf.getMaildropList("*****@*****.**")
        self.assertIsInstance(res, dict)

    def test_addDeleteAlias(self):
        res = self.ldmf.addDomain("example.com")
        # self.assertTrue(res)

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = "*****@*****.**"
        alias.mail = ["*****@*****.**"]
        alias.maildrop = ["*****@*****.**"]

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.deleteAlias("*****@*****.**")
        self.assertTrue(res)

        res = self.ldmf.deleteDomain("example.com")
        self.assertTrue(res)

    """
Ejemplo n.º 2
0
class TestLdapModelFactory(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.username = '******'
        self.password = '******'

        ldap_connector = LdapConnector(username=self.username,
                                       password=self.password)
        self.ldapcon = ldap_connector.get_connection()
        self.ldmf = LdapModelFactory(self.ldapcon)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.ldapcon = None

    ################# User
    def test_getUser(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user, mematool.model.ldapmodel.Member)

    def test_getUserList(self):
        o = self.ldmf.getUserList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getActiveMemberList(self):
        o = self.ldmf.getActiveMemberList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getUserGroupList(self):
        o = self.ldmf.getUserGroupList(self.username)
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getHighestUidNumber(self):
        o = self.ldmf.getHighestUidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    def test_getUidNumberFromUid(self):
        o = self.ldmf.getUidNumberFromUid(self.username)
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    '''
  def test_prepareVolatileAttribute(self):
    # @todo
    raise NotImplemented()

  def test__updateMember(self):
    # @todo
    raise NotImplemented()

  def test__addMember(self):
    # @todo
    raise NotImplemented()

  def test_deleteUser(self):
    # @todo
    raise NotImplemented()

  def test_changeUserGroup(self):
    # @todo
    raise NotImplemented()

  def test_updateAvatar(self):
    # @todo
    raise NotImplemented()
  '''

    ################# Group

    def test_getGroup(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            group = self.ldmf.getGroup(g)
            self.assertIsInstance(group, mematool.model.dbmodel.Group)

    def test_getGroupList(self):
        o = self.ldmf.getGroupList()
        self.assertIsInstance(o, list)
        self.assertGreaterEqual(len(o), 1)

    def test_getGroupMembers(self):
        user = self.ldmf.getUser(self.username)
        self.assertIsInstance(user.groups, list)
        self.assertGreaterEqual(len(user.groups), 1)

        for g in user.groups:
            o = self.ldmf.getGroupMembers(g)
            self.assertIsInstance(o, list)
            self.assertGreaterEqual(len(o), 1)

    def test_addDeleteGroup(self):
        # add
        self.assertTrue(self.ldmf.addGroup('test_group'))
        o = self.ldmf.getGroupList()
        self.assertIn('test_group', o)

        # delete
        self.assertTrue(self.ldmf.deleteGroup('test_group'))
        o = self.ldmf.getGroupList()
        self.assertNotIn('test_group', o)

    def test_getHighestGidNumber(self):
        o = self.ldmf.getHighestGidNumber()
        self.assertIsInstance(o, str)
        self.assertRegexpMatches(o, r'^\d+$')
        o = int(o)
        self.assertGreaterEqual(o, 1000)

    ################# Domain

    def test_addDeleteDomain(self):
        res = self.ldmf.addDomain('example.com')
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertIn('example.com', res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

        res = self.ldmf.getDomainList()
        self.assertNotIn('example.com', res)

    def test_getDomain(self):
        res = self.ldmf.addDomain('example.com')
        self.assertTrue(res)

        d = self.ldmf.getDomain('example.com')
        self.assertIsInstance(d, mematool.model.ldapmodel.Domain)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    def test_getDomainList(self):
        res = self.ldmf.getDomainList()
        self.assertIsInstance(res, list)

    ################# Alias

    def test_getAlias(self):
        res = self.ldmf.addDomain('example.com')

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = '*****@*****.**'
        alias.mail = ['*****@*****.**']
        alias.maildrop = ['*****@*****.**']

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.getAlias('*****@*****.**')
        self.assertIsInstance(res, mematool.model.ldapmodel.Alias)

        res = self.ldmf.deleteAlias('*****@*****.**')
        self.assertTrue(res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    def test_getAliasList(self):
        res = self.ldmf.getAliasList('example.com')
        self.assertIsInstance(res, list)

    def test_getMaildropList(self):
        res = self.ldmf.getMaildropList('*****@*****.**')
        self.assertIsInstance(res, dict)

    def test_addDeleteAlias(self):
        res = self.ldmf.addDomain('example.com')
        #self.assertTrue(res)

        alias = mematool.model.ldapmodel.Alias()
        alias.dn_mail = '*****@*****.**'
        alias.mail = ['*****@*****.**']
        alias.maildrop = ['*****@*****.**']

        try:
            res = self.ldmf.addAlias(alias)
            self.assertTrue(res)
        except mematool.helpers.exceptions.EntryExists:
            pass

        res = self.ldmf.deleteAlias('*****@*****.**')
        self.assertTrue(res)

        res = self.ldmf.deleteDomain('example.com')
        self.assertTrue(res)

    '''
Ejemplo n.º 3
0
class GroupsController(BaseController):
  def __init__(self):
    super(GroupsController, self).__init__()
    self.lmf = LdapModelFactory()

  def __before__(self, action, **param):
    super(GroupsController, self).__before__()

  def _sidebar(self):
    super(GroupsController, self)._sidebar()

    c.actions.append({'name' : _('Show all groups'), 'args' : {'controller' : 'groups', 'action' : 'listGroups'}})
    c.actions.append({'name' : _('Add Group'), 'args' : {'controller' : 'groups', 'action' : 'editGroup'}})
    c.actions.append({'name' : _('Members'), 'args' : {'controller' : 'members', 'action' : 'index'}})

  def index(self):
    if self.lmf.isUserInGroup(self.identity, 'office') or self.lmf.isUserInGroup(self.identity, 'sysops'):
      return self.listGroups()

    return redirect(url(controller='profile', action='index'))

  @BaseController.needGroup('superadmins')
  def listGroups(self):
    c.heading = _('Managed groups')

    c.groups = self.lmf.getManagedGroupList()

    return render('/groups/listGroups.mako')

  @BaseController.needGroup('superadmins')
  def editGroup(self):
    # vary form depending on mode (do that over ajax)
    if request.params.get('gid', '') == '':
      c.group = Group()
      action = 'Adding'
      c.gid = ''
    else:
      try:
        ParamChecker.checkUsername('gid', param=True)
      except:
        redirect(url(controller='groups', action='index'))

      action = 'Editing'
      c.gid = request.params['gid']
      try:
        c.group = self.lmf.getGroup(request.params['gid'])
        users = ''

        for u in c.group.users:
          if not users == '':
            users += '\n'
          users += u

        c.group.users = users
      except LookupError:
        # @TODO implement better handler
        print 'No such group!'
        redirect(url(controller='groups', action='index'))

    c.heading = '{0} group'.format(action)

    return render('/groups/editGroup.mako')

  def checkEdit(f):
    def new_f(self):
      if not 'gid' in request.params:
        redirect(url(controller='groups', action='index'))
      else:
        formok = True
        errors = []
        items = {}

        try:
          ParamChecker.checkUsername('gid', param=True)
        except:
          formok = False
          errors.append(_('Invalid group ID'))

        items['users'] = []

        if 'users' in request.params:
          try:
            #ParamChecker.checkString('users', param=True, min_len=-1, max_len=9999, regex=r'([\w]{1,20}\n?)*')

            for k in request.params['users'].split('\n'):
              m = k.replace('\r', '').replace(' ', '')
              if m == '':
                continue
              else:
                ParamChecker.checkUsername(m, param=False)
                items['users'].append(m)
          except InvalidParameterFormat as ipf:
            formok = False
            errors.append(_('Invalid user name(s)'))

        if not formok:
          session['errors'] = errors
          session['reqparams'] = {}

          # @TODO request.params may contain multiple values per key... test & fix
          for k in request.params.iterkeys():
            session['reqparams'][k] = request.params[k]

          session.save()

          redirect(url(controller='groups', action='editGroup', gid=request.params['gid']))
        else:
          items['gid'] = request.params['gid']

      return f(self, items)
    return new_f

  @BaseController.needGroup('superadmins')
  @checkEdit
  @restrict('POST')
  def doEditGroup(self, items):
    if not self.lmf.addGroup(items['gid']):
      session['flash'] = _('Failed to add group!')
      session['flash_class'] = 'error'
      session.save()
    else:
      try:
        lgrp_members = self.lmf.getGroupMembers(items['gid'])
      except LookupError:
        lgrp_members = []

      # Adding new members
      for m in items['users']:
        if not m in lgrp_members:
          #print 'adding -> ' + str(m)
          self.lmf.changeUserGroup(m, items['gid'], True)

      # Removing members
      for m in lgrp_members:
        if not m in items['users']:
          #print 'removing -> ' + str(m)
          self.lmf.changeUserGroup(m, items['gid'], False)

      # @TODO add group if not exist

      session['flash'] = _('Group saved successfully')
      session['flash_class'] = 'success'
      session.save()

    redirect(url(controller='groups', action='index'))

  @BaseController.needGroup('superadmins')
  def unmanageGroup(self):
    try:
      ParamChecker.checkUsername('gid', param=True)
    except:
      redirect(url(controller='groups', action='index'))

    result = self.lmf.unmanageGroup(request.params['gid'])

    if result:
      session['flash'] = _('Group no longer managed')
      session['flash_class'] = 'success'
    else:
      session['flash'] = _('Failed to remove group from management!')
      session['flash_class'] = 'error'

    session.save()

    redirect(url(controller='groups', action='index'))

  @BaseController.needGroup('superadmins')
  def deleteGroup(self):
    try:
      ParamChecker.checkUsername('gid', param=True)
    except:
      redirect(url(controller='groups', action='index'))

    result = self.lmf.deleteGroup(request.params['gid'])

    if result:
      session['flash'] = _('Group successfully deleted')
      session['flash_class'] = 'success'
    else:
      session['flash'] = _('Failed to delete group!')
      session['flash_class'] = 'error'

    session.save()

    redirect(url(controller='groups', action='index'))