Esempio n. 1
0
    def validatePayment(self, member_id, idPayment):
        """ Validate a payment specified by an id """
        try:
            ParamChecker.checkUsername('member_id', param=True)
            ParamChecker.checkInt('idPayment', param=True)
        except:
            raise HTTPRedirect('/payments/index')

        try:
            np = self.db.query(Payment).filter(Payment.id == idPayment).one()

            if np.verified:
                np.verified = False
            else:
                np.verified = True
            self.request.db.commit()

            self.session['flash'] = _(
                'Payment validation successfully toggled')
            self.session['flash_class'] = 'success'
        except:
            self.session['flash'] = _('Saving payment failed')
            self.session['flash_class'] = 'error'

        self.session.save()

        raise HTTPRedirect(
            '/payments/listPayments/?member_id={0}'.format(member_id))
Esempio n. 2
0
    def editPayment(self, member_id, year=None, month=None, idPayment='0'):
        """ Add or edit a payment to/of a specific user """
        if not self.is_admin() and not member_id == self.session.get(
                'username'):
            raise HTTPError(403, 'Forbidden')

        c = TemplateContext()
        c.member_id = member_id
        c.status_0 = False
        c.status_1 = False
        c.status_2 = False

        # vary form depending on mode (do that over ajax)
        if idPayment == '0':
            c.payment = Payment()
            action = 'Adding'

            try:
                ParamChecker.checkYear('year', param=True)
                ParamChecker.checkMonth('month', param=True)
                c.date = str(datetime.date(int(year), int(month), 1))
            except:
                '''Don't care ... just let the user enter a new date'''
                pass

        elif not idPayment == '' and IsInt(idPayment) and int(idPayment) > 0:
            # @fixme convert IsInt to new class
            action = 'Editing'
            payment_q = self.db.query(Payment).filter(
                Payment.id == int(idPayment))
            try:
                payment = payment_q.one()

                # @TODO allow member editing if not verified???
                if payment.verified and not self.is_admin():
                    raise HTTPError(403, 'Forbidden')

                c.payment = payment
                setattr(c, 'status_' + str(payment.status), True)
            except NoResultFound:
                print "oops"
                raise HTTPRedirect('/members/index')
        else:
            raise HTTPRedirect('/members/index')

        c.heading = _('%s payment for user %s') % (action, c.member_id)
        self.sidebar.append({
            'name': _('List payments'),
            'args': {
                'controller': 'payments',
                'action': 'listPayments',
                'params': {
                    'member_id': member_id
                }
            }
        })

        return self.render('/payments/editPayment.mako', template_context=c)
Esempio n. 3
0
    def setLang(self, lang):
        if lang in Config.get('mematool', 'languages', []):
            self.session['language'] = lang
            self.session.save()

        if 'user' in self.session:
            raise HTTPRedirect('/profile/index')

        raise HTTPRedirect('/')
Esempio n. 4
0
        def new_f(self, member_id, **kwargs):
            # @TODO request.params may contain multiple values per key... test & fix
            formok = True
            errors = []

            try:
                ParamChecker.checkMode('mode', values=('add', 'edit'))
            except InvalidParameterFormat as ipf:
                formok = False
                errors.append(ipf.message)

            m = Member()

            for v in m.str_vars:
                setattr(m, v, self.request.params.get(v, ''))

            m.uid = member_id

            try:
                m.check()
            except InvalidParameterFormat as ipf:
                formok = False
                errors += ipf.message

            if self.request.params[
                    'mode'] == 'add' or not self.request.params.get(
                        'userPassword', '') == '':
                try:
                    ParamChecker.checkPassword('userPassword', 'userPassword2')
                except InvalidParameterFormat as ipf:
                    formok = False
                    errors.append(ipf.message)

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

                # @TODO request.params may contain multiple values per key... test & fix
                for k in self.request.params.iterkeys():
                    if k == 'fullMember' or k == 'lockedMember':
                        if self.request.params[k] == 'on':
                            self.session['reqparams'][k] = True
                        else:
                            self.session['reqparams'][k] = False
                    else:
                        self.session['reqparams'][k] = self.request.params[k]

                self.session.save()

                if self.request.params['mode'] == 'add':
                    raise HTTPRedirect('/members/addMember')
                else:
                    raise HTTPRedirect(
                        '/members/editMember/?member_id={0}'.format(member_id))

            return f(self)
Esempio n. 5
0
  def editAlias(self, alias=None, *args, **kwargs):
    c = TemplateContext()

    # vary form depending on mode (do that over ajax)
    if alias is None:
      action = 'Adding'
      c.mode = 'add'

      domains = self.mf.getDomains()
      c.select_domains = []
      for d in domains:
        c.select_domains.append([d.dc, d.dc])

    elif not alias == '':
      try:
        ParamChecker.checkEmail('alias')
      except:
        raise HTTPRedirect('/mails/index')

      action = 'Editing'
      c.alias = alias
      c.mode = 'edit'
      try:
        alias = self.mf.getAlias(alias)
        mail = ''

        for m in alias.mail:
          if not mail == '':
            mail += '\n'
          if not m == alias.dn_mail:
            mail += m

        c.mail = mail

        maildrop = ''

        for m in alias.maildrop:
          if not maildrop == '':
            maildrop += '\n'
          if not m == alias.dn_mail and not m in maildrop:
            maildrop += m

        c.maildrop = maildrop

      except LookupError:
        # @TODO implement better handler
        msg = _('No such alias!')
        return self.index(msg=msg)
    else:
      raise HTTPRedirect('/mails/index')

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

    return self.render('/mails/editAlias.mako', template_context=c)
Esempio n. 6
0
    def doEditMember(self):
        try:
            if self.request.params['mode'] == 'edit':
                member = self.mf.getUser(self.request.params['member_id'])
            else:
                member = Member()
                member.uid = self.request.params['member_id']

            for v in member.str_vars:
                if v in self.request.params:
                    setattr(member, v,
                            self.request.params.get(v).lstrip(' ').rstrip(' '))

            for v in member.bool_vars:
                if v in self.request.params:
                    setattr(member, v, True)

            if not self.request.params.get(
                    'userPassword', ''
            ) == '' and self.request.params[
                    'userPassword'] == self.request.params['userPassword2']:
                member.setPassword(self.request.params['userPassword'])
            ''' fullMember / lockedMember'''
            if 'fullMember' in self.request.params and not Config.get(
                    'mematool', 'group_fullmember') in member.groups:
                member.groups.append(Config.get('mematool',
                                                'group_fullmember'))
            elif not 'fullMember' in self.request.params and Config.get(
                    'mematool', 'group_fullmember') in member.groups:
                member.groups.remove(Config.get('mematool',
                                                'group_fullmember'))

            if 'lockedMember' in self.request.params and not Config.get(
                    'mematool', 'group_lockedmember') in member.groups:
                member.groups.append(
                    Config.get('mematool', 'group_lockedmember'))
            elif not 'lockedMember' in self.request.params and Config.get(
                    'mematool', 'group_lockedmember') in member.groups:
                member.groups.remove(
                    Config.get('mematool', 'group_lockedmember'))

            self.mf.saveMember(member)

            self.session['flash'] = _('Member details successfully edited')
            self.session.save()

            raise HTTPRedirect('/members/editMember/?member_id={0}'.format(
                self.request.params['member_id']))

        except LookupError:
            print 'No such user !'

        # @TODO make much more noise !
        raise HTTPRedirect('/members/showAllMembers')
Esempio n. 7
0
    def doLogin(self, username=None, password=None):
        try:
            ParamChecker.checkUsername('username', param=True)
            ParamChecker.checkPassword('password', 'password', param=True)
        except InvalidParameterFormat as ipf:
            return self.index(_('Invalid data'))

        try:
            ldap_connector = LdapConnector(username=username,
                                           password=password)
        except mematool.helpers.exceptions.InvalidCredentials:
            return self.index(_('Invalid credentials'))
        except mematool.helpers.exceptions.ServerError:
            return self.index(_('Server error, please retry later'))

        old_session_language = self.session.get('language', '')

        self.session.regenerate()
        self.session['username'] = username
        self.session['password'] = encodeAES(password)
        self.set_ldapcon(ldap_connector.get_connection())
        self.session['groups'] = self.mf.getUserGroupList(username)

        try:
            user = self.mf.getUser(self.session['username'])
        except:
            return self.index(_('Server error, please retry later'))

        self.session['user'] = user

        if self.is_admin():
            self.session[
                'pendingMemberValidations'] = self.pendingMemberValidations()

        uidNumber = user.uidNumber
        language = self.db.query(Preferences).filter(
            and_(Preferences.uidNumber == uidNumber,
                 Preferences.key == 'language')).one()

        if language.value in self.languages:
            self.session['language'] = language.value
        elif not old_session_language == '':
            self.session['language'] = old_session_language
        else:
            self.session['language'] = self.default_language

        log.info(username + ' logged in')

        if user.is_admin():
            raise HTTPRedirect('/members/index')
        else:
            raise HTTPRedirect('/profile/index')
Esempio n. 8
0
    def savePayment(self, member_id, items):
        """ Save a new or edited payment """
        verified = False

        if self.is_finance_admin() and ParamChecker.checkInt(
                'verified', param=True, optional=True):
            verified = True

        if items['idPayment'] > 0:
            try:
                np = self.db.query(Payment).filter(
                    Payment.id == items['idPayment']).one()
                np.verified = verified
            except:
                self.session['flash'] = _('Invalid record')
                self.session.save()
                raise HTTPRedirect(
                    '/payments/listPayments/?member_id={0}'.format(member_id))
        else:
            np = Payment()
            np.verified = verified
            np.status = 0

        for key, value in items.iteritems():
            setattr(np, key, value)

        try:
            np.uid = member_id
        except:
            self.session['flash'] = _('Invalid member')
            self.session.save()
            raise HTTPRedirect(
                '/payments/listPayments/?member_id={0}'.format(member_id))

        # Cleanup session
        if 'reqparams' in self.session:
            del (self.session['reqparams'])
        self.session.save()
        ##########

        self.db.add(np)
        self.db.commit()

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

        raise HTTPRedirect(
            '/payments/listPayments/?member_id={0}'.format(member_id))
Esempio n. 9
0
    def doEditAvatar(self):
        if not 'avatar' in self.request.params or not len(
                self.request.params['avatar'].value) > 0:
            raise HTTPRedirect('/profile/editAvatar')

        try:
            img_param = self.request.params['avatar'].file
            img = self._resizeImage(img_param)
            member = self.mf.getUser(self.session['username'])
            self.mf.updateAvatar(member, img)
        except:
            import sys, traceback
            traceback.print_exc(file=sys.stdout)

        raise HTTPRedirect('/profile/editAvatar')
Esempio n. 10
0
    def index(self):
        if self.is_admin() or self.mf.isUserInGroup(
                self.session.get('username'), 'office'):
            return self.showOutstanding()

        raise HTTPRedirect('/payments/listPayments/?member_id={0}'.format(
            self.session.get('username')))
Esempio n. 11
0
    def index(self, path=b"", **kwargs):
        """
        Delete the repository.
        """
        self.assertIsInstance(path, bytes)
        _logger.debug("repo delete [%r]", path)

        # Check user permissions
        repo_obj = self.validate_user_path(path)[0]

        # Validate the name
        confirm_name = kwargs.get('confirm_name', None)
        if confirm_name != repo_obj.display_name:
            _logger.info("bad confirmation %r != %r", confirm_name,
                         repo_obj.display_name)
            raise HTTPError(400, "bad confirmation")

        # Update the repository encoding
        _logger.info("deleting repository [%s]", repo_obj)
        repo_obj.delete()

        # Refresh repository list
        repos = self.app.currentuser.repos
        r = self.app.currentuser.get_repo(repo_obj.path)
        repos.remove(r.name)
        self.app.currentuser.repos = repos
        raise HTTPRedirect("/")
Esempio n. 12
0
    def doEdit(self):
        member = self.session.get('user')

        try:
            language = self.db.query(Preferences).filter(
                and_(Preferences.uidNumber == member.uidNumber,
                     Preferences.key == 'language')).one()
            language.last_change = datetime.datetime.now()
            language.value = self.request.params['language']

            self.session['language'] = language.value
            self.session['flash'] = _('Changes saved!')
            self.session['flash_class'] = 'success'
        except NoResultFound:
            pref = Preferences()
            pref.uidNumber = member.uidNumber
            pref.last_change = datetime.datetime.now().date()
            pref.key = 'language'
            pref.value = self.request.params['language']
            self.db.add(pref)

            self.session['language'] = cherrypy.request.params['language']

            self.session['flash'] = _('Changes saved!')
            self.session['flash_class'] = 'success'
        except:
            self.session['flash'] = _('Unknown error, nothing saved')
            self.session['flash_class'] = 'error'

        self.db.commit()

        self.session.save()
        raise HTTPRedirect('/preferences/edit')
Esempio n. 13
0
    def new_f(self, domain):
      formok = True
      errors = []
      items = {}

      try:
        ParamChecker.checkDomain('domain')
      except InvalidParameterFormat as ipf:
        formok = False
        errors.append(ipf.message)

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

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

        self.session.save()

        raise HTTPRedirect('/mails/editDomain')
      else:
        items['domain'] = domain

      return f(self, items)
Esempio n. 14
0
    def validateMember(self, member_id):
        try:
            member = self.mf.getUser(member_id)

            if member.validate:
                tm = self.db.query(TmpMember).filter(
                    TmpMember.id == member.uidNumber).first()
                member.givenName = tm.gn
                member.sn = tm.sn
                member.homePostalAddress = tm.homePostalAddress

                # @FIXME fix this nasty workaround
                if not tm.phone == '>>REMOVE<<':
                    member.homePhone = tm.phone
                else:
                    member.homePhone = ''

                member.mobile = tm.mobile
                member.mail = tm.mail
                member.xmppID = tm.xmppID

                self.mf.saveMember(member)
                self.db.delete(tm)
                self.db.commit()

                self.session['flash'] = _('Changes accepted')
                self.postValidationMail(member_id, member.mail, validated=True)
            else:
                self.session['flash'] = _('Nothing to validate!')

        except LookupError:
            self.session['flash'] = _('Member validation failed!')

        self.session.save()
        raise HTTPRedirect('/members/showAllMembers')
Esempio n. 15
0
    def deleteUser(self, member_id):
        try:
            self.mf.deleteUser(member_id)

            aliases = self.mf.getMaildropList(member_id)
            errors = ''
            for dn, attr in aliases.items():
                if errors == '':
                    errors = 'Could not auto-delete the following aliases:'

                m = re.match(r'^mail=([^,]+),', dn)
                if m:
                    alias = m.group(1)
                    url_ = url(controller='mails',
                               action='editAlias',
                               alias=alias)
                    errors += '\n<br/><a href="{0}" target="_blank">{1}</a>'.format(
                        url_, alias)

                if not errors == '':
                    if not 'errors' in self.session:
                        self.session['errors'] = []
                    self.session['errors'].append(literal(errors))

            self.session['flash'] = _('User successfully deleted')
            self.session.save()
        except LookupError:
            self.session['flash'] = _('Failed to delete user')
            self.session.save()

        # @TODO make much more noise !
        raise HTTPRedirect('/members/showAllMembers')
Esempio n. 16
0
File: main.py Progetto: xou/mcmatch
 def update_code_sample(self, sample):
   samples = os.listdir(code_sample_path)
   if not sample in samples:
     raise cherrypy.HTTPError(404, "Sample not found")
   f = open(os.path.join(code_sample_path, sample))
   cherrypy.session['code'] = f.read() # @UndefinedVariable
   f.close()
   raise HTTPRedirect("/")
Esempio n. 17
0
    def deletePayment(self, member_id, idPayment):
        """ Delete a payment specified by an id """
        try:
            ParamChecker.checkUsername('member_id', param=True)
            ParamChecker.checkInt('idPayment', param=True)
        except:
            raise HTTPRedirect('/members/index')

        try:
            np = self.db.query(Payment).filter(Payment.id == idPayment).one()
            self.db.delete(np)
            self.db.commit()
        except:
            ''' Don't care '''
            pass

        raise HTTPRedirect(
            '/payments/listPayments/?member_id={0}'.format(member_id))
Esempio n. 18
0
    def doDeleteAvatar(self):
        try:
            member = self.mf.getUser(self.session['username'])
            self.mf.updateAvatar(member, None)
        except:
            import sys, traceback
            traceback.print_exc(file=sys.stdout)

        raise HTTPRedirect('/profile/editAvatar')
Esempio n. 19
0
    def index(self, msg=None, msg_class='error'):
        if msg and not 'msg' in cherrypy.request.params:
            self.session['flash'] = msg
            self.session['flash_class'] = msg_class
            self.session.save()

        if self.is_admin():
            return self.listGroups()

        raise HTTPRedirect('/profile/index')
Esempio n. 20
0
    def bulkAdd(self, member_id):
        try:
            ParamChecker.checkUsername('member_id', param=True)
        except:
            raise HTTPRedirect('/payments/index')

        c = TemplateContext()
        c.member_id = member_id
        c.heading = _('Add bulk payments')

        return self.render('/payments/bulkAdd.mako', template_context=c)
Esempio n. 21
0
  def listAliases(self, domain, *args, **kwargs):
    try:
      ParamChecker.checkDomain('domain', param=True)
    except:
      raise HTTPRedirect('/mails/index')

    c = TemplateContext()
    c.heading = _('Aliases for domain: %s') % (domain)
    c.domain = domain
    c.aliases = self.mf.getAliases(domain)

    return self.render('/mails/listAliases.mako', template_context=c)
Esempio n. 22
0
    def doBulkAdd(self, member_id, months, verified=None):
        try:
            ParamChecker.checkUsername('member_id', param=True)
            ParamChecker.checkInt('months', param=True, max_len=2)
        except:
            raise HTTPRedirect('/payments/index')

        lastDate = self._getLastPayment(member_id)
        months = int(months)

        if self.is_finance_admin():
            try:
                ParamChecker.checkInt('verified', param=True, max_len=1)
                verified = True
            except:
                verified = False

        try:
            for i in range(months):
                p = Payment()
                p.uid = member_id
                p.date = lastDate + relativedelta(months=i)
                p.status = 0
                p.verified = verified

                self.db.add(p)

            self.db.commit()

            self.session['flash'] = _('Payments added')
            self.session['flash_class'] = 'success'
        except Exception as e:
            self.session['flash'] = _('Operation failed')
            self.session['flash_class'] = 'error'

        self.session.save()

        raise HTTPRedirect(
            '/payments/listPayments/?member_id={0}'.format(member_id))
Esempio n. 23
0
 def list_products(self, event):
     url = self.get_url()
     if not url.endswith("/"):
         raise HTTPRedirect(self.get_hostname() + "/" + url + "/")
     links = []
     if "evtids" in event:
         for pro in self._products:
             if "evtset" in pro["show"]:
                 links.append(pro["file"])
         for evid in event["evtids"]:
             links.append("%s/" % evid)
     else:
         for pro in self._products:
             if "evt" in pro["show"]:
                 links.append(pro["file"])
     return self.links2html(links)
Esempio n. 24
0
    def deleteGroup(self, gid):
        try:
            ParamChecker.checkUsername('gid', param=True)
        except:
            raise HTTPRedirect('/groups/index')

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

        if result:
            msg = _('Group successfully deleted')
            msg_class = 'success'
        else:
            msg = _('Failed to delete group!')
            msg_class = 'error'

        return self.index(msg=msg, msg_class=msg_class)
Esempio n. 25
0
    def unmanageGroup(self, gid):
        try:
            ParamChecker.checkUsername('gid', param=True)
        except:
            raise HTTPRedirect('/groups/index')

        result = self.mf.unmanageGroup(gid)

        if result:
            msg = _('Group no longer managed')
            msg_class = 'success'
        else:
            msg = _('Failed to remove group from management!')
            msg_class = 'error'

        return self.index(msg=msg, msg_class=msg_class)
Esempio n. 26
0
        def new_f(self, gid, users=None):
            formok = True
            errors = []
            items = {}

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

            items['users'] = []

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

                    for k in 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:
                self.session['errors'] = errors
                self.session['reqparams'] = {}

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

                self.session.save()

                raise HTTPRedirect('/groups/editGroup/?gid={0}'.format(gid))
            else:
                items['gid'] = gid

            return f(self, items)
Esempio n. 27
0
    def get_ldapcon(self):
        #@todo: this is not enough ... ass a cherrypy before-handler
        if self.session.get('username') is None or self.session.get(
                'password') is None:
            raise HTTPRedirect('/')

        if self.ldapcon is None:
            username = self.session.get('username')
            password = decodeAES(self.session.get('password'))
            self.ldapcon = LdapConnector(username, password).get_connection()
        else:
            try:
                self.ldapcon.whoami_s()
            except ldap.SERVER_DOWN:
                #@todo make this cleaner refactor
                username = self.session.get('username')
                password = decodeAES(self.session.get('password'))
                self.ldapcon = LdapConnector(username,
                                             password).get_connection()

        return self.ldapcon
Esempio n. 28
0
  def doEditAlias(self, items, *args, **kwargs):
    try:
      alias = Alias()
      alias.dn_mail = items['alias']
      alias.mail = items['mail']
      alias.maildrop = items['maildrop']

      if items['mode'] == 'edit':
        self.mf.updateAlias(alias)
      else:
        self.mf.addAlias(alias)

      self.session['flash'] = _('Alias successfully edited')
      self.session.save()
    except Exception as e:
      import sys, traceback
      traceback.print_exc(file=sys.stdout)
      msg = _('Error while editing alias')
      return self.index(msg=msg)

    raise HTTPRedirect('/mails/editAlias/?alias={0}'.format(alias.dn_mail))
Esempio n. 29
0
        def new_f(self, **kwargs):
            # @TODO request.params may contain multiple values per key... test & fix
            formok = True
            errors = []

            m = self.mf.getUser(self.session.get('username'))

            for v in m.str_vars:
                if v in self.request.params:
                    setattr(m, v, self.request.params.get(v, ''))

            try:
                m.check()
            except InvalidParameterFormat as ipf:
                formok = False
                errors += ipf.message

            if not self.request.params.get(
                    'userPassword', ''
            ) == '' and self.request.params[
                    'userPassword'] == self.request.params['userPassword2']:
                try:
                    ParamChecker.checkPassword('userPassword', 'userPassword2')
                except InvalidParameterFormat as ipf:
                    formok = False
                    errors.append(ipf.message)

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

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

                self.session.save()

                raise HTTPRedirect('/profile/edit')

            return f(self)
Esempio n. 30
0
  def deleteAlias(self, alias, *args, **kwargs):
    try:
      ParamChecker.checkEmail('alias', param=True)
    except:
      raise HTTPRedirect('/mails/index')

    try:
      result = self.mf.deleteAlias(alias)

      if result:
        msg = _('Alias successfully deleted')
        msg_class = 'success'
      else:
        msg = _('Failed to delete alias!')
        msg_class = 'error'
    except:
      import sys, traceback
      traceback.print_exc(file=sys.stdout)
      msg = _('Failed to delete alias!')
      msg_class = 'error'

    return self.index(msg=msg, msg_class=msg_class)