Esempio n. 1
0
class BasicPylonsController(WSGIController):
    """Mock Pylons controller"""

    sub1 = SubController1()

    panel = SecurePanel()

    def index(self, **kwargs):
        return 'hello world'

    @ActionProtector(in_group('admins'))
    def admin(self, *args, **kwargs):
        return 'got to admin'

    def troll_detected(reason):
        # Let's ignore the reason
        return 'Trolls are banned'

    @ActionProtector(All(not_anonymous(), Not(is_user('sballmer'))),
                     denial_handler=troll_detected)
    def leave_comment(self):
        return 'Comment accepted'

    @special_require(not_anonymous())
    def logout(self):
        return 'You have been logged out'

    @special_require(All(not_anonymous(), Not(is_user('sballmer'))),
                     denial_handler=troll_detected)
    def start_thread(self):
        return 'You have started a thread'

    @ActionProtector(Not(not_anonymous()))
    def get_parameter(self, something):
        # Checking that parameters are received
        return 'Parameter received: %s' % something

    def boolean_predicate(self):
        p = not_anonymous()
        return 'The predicate is %s' % bool(p)

    def is_met_util(self):
        if is_met(not_anonymous()):
            return 'You are not anonymous'
        return 'You are anonymous'

    def not_met_util(self):
        if not_met(not_anonymous()):
            return 'You are anonymous'
        return 'You are not anonymous'
Esempio n. 2
0
class AccountsController(BaseController):
    "Accounts controller"

    def __before__(self):
        "set context"
        BaseController.__before__(self)
        if self.identity:
            c.user = self.identity['user']
        else:
            c.user = None
        c.selectedtab = 'accounts'

    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > arrow.utcnow().datetime:
                msg = _('You have been banned after' ' several failed logins')
                log.info(msg)
                abort(409, msg)
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = arrow.utcnow().datetime + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if arrow.utcnow().datetime > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            c.form = ResetPwForm(request.POST, csrf_context=session)
            return self.render('/accounts/login.html')

    def loggedin(self):
        "Landing page"
        came_from = (unquote(str(request.params.get('came_from', '')))
                     or url('/'))
        if not self.identity:
            if 'repoze.who.logins' in request.environ:
                login_counter = request.environ['repoze.who.logins'] + 1
            else:
                abort(409)
            redirect(
                url('/accounts/login',
                    came_from=came_from,
                    __logins=login_counter))
        userid = self.identity['repoze.who.userid']
        user = self.identity['user']
        if user is None:
            try:
                user, local_part, domain, domains = add_user(userid)
                msg = _('First time Login from external auth,'
                        ' your local account was created')
                user_address_update(user, local_part, domain, domains,
                                    self.identity)
            except IntegrityError:
                Session.rollback()
                redirect(url('/logout'))
            except ldap.LDAPError:
                pass
        else:
            if not user.active:
                redirect(url('/logout'))
            msg = _('Login successful, Welcome back %(username)s !' %
                    dict(username=userid))
        update_login(user)
        if user.is_peleb:
            for domain in user.domains:
                if check_language(domain.language):
                    session['lang'] = domain.language
                    session.save()
                    break
        session['taskids'] = []
        session.save()
        info = auditmsgs.ACCOUNTLOGIN_MSG % dict(u=user.username)
        audit_log(user.username, 6, unicode(info), request.host,
                  request.remote_addr,
                  arrow.utcnow().datetime)
        flash(msg)
        log.info(msg)
        redirect(url(came_from))

    # pylint: disable-msg=R0201
    def loggedout(self):
        "Logged out page"
        session.clear()
        if 'theme' in session:
            del session['theme']
        session.save()
        came_from = (unquote(str(request.params.get('came_from', '')))
                     or url('/accounts/login'))
        redirect(url(came_from))

    def passwdreset(self):
        """Render password reset page"""
        c.came_from = '/'
        c.login_counter = 0
        c.form = ResetPwForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            key_seed = '%s%s' % (c.form.email.data, arrow.utcnow().ctime())
            token = hashlib.sha1(key_seed).hexdigest()
            user = Session.query(User)\
                            .filter(User.email == c.form.email.data)\
                            .one()
            if not user.local:
                flash(
                    _('The account %s is an external account, use your'
                      ' External systems to change the password. '
                      'Contact your system adminstrator if you do not '
                      'know which external systems you authenticate to') %
                    user.email)
                redirect(url('/accounts/login'))
            rtoken = Session\
                    .query(ResetToken.used)\
                    .filter(ResetToken.used == false())\
                    .filter(ResetToken.user_id == user.id)\
                    .all()
            if not rtoken:
                rtoken = ResetToken(token, user.id)
                Session.add(rtoken)
                Session.commit()
                host = URL_PREFIX_RE.sub('', request.host_url)
                c.username = user.username
                c.firstname = user.firstname or user.username
                c.reset_url = url('accounts-pw-token-reset',
                                  token=token,
                                  host=host)
                text = self.render('/email/pwreset.txt')
                mailer = Mailer(get_conf_options(config))
                mailer.start()
                sdrnme = config.get('baruwa.custom.name', 'Baruwa')
                email = Msg(author=[(sdrnme,
                                     config.get('baruwa.reports.sender'))],
                            to=[('', c.form.email.data)],
                            subject=_("[%s] Password reset request") % sdrnme)
                email.plain = text
                mailer.send(email)
                mailer.stop()
            flash(
                _('An email has been sent to the address provided, '
                  'please follow the instructions in that email to '
                  'reset your password.'))
            redirect(url('/accounts/login'))
        return self.render('/accounts/login.html')

    def pwtokenreset(self, token):
        """Reset password using token"""
        try:
            token = Session.query(ResetToken)\
                    .filter(ResetToken.token == token)\
                    .filter(ResetToken.used == false()).one()
            threshold = token.timestamp + timedelta(minutes=20)
            if arrow.utcnow().datetime > threshold:
                Session.delete(token)
                Session.commit()
                raise NoResultFound
            user = self._get_user(token.user_id)
            if not user or user.is_superadmin:
                raise NoResultFound
            passwd = mkpasswd()
            user.set_password(passwd)
            Session.add(user)
            Session.delete(token)
            Session.commit()
            c.passwd = passwd
            c.firstname = user.firstname or user.username
            text = self.render('/email/pwchanged.txt')
            mailer = Mailer(get_conf_options(config))
            mailer.start()
            sdrnme = config.get('baruwa.custom.name', 'Baruwa')
            email = Msg(author=[(sdrnme, config.get('baruwa.reports.sender'))],
                        to=[('', user.email)],
                        subject=_("[%s] Password reset") % sdrnme)
            email.plain = text
            mailer.send(email)
            mailer.stop()
            flash(
                _('The password has been reset, check your email for'
                  ' the temporary password you should use to login.'))
        except NoResultFound:
            msg = _('The token used is invalid or does not exist')
            flash_alert(msg)
            log.info(msg)
        redirect(url('/accounts/login'))

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def pwchange(self, userid):
        """Reset a user password"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        c.form = ChangePasswordForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            if user.local and not user.is_superadmin:
                change_user_pw(user, c.user, c.form.password1.data,
                               request.host, request.remote_addr)
                msg = _('The account password for %(name)s has been reset') \
                        % dict(name=user.username)
                flash(msg)
            else:
                if user.is_superadmin:
                    flash(_('Admin accounts can not be modified via the web'))
                else:
                    flash(
                        _('This is an external account, use'
                          ' external system to reset the password'))
            redirect(url('account-detail', userid=user.id))
        c.id = userid
        c.username = user.username
        c.posturl = 'accounts-pw-change'
        return self.render('/accounts/pwchange.html')

    @ActionProtector(not_anonymous())
    def upwchange(self, userid):
        """User change own password"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        if user.id != c.user.id or c.user.is_superadmin:
            abort(403)
        c.form = UserPasswordForm(request.POST, csrf_context=session)
        if (request.method == 'POST' and c.form.validate()
                and user.validate_password(c.form.password3.data)):
            if user.local:
                user.set_password(c.form.password1.data)
                Session.add(user)
                Session.commit()
                flash(
                    _('The account password for %(name)s has been reset') %
                    dict(name=user.username))
                info = auditmsgs.PASSWORDCHANGE_MSG % dict(u=user.username)
                audit_log(c.user.username, 2, unicode(info), request.host,
                          request.remote_addr,
                          arrow.utcnow().datetime)
            else:
                flash(
                    _('This is an external account, use'
                      ' external system to reset the password'))
            redirect(url('account-detail', userid=user.id))
        elif (request.method == 'POST'
              and not user.validate_password(c.form.password3.data)
              and not c.form.password3.errors):
            flash_alert(
                _('The old password supplied does'
                  ' not match our records'))
        c.id = userid
        c.username = user.username
        c.posturl = 'accounts-pw-uchange'
        return self.render('/accounts/pwchange.html')

    # pylint: disable-msg=W0622
    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def index(self, page=1, orgid=None, domid=None, format=None):
        """GET /accounts/: Paginate items in the collection"""
        num_items = session.get('accounts_num_items', 10)
        c.form = BulkDelUsers(request.POST, csrf_context=session)
        if request.method == 'POST':
            if c.form.accountid.data and \
                str(c.user.id) in c.form.accountid.data:
                c.form.accountid.data.remove(str(c.user.id))
            if c.form.accountid.data and c.form.whatdo.data == 'disable':
                Session.query(User)\
                    .filter(User.id.in_(c.form.accountid.data))\
                    .update({'active': False}, synchronize_session='fetch')
                Session.commit()
            if c.form.accountid.data and c.form.whatdo.data == 'enable':
                Session.query(User)\
                        .filter(User.id.in_(c.form.accountid.data))\
                        .update({'active': True}, synchronize_session='fetch')
                Session.commit()
            if c.form.accountid.data and c.form.whatdo.data == 'delete':
                session['bulk_account_delete'] = c.form.accountid.data
                session.save()
                # redirect for confirmation
                redirect(url('accounts-confirm-delete'))
        users = Session.query(User.id, User.username, User.firstname,
                              User.lastname, User.email, User.active,
                              User.local, User.account_type).order_by(User.id)
        usrcount = Session.query(User.id)
        if c.user.is_domain_admin:
            users = users.join(domain_users, (dom_owns,
                                domain_users.c.domain_id ==
                                dom_owns.c.domain_id),
                                (oas,
                                dom_owns.c.organization_id ==
                                oas.c.organization_id))\
                                .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                                    domain_users.c.domain_id ==
                                    dom_owns.c.domain_id),
                                    (oas,
                                    dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)
        if domid:
            users = users.filter(
                and_(domain_users.c.domain_id == domid,
                     domain_users.c.user_id == User.id))
            usrcount = usrcount.filter(
                and_(domain_users.c.domain_id == domid,
                     domain_users.c.user_id == User.id))
        if orgid:
            users = users.filter(
                and_(
                    domain_users.c.user_id == User.id,
                    domain_users.c.domain_id == dom_owns.c.domain_id,
                    dom_owns.c.organization_id == orgid,
                ))
            usrcount = usrcount.filter(
                and_(
                    domain_users.c.user_id == User.id,
                    domain_users.c.domain_id == dom_owns.c.domain_id,
                    dom_owns.c.organization_id == orgid,
                ))

        users = users.distinct(User.id)
        usrcount = usrcount.distinct(User.id)

        pages = paginate.Page(users,
                              page=int(page),
                              items_per_page=num_items,
                              item_count=usrcount.count())
        if format == 'json':
            response.headers['Content-Type'] = 'application/json'
            data = convert_acct_to_json(pages, orgid)
            return data

        c.page = pages
        c.domid = domid
        c.orgid = orgid
        return self.render('/accounts/index.html')

    # pylint: disable-msg=R0914,W0142,W0613
    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def search(self, format=None):
        "Search for accounts"
        total_found = 0
        search_time = 0
        num_items = session.get('accounts_num_items', 10)
        qry = request.GET.get('q', '')
        doms = request.GET.get('d', None)
        kwds = {'presliced_list': True}
        page = int(request.GET.get('p', 1))
        conn = SphinxClient()
        sphinxopts = extract_sphinx_opts(config['sphinx.url'])
        conn.SetServer(sphinxopts.get('host', '127.0.0.1'))
        conn.SetMatchMode(SPH_MATCH_EXTENDED2)
        conn.SetFieldWeights(
            dict(username=50, email=30, firstname=10, lastname=10))
        if page == 1:
            conn.SetLimits(0, num_items, 500)
        else:
            page = int(page)
            offset = (page - 1) * num_items
            conn.SetLimits(offset, num_items, 500)
        if doms:
            conn.SetFilter('domains', [
                int(doms),
            ])
        if c.user.is_domain_admin:
            # crcs = get_dom_crcs(Session, c.user)
            domains = Session.query(Domain.id).join(dom_owns,
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)
            conn.SetFilter('domains', [domain[0] for domain in domains])
        qry = clean_sphinx_q(qry)
        try:
            results = conn.Query(qry, 'accounts, accounts_rt')
        except (socket.timeout, struct.error):
            redirect(request.path_qs)
        qry = restore_sphinx_q(qry)
        if results and results['matches']:
            ids = [hit['id'] for hit in results['matches']]
            total_found = results['total_found']
            search_time = results['time']
            users = Session.query(User.id,
                                    User.username,
                                    User.firstname,
                                    User.lastname,
                                    User.email,
                                    User.active,
                                    User.local,
                                    User.account_type)\
                                .filter(User.id.in_(ids))\
                                .order_by(User.id)\
                                .all()
            usercount = total_found
        else:
            users = []
            usercount = 0
        c.q = qry
        c.d = doms
        c.total_found = total_found
        c.search_time = search_time
        c.page = paginate.Page(users,
                               page=int(page),
                               items_per_page=num_items,
                               item_count=usercount,
                               **kwds)
        return self.render('/accounts/searchresults.html')

    @ActionProtector(All(not_anonymous(), CanAccessAccount()))
    def detail(self, userid):
        """GET /accounts/userid/ Show a specific item"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        c.account = user
        return self.render('/accounts/account.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def add(self):
        """/accounts/new"""
        c.form = user_add_form(c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            try:
                user = create_user(c.form, c.user.username, request.host,
                                   request.remote_addr)
                flash(
                    _('The account: %(user)s was created successfully') %
                    {'user': user.username})
                redirect(url('account-detail', userid=user.id))
            except IntegrityError:
                Session.rollback()
                flash_alert(
                    _('Either the username or email address already exist'))
        return self.render('/accounts/new.html')

    @ActionProtector(All(not_anonymous(), CanAccessAccount()))
    def edit(self, userid):
        """GET /accounts/edit/id: Form to edit an existing item"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = user_update_form(user, c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(userid=user.id)
            if update_changed(c.form, FORM_FIELDS, user):
                try:
                    update_user(user, c.user, request.host,
                                request.remote_addr)
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active
                        and c.form.active.data is False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/edit.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        del c.form.domains
        if request.method == 'POST':
            if c.form.validate():
                delete_user(user, c.user, request.host, request.remote_addr)
                flash(_('The account has been deleted'))
                redirect(url(controller='accounts', action='index'))
        else:
            flash_info(
                _('The account: %(a)s and all associated data'
                  ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/delete.html')

    @ActionProtector(not_anonymous())
    def confirm_delete(self):
        "Confirm mass delete"
        accountids = session.get('bulk_account_delete', [])
        if not accountids:
            redirect(url(controller='accounts', action='index'))

        num_items = 10
        if len(accountids) > num_items and len(accountids) <= 20:
            num_items = 20
        if len(accountids) > num_items and len(accountids) <= 50:
            num_items = 50
        if len(accountids) > num_items and len(accountids) <= 100:
            num_items = 100

        users = Session.query(User).filter(User.id.in_(accountids))
        usrcount = Session.query(User.id)

        if c.user.is_domain_admin and usrcount:
            users = users.join(domain_users, (dom_owns,
                    domain_users.c.domain_id == dom_owns.c.domain_id),
                    (oas, dom_owns.c.organization_id == oas.c.organization_id))\
                    .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                        domain_users.c.domain_id == dom_owns.c.domain_id),
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)

        if request.method == 'POST':
            tasks = []
            # try:
            for account in users.all():
                info = auditmsgs.DELETEACCOUNT_MSG % dict(u=account.username)
                Session.delete(account)
                tasks.append([
                    c.user.username, 4,
                    unicode(info), request.host, request.remote_addr,
                    arrow.utcnow().datetime
                ])
            Session.commit()
            del session['bulk_account_delete']
            session.save()
            backend_user_update(None, True)
            for task in tasks:
                audit_log(*task)
            flash(_('The accounts have been deleted'))
            redirect(url(controller='accounts'))
        else:
            flash(
                _('The following accounts are about to be deleted,'
                  ' this action is not reversible, Do you wish to '
                  'continue ?'))

        try:
            c.page = paginate.Page(users,
                                   page=1,
                                   items_per_page=num_items,
                                   item_count=usrcount.count())
        except DataError:
            msg = _('An error occured try again')
            flash_alert(msg)
            log.info(msg)
            redirect(url(controller='accounts', action='index'))
        return self.render('/accounts/confirmbulkdel.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def addaddress(self, userid):
        "Add address"
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = AddressForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                addr = create_address(c.form, user, c.user, request.host,
                                      request.remote_addr)
                flash(
                    _('The alias address %(address)s was successfully created.'
                      % dict(address=addr.address)))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(url(controller='accounts', action='detail',
                         userid=userid))
        c.id = userid
        return self.render('/accounts/addaddress.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def editaddress(self, addressid):
        "Edit address"
        address = get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                if (address.address != c.form.address.data
                        or address.enabled != c.form.enabled.data):
                    update_address(c.form, address, c.user, request.host,
                                   request.remote_addr)
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(
                url(controller='accounts',
                    action='detail',
                    userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return self.render('/accounts/editaddress.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def deleteaddress(self, addressid):
        "Delete address"
        address = get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            user_id = delete_address(address, c.user, request.host,
                                     request.remote_addr)
            flash(_('The address has been deleted'))
            redirect(
                url(controller='accounts', action='detail', userid=user_id))
        c.id = addressid
        c.userid = address.user_id
        return self.render('/accounts/deleteaddress.html')

    def set_language(self):
        "Set the language"
        nextpage = request.params.get('next', None)
        if not nextpage:
            nextpage = request.headers.get('Referer', None)
        if not nextpage:
            nextpage = '/'
        if '://' in nextpage:
            from_url = urlparse(nextpage)
            nextpage = from_url[2]
        lang_code = request.params.get('language', None)
        if lang_code and check_language(lang_code):
            session['lang'] = lang_code
            session.save()
        params = []
        for param in request.params:
            if param not in ['language', 'amp']:
                value = request.params[param]
                if value:
                    if (param == 'came_from'
                            and '://' in urllib2.unquote(value)):
                        urlparts = urlparse(urllib2.unquote(value))
                        value = urlparts[2] or '/'
                    params.append('%s=%s' %
                                  (urllib2.quote(param), urllib2.quote(value)))
        if 'lc=1' not in params:
            params.append('lc=1')
        if params:
            nextpage = "%s?%s" % (nextpage, '&amp;'.join(params))
        redirect(nextpage)

    @ActionProtector(All(not_anonymous(), OwnsDomain()))
    def import_accounts(self, domainid):
        "import accounts"
        try:
            cachekey = u'domain-%s' % domainid
            domain = Session.query(Domain.id, Domain.name)\
                    .filter(Domain.id == domainid)\
                    .options(FromCache('sql_cache_med', cachekey)).one()
        except NoResultFound:
            abort(404)

        c.form = ImportCSVForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            basedir = config['pylons.cache_dir']
            csvdata = request.POST['csvfile']
            if hasattr(csvdata, 'filename'):
                dstfile = os.path.join(basedir, 'uploads',
                                       csvdata.filename.lstrip(os.sep))
                if not os.path.exists(dstfile) and iscsv(csvdata.file):
                    csvfile = open(dstfile, 'w')
                    shutil.copyfileobj(csvdata.file, csvfile)
                    csvdata.file.close()
                    csvfile.close()
                    task = importaccounts.apply_async(args=[
                        domainid, dstfile, c.form.skipfirst.data, c.user.id
                    ])
                    session['taskids'].append(task.task_id)
                    session['acimport-count'] = 1
                    session['acimport-file'] = dstfile
                    session.save()
                    msg = _('File uploaded, and is being processed, this page'
                            ' will automatically refresh to show the status')
                    flash(msg)
                    log.info(msg)
                    redirect(url('accounts-import-status',
                                 taskid=task.task_id))
                else:
                    filename = csvdata.filename.lstrip(os.sep)
                    if not iscsv(csvdata.file):
                        msg = _('The file: %s is not a CSV file') % filename
                        flash_alert(msg)
                        log.info(msg)
                    else:
                        msg = _('The file: %s already exists and'
                                ' is being processed.') % filename
                        flash_alert(msg)
                        log.info(msg)
                    csvdata.file.close()
            else:
                msg = _('No CSV was file uploaded, try again')
                flash_alert(msg)
                log.info(msg)

        c.domain = domain
        return self.render('/accounts/importaccounts.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def import_status(self, taskid):
        "import status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            msg = _('The task status requested has expired or does not exist')
            flash(msg)
            log.info(msg)
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    msg = _('Error occured in processing %s') % result.result
                    flash_alert(msg)
                    log.info(msg)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='accounts'))
            backend_user_update(None, True)
            audit_log(c.user.username, 3, unicode(auditmsgs.ACCOUNTIMPORT_MSG),
                      request.host, request.remote_addr,
                      arrow.utcnow().datetime)
        else:
            session['acimport-count'] += 1
            if (session['acimport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['acimport-file'])
                except OSError:
                    pass
                del session['acimport-count']
                session.save()
                msg = _('The import could not be processed,'
                        ' try again later')
                flash_alert(msg)
                log.info(msg)
                redirect(url(controller='accounts'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return self.render('/accounts/importstatus.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def export_accounts(self, domainid=None, orgid=None):
        "export domains"
        task = exportaccounts.apply_async(args=[domainid, c.user.id, orgid])
        if 'taskids' not in session:
            session['taskids'] = []
        session['taskids'].append(task.task_id)
        session['acexport-count'] = 1
        session.save()
        msg = _('Accounts export is being processed')
        flash(msg)
        log.info(msg)
        redirect(url('accounts-export-status', taskid=task.task_id))

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def export_status(self, taskid):
        "export status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            msg = _('The task status requested has expired or does not exist')
            flash(msg)
            log.info(msg)
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                msg = _('Error occured in processing %s') % result.result
                if c.user.is_superadmin:
                    flash_alert(msg)
                    log.info(msg)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                    log.info(msg)
                redirect(url(controller='accounts', action='index'))
            results = dict(
                f=True if not result.result['global_error'] else False,
                id=taskid,
                global_error=result.result['global_error'])
            audit_log(c.user.username, 5, unicode(auditmsgs.ACCOUNTEXPORT_MSG),
                      request.host, request.remote_addr,
                      arrow.utcnow().datetime)
        else:
            try:
                session['acexport-count'] += 1
            except KeyError:
                session['acexport-count'] = 1
            session.save()
            if (session['acexport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['acexport-count']
                session.save()
                msg = _('The export could not be processed, try again later')
                flash_alert(msg)
                log.info(msg)
                redirect(url(controller='accounts', action='index'))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        dwn = request.GET.get('d', None)
        if finished and (dwn and dwn == 'y'):
            response.content_type = 'text/csv'
            response.headers['Cache-Control'] = 'max-age=0'
            csvdata = result.result['f']
            disposition = 'attachment; filename=accounts-export-%s.csv' % \
                            taskid
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(csvdata)
            return csvdata
        return self.render('/accounts/exportstatus.html')

    # pylint: disable-msg=R0201,W0613
    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def setnum(self, format=None):
        "Set number of account items returned"
        num = check_num_param(request)

        if num and num in [10, 20, 50, 100]:
            session['accounts_num_items'] = num
            session.save()
        nextpage = request.headers.get('Referer', '/')
        if '://' in nextpage:
            from_url = urlparse(nextpage)
            nextpage = from_url[2]
        redirect(nextpage)
Esempio n. 3
0
from baruwa.model.meta import Session
from baruwa.model.auth import LDAPSettings, RadiusSettings
from baruwa.model.accounts import Group, domain_owners
from baruwa.model.accounts import organizations_admins as oa
from baruwa.model.domains import DomainAlias
from baruwa.model.domains import Domain, DeliveryServer, AuthServer
from baruwa.forms.domains import BulkDelDomains, AddLDAPSettingsForm
from baruwa.forms.domains import AddDomainForm, AddDeliveryServerForm
from baruwa.forms.domains import AddAuthForm, AUTH_PROTOCOLS, EditDomainAlias
from baruwa.forms.domains import AddDomainAlias, AddRadiusSettingsForm
from baruwa.lib.audit.msgs.domains import *

log = logging.getLogger(__name__)


@ControllerProtector(All(not_anonymous(), OnlyAdminUsers()))
class DomainsController(BaseController):
    def __before__(self):
        "set context"
        BaseController.__before__(self)
        if self.identity:
            c.user = self.identity['user']
        else:
            c.user = None
        c.selectedtab = 'domains'

    def _get_server(self, destinationid):
        "utility"
        try:
            cachekey = u'deliveryserver-%s' % destinationid
            q = Session.query(DeliveryServer)\
class ProyectoController(BaseController):
    allow_only = not_anonymous(
        msg='Solo usuarios registrados pueden acceder a los proyectos')

    @expose()
    def index(self, **named):
        """Handle the front-page."""
        redirect('/proyecto/lista')

    @expose(template='gestionitem.templates.proyectoTmpl.lista')
    def lista(self, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        expresion = named.get('expresion')
        orden = named.get('submit')
        proyectos = []

        id = identity['user']
        for grupo in id.groups:
            if (grupo.group_name == 'Administrador'):
                if (orden == None or orden == 'Listar Todos'):
                    proyectos = DBSession.query(Proyecto).filter(
                        Proyecto.estado != 4).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like(
                            '%' + expresion +
                            '%')).filter(Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion +
                                '%')).filter(Proyecto.estado != 4).all()
                    proyectos = proyectoxdescripcion + proyectoxlider + proyectoxestado
                    muestraBoton = "true"

            if (grupo.group_name == 'LiderProyecto'):
                if (orden == None or orden == 'Listar Todos'):
                    proyectosLider = DBSession.query(Proyecto).filter(
                        Proyecto.id_lider == id.user_id).filter(
                            Proyecto.estado != 4).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.id_lider == id.user_id).filter(
                                    Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like('%' + expresion + '%')
                    ).filter(Proyecto.id_lider == id.user_id).filter(
                        Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion + '%')).filter(
                                    Proyecto.id_lider == id.user_id).filter(
                                        Proyecto.estado != 4).all()
                    proyectosLider = proyectoxdescripcion + proyectoxlider + proyectoxestado
                    muestraBoton = "true"
                elif (orden):
                    proyectosLider = DBSession.query(Proyecto).filter(
                        Proyecto.id_lider == id.user_id).filter(
                            Proyecto.estado != 4).all()
                    muestraBoton = "false"

                for proyect in proyectosLider:
                    if (proyect in proyectos):
                        proyect.setDefinir()
                        proyect.setmostrarFases()
                        indice = proyectos.index(proyect)
                        proyectos[indice] = proyect

                    else:
                        proyect.setDefinir()
                        proyect.setmostrarFases()
                        proyectos.append(proyect)

            if (grupo.group_name == 'Desarrollador'
                    or grupo.group_name == 'Aprobador'):
                proyectosDesarrollador = []
                ufrs = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.user_id == id.user_id).all()

                if (orden == None or orden == 'Listar Todos'):
                    for ufr in ufrs:
                        try:
                            fase = DBSession.query(Fase).join(
                                (Proyecto, Fase.proyectoObj)).filter(
                                    Fase.id == ufr.fase_id).filter(
                                        Proyecto.estado != 4).one()
                            proyectosDesarrollador.append(fase.proyectoObj)
                        except:
                            pass
                    proyectosDesarrolladorset = set(proyectosDesarrollador)
                    proyectosDesarrollador = list(proyectosDesarrolladorset)
                    muestraBoton = "false"

                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like(
                            '%' + expresion +
                            '%')).filter(Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion +
                                '%')).filter(Proyecto.estado != 4).all()
                    proyectosaux = proyectoxlider + proyectoxdescripcion + proyectoxestado
                    proyectosauxset = set(proyectosaux)
                    proyectosaux = list(proyectosauxset)

                    for ufr in ufrs:
                        if ufr.fase.proyectoObj in proyectosaux:
                            proyectosDesarrollador.append(ufr.fase.proyectoObj)
                    proyectosDesarrolladorset = set(proyectosDesarrollador)
                    proyectosDesarrollador = list(proyectosDesarrolladorset)
                    muestraBoton = "true"

                if proyectos.__len__() > 0:
                    for proyecto1 in proyectosDesarrollador:
                        if proyecto1 in proyectos:
                            proyecto1.setmostrarFases()
                        else:
                            proyecto1.setmostrarFases()
                            proyectos.append(proyecto1)

                else:
                    proyectos = proyectosDesarrollador
                    for proyecto12 in proyectos:
                        proyecto12.setmostrarFases()

        proset = set(proyectos)
        proyectos = list(proset)

        from webhelpers import paginate

        count = proyectos.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            proyectos,
            page,
            item_count=count,
            items_per_page=5,
        )
        proyectos = currentPage.items
        return dict(page='Lista de proyectos',
                    proyectos=proyectos,
                    subtitulo='Proyectos',
                    user=user,
                    muestraBoton=muestraBoton,
                    currentPage=currentPage)

    @expose('gestionitem.templates.proyectoTmpl.nuevo')
    @require(
        All(in_group('Administrador'),
            has_permission('crear proyecto'),
            msg='Debe poseer Rol "Administrador" para crear nuevos proyectos'))
    def nuevo(self):
        """Handle the front-page."""
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        lideres = DBSession.query(User).join(
            (Rol,
             User.groups)).filter(Rol.group_name == 'LiderProyecto').all()
        nombreProyectos = []
        proyectos = DBSession.query(Proyecto).all()
        for proyecto in proyectos:
            nombreProyectos.append(proyecto.descripcion)
            nombreProyectos.append(",")
        return dict(page='Nuevo Proyecto',
                    lideres=lideres,
                    nombreProyectos=nombreProyectos,
                    user=user)

    @expose()
    @require(
        All(in_group('Administrador'),
            has_permission('crear proyecto'),
            msg='Debe poseer Rol "Administrador" para crear nuevos proyectos'))
    def add_proyecto(self, descripcion, lider, **named):
        """Registra un proyecto nuevo """
        new = Proyecto(
            descripcion=descripcion,
            id_lider=lider,
            estado=1,
        )
        DBSession.add(new)
        flash('''Proyecto Registrado: %s''' % (descripcion, ))
        redirect('./index')

    @expose(template="gestionitem.templates.proyectoTmpl.editar")
    @require(
        All(in_group('Administrador'),
            has_permission('editar proyecto'),
            msg='Debe poseer Rol "Administrador" editar proyectos'))
    def editar(self, id):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()

        if proyecto.lider != None:
            usuarios = DBSession.query(User).join((Rol, User.groups)).filter(
                Rol.group_name == 'LiderProyecto').filter(
                    User.user_id != proyecto.lider.user_id).all()
        else:
            usuarios = DBSession.query(User).join(
                (Rol, User.groups)).filter(Rol.group_name == 'LiderProyecto')

        return dict(page='Editar Proyecto',
                    id=id,
                    proyecto=proyecto,
                    subtitulo='ABM-Proyecto',
                    user=user,
                    usuarios=usuarios)

    @expose()
    @require(
        All(in_group('Administrador'),
            has_permission('editar proyecto'),
            msg='Debe poseer Rol "Administrador" editar proyectos'))
    def actualizar(self, id, descripcion, id_user, submit):
        """Create a new movie record"""
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.descripcion = descripcion
        proyecto.id_lider = id_user

        DBSession.flush()

        redirect('/proyecto')

    @expose()
    @require(
        in_group('Administrador',
                 msg='Debe poseer Rol "Administrador" eliminar proyectos'))
    @require(
        All(in_group('Administrador'),
            has_permission('eliminar proyecto'),
            msg='Debe poseer Rol "Administrador" eliminar proyectos'))
    def eliminar(self, id):
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.estado = 4

        redirect('/proyecto')

    @expose(template='gestionitem.templates.proyectoTmpl.avisoEliminarProyecto'
            )
    def avisoEliminarProyecto(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()

        return dict(page='Aviso Editar Item',
                    user=user,
                    fases=proyecto.fases,
                    proyecto=proyecto,
                    subtitulo='Aviso')

    @expose()
    def cambiarEstado(self, id, estado, **named):
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.estado = estado
        DBSession.flush()
        redirect('/proyecto')

    @expose(template="gestionitem.templates.proyectoTmpl.proyectoDef")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('definir proyecto'),
            msg='Debe poseer Rol "LiderProyecto" para definir proyectos'))
    def proyectoDef(self, id, **named):
        fases = DBSession.query(Fase).filter(Fase.proyecto_id == id)

        proyecto_id = id

        return dict(page='Definir Proyecto',
                    proyecto_id=proyecto_id,
                    subtitulo='Definir Proyecto')

    @expose(template="gestionitem.templates.proyectoTmpl.faseList")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('definir proyecto'),
            msg='Debe poseer Rol "LiderProyecto" para definir fases'))
    def definir_fase(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        fases = []

        expresion = named.get('expresion')
        orden = named.get('submit')

        iduser = identity['user']

        proyecto = DBSession.query(Proyecto).filter(Proyecto.id == id).one()
        proyectoEstado = proyecto.estado
        for grupo in iduser.groups:
            if (grupo.group_name == 'LiderProyecto'):
                if (orden == None or orden == 'Listar Todos'
                        or orden == 'Cancelar'):
                    fases = DBSession.query(Fase).filter(
                        Fase.proyecto_id == id).order_by(
                            Fase.numero_fase).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    fasesxdescripcion = DBSession.query(Fase).filter(
                        Fase.proyecto_id == id).filter(
                            Fase.descripcion.like('%' + expresion +
                                                  '%')).all()
                    fasesxestado = DBSession.query(Fase).join(
                        (EstadoFase, Fase.estadoObj)).filter(
                            Fase.proyecto_id == id).filter(
                                EstadoFase.descripcion.like('%' + expresion +
                                                            '%')).all()
                    fases = fasesxdescripcion + fasesxestado
                    muestraBoton = "true"

            elif (grupo.group_name == 'Desarrollador'
                  or grupo.group_name == 'Aprobador'):
                ufrs = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.user_id == iduser.user_id).all()
                for ufr in ufrs:
                    if (str(ufr.fase.proyecto_id) == id):
                        fasetot = []
                        if (orden == None or orden == 'Listar Todos'
                                or orden == 'Cancelar'):
                            fase1 = DBSession.query(Fase).filter(
                                Fase.id == ufr.fase_id).one()
                            muestraBoton = "false"
                        elif (orden == 'Buscar' and expresion != None):
                            fase1xdescripcion = DBSession.query(Fase).filter(
                                Fase.id == ufr.fase_id).filter(
                                    Fase.descripcion.like('%' + expresion +
                                                          '%')).all()
                            fase1xestado = DBSession.query(Fase).join(
                                (EstadoFase, Fase.estadoObj
                                 )).filter(Fase.id == ufr.fase_id).filter(
                                     EstadoFase.descripcion.like('%' +
                                                                 expresion +
                                                                 '%')).all()
                            fasetot = fase1xdescripcion + fase1xestado
                            muestraBoton = "true"
                        for fase1 in fasetot:
                            if (fase1 in fases):
                                pass
                            else:
                                fases.append(fase1)

        faseset = set(fases)
        fases = list(faseset)
        fases = sorted(fases, key=lambda Fase: Fase.numero_fase)
        proyecto_id = id

        from webhelpers import paginate
        count = fases.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            fases,
            page,
            item_count=count,
            items_per_page=5,
        )
        fases = currentPage.items
        return dict(page='Lista de fases',
                    fases=fases,
                    proyecto_id=proyecto_id,
                    subtitulo='fases',
                    user=iduser,
                    proyectoEstado=proyectoEstado,
                    muestraBoton=muestraBoton,
                    proyecto=proyecto,
                    currentPage=currentPage)

    @expose(template="gestionitem.templates.proyectoTmpl.agregar_fase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('crear fase'),
            msg='Debe poseer Rol "LiderProyecto" para agregar fases'))
    def agregar_fase(self, id):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        proyecto = DBSession.query(Proyecto).filter(Proyecto.id == id).one()
        fase = DBSession.query(Fase).filter(
            Fase.proyecto_id == proyecto.id).all()
        codigos = []
        for i, cod in enumerate(fase):
            codigos.append(cod.codigo_fase)
            codigos.append(",")
        return dict(page='Nueva Fase',
                    proyecto=proyecto,
                    user=user,
                    codigos=codigos)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('crear fase'),
            msg='Debe poseer Rol "LiderProyecto" para agregar fases'))
    def save_fase(self, id, descripcion_proyecto, nombre_fase, codFase,
                  submit):
        fases = DBSession.query(Fase).filter(Fase.proyecto_id == id)
        num = fases.count() + 1

        new = Fase(descripcion=nombre_fase,
                   proyecto_id=id,
                   numero_fase=num,
                   estado_id=3,
                   codigo_fase=codFase)
        DBSession.add(new)
        flash('''Fase Registrada: %s''' % (nombre_fase, ))
        redirect('/proyecto/definir_fase/' + id)

    @expose("gestionitem.templates.proyectoTmpl.editar_fase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar fase'),
            msg='Debe poseer Rol "LiderProyecto" para editar fases'))
    def editar_fase(self, id):

        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        fases = DBSession.query(Fase).filter(
            Fase.proyecto_id == fase.proyecto_id).all()
        codigos = []
        for i, cod in enumerate(fases):
            codigos.append(cod.codigo_fase)
            codigos.append(",")

        return dict(page='Editar fase',
                    id=id,
                    fase=fase,
                    user=user,
                    codigos=codigos,
                    subtitulo='ABM-Fase')

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar fase'),
            msg='Debe poseer Rol "LiderProyecto" para editar fases'))
    def actualizar_fase(self, id, descripcion_proyecto, nombre_fase,
                        numero_fase, submit):
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        fase.descripcion = nombre_fase
        fase.numero_fase = numero_fase
        #        fase.codigo_fase = codFase
        DBSession.flush()
        redirect('/proyecto/definir_fase/' + str(fase.proyecto_id))

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('eliminar fase'),
            msg='Debe poseer Rol "LiderProyecto" para eliminar fases'))
    def eliminar_fase(self, id):
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        id_proyecto = fase.proyecto_id
        ufrs = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == id).all()
        for ufr in ufrs:
            DBSession.delete(ufr)
        DBSession.flush()
        #        itemusuarios = DBSession.query(TipoItemUsuario).filter(TipoItemUsuario.fase_id == id).all()

        DBSession.delete(fase)
        fases = DBSession.query(Fase).filter(
            Fase.proyecto_id == id_proyecto).order_by(Fase.id).all()
        for i, fase in enumerate(fases):
            fase.numero_fase = i + 1
            DBSession.flush()

        redirect('/proyecto/definir_fase/' + str(id_proyecto))

    @expose("gestionitem.templates.proyectoTmpl.usuario_faseList")
    @require(
        in_group('LiderProyecto',
                 msg='Debe poseer Rol "LiderProyecto" para listar usuarios'))
    def usuario_faseList(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        expresion = named.get('expresion')
        orden = named.get('submit')

        usuarioFaseRols = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == id).all()

        for ufr in usuarioFaseRols:
            if ufr.usuario == None:
                DBSession.delete(ufr)
                DBSession.flush()
        if (orden == None or orden == 'Listar Todos' or orden == 'Cancelar'):
            usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                UsuarioFaseRol.fase_id == id).all()
            muestraBoton = "false"
        elif (orden == 'Buscar' and expresion != None):
            usuarioxnombre = DBSession.query(UsuarioFaseRol).join(
                (User, UsuarioFaseRol.usuario)).filter(
                    UsuarioFaseRol.fase_id == id).filter(
                        User.user_name.like('%' + expresion + '%')).order_by(
                            User.user_name).all()
            usuarioxrol = DBSession.query(UsuarioFaseRol).join(
                (Rol, UsuarioFaseRol.rol)).filter(
                    UsuarioFaseRol.fase_id == id).filter(
                        Rol.group_name.like('%' + expresion + '%')).all()
            usuarioFaseRol1 = usuarioxnombre + usuarioxrol
            usuarioFaseRol = set(usuarioFaseRol1)
            usuarioFaseRol = list(usuarioFaseRol)
            muestraBoton = "true"
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        from webhelpers import paginate
        count = usuarioFaseRol.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            usuarioFaseRol,
            page,
            item_count=count,
            items_per_page=5,
        )
        usuarioFaseRol = currentPage.items
        descripcion = fase.descripcion
        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == fase.proyecto_id).one()

        return dict(page='Usuarios de fase ' + descripcion,
                    usuariofaserol=usuarioFaseRol,
                    descripcion=descripcion,
                    fase_id=id,
                    subtitulo='Usuarios de fase',
                    proyecto_id=fase.proyecto_id,
                    user=user,
                    muestraBoton=muestraBoton,
                    proyecto=proyecto,
                    currentPage=currentPage)

    @expose("gestionitem.templates.proyectoTmpl.agregarUsuarioFase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('asignar desarrollador'),
            msg='LiderProyecto" para agregar usuarios'))
    def agregar_usuario_fase(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        usuarios = DBSession.query(User).join((Rol, User.groups)).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        roles = DBSession.query(Rol).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        #        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(UsuarioFaseRol.fase_id == id).all()

        return dict(page='Asignar Usuario a fase ' + fase.descripcion,
                    usuarios=usuarios,
                    roles=roles,
                    proyecto_id=id,
                    user=user,
                    fase=fase)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('asignar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para agregar usuarios'))
    def save_usuario_fase(self, fase, user, rol, **named):
        try:
            rol = int(rol)
            try:
                usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.fase_id == fase).filter(
                        UsuarioFaseRol.user_id == user).filter(
                            UsuarioFaseRol.rol_id == rol).one()
                DBSession.delete(usuarioFaseRol)
            except:
                pass
            new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol)

            DBSession.add(new)

        except:

            for rol1 in rol:
                try:
                    usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                        UsuarioFaseRol.fase_id == fase).filter(
                            UsuarioFaseRol.user_id == user).filter(
                                UsuarioFaseRol.rol_id == rol1).one()
                    DBSession.delete(usuarioFaseRol)
                except:
                    pass
                new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol1)

                DBSession.add(new)

        CambiarEstadoFase = DBSession.query(Fase).filter(Fase.id == fase).one()
        CambiarEstadoFase.estado_id = 1
        redirect('/proyecto/usuario_faseList/' + fase)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('eliminar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para eliminar usuarios'))
    def eliminar_usuario_fase(self, ufr):
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        fase = usuarioFaseRol.fase_id
        DBSession.delete(usuarioFaseRol)
        usuarioFaseRolcantidad = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == fase).all()
        if usuarioFaseRolcantidad.__len__() == 0:
            faseCambiarEstado = DBSession.query(Fase).filter(
                Fase.id == fase).one()
            faseCambiarEstado.estado_id = 3
            DBSession.flush()

        redirect('/proyecto/usuario_faseList/' + str(fase))

    @expose("gestionitem.templates.proyectoTmpl.editarUsuarioFase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para editar usuarios'))
    def editar_usuario_fase(self, ufr, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        fase = DBSession.query(Fase).filter(
            Fase.id == usuarioFaseRol.fase_id).one()
        usuario = DBSession.query(User).filter(
            User.user_id == usuarioFaseRol.user_id).one()
        rol = DBSession.query(Rol).filter(
            Rol.group_id == usuarioFaseRol.rol_id).one()
        roles = DBSession.query(Rol).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        return dict(page='Editar Usuario de fase' + fase.descripcion,
                    fase=fase,
                    usuario=usuario,
                    roles=roles,
                    rol=rol,
                    user=user,
                    ufr=usuarioFaseRol)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para editar usuarios'))
    def actualizar_usuario_fase(self, fase, ufr, submit, **named):
        rol = named.get('rol')
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        user = usuarioFaseRol.user_id

        if rol == None:
            usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                UsuarioFaseRol.id == ufr).one()
            DBSession.delete(usuarioFaseRol)

        else:

            try:
                rol = int(rol)
                try:
                    usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                        UsuarioFaseRol.fase_id == fase).filter(
                            UsuarioFaseRol.user_id == user).filter(
                                UsuarioFaseRol.rol_id == rol).one()
                    DBSession.delete(usuarioFaseRol)
                except:
                    pass
                new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol)

                DBSession.add(new)

            except:

                for rol1 in rol:
                    try:
                        usuarioFaseRol = DBSession.query(
                            UsuarioFaseRol).filter(
                                UsuarioFaseRol.fase_id == fase).filter(
                                    UsuarioFaseRol.user_id == user).filter(
                                        UsuarioFaseRol.rol_id == rol1).one()
                        DBSession.delete(usuarioFaseRol)
                    except:
                        pass
                    new = UsuarioFaseRol(user_id=user,
                                         fase_id=fase,
                                         rol_id=rol1)

                    DBSession.add(new)
        redirect('/proyecto/usuario_faseList/' + fase)
Esempio n. 5
0
class LineaBaseController(BaseController):
    @expose(template="gestionitem.templates.lineaBase.generar_linea_base")
    @require(
        All(
            in_group(
                'LiderProyecto',
                msg='Debe poseer Rol "LiderProyecto" para generar lineas bases'
            ),
            has_permission(
                'Gestionar linea base',
                msg=
                'Debe poseer Permiso "Generar linea base" para agregar fases'))
    )
    def generar_linea_base(self, idfase, **named):
        """ Se utiliza para generar la linea base de un fase indicada en el parametro.
   
        @param idfase: identificador de la fase.
        @type idfase: Integer
       
        @return: diccionario de todos los elementos que se obtienen con las consultas para mostrar en la pagina.
        @rtype: Diccionario.
        """
        expresion = ""

        itemSeleccionado = DBSession.query(ItemUsuario).filter_by(id=-1)
        itemselect = named.get('itemselect', '0')

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()

        if (itemselect != 0):
            try:
                itemselect = int(itemselect)
                itemselect = [itemselect]
                itemSeleccionado = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.id.in_(itemselect)).order_by(ItemUsuario.id)
            except:
                itemSeleccionado = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.id.in_(itemselect)).order_by(ItemUsuario.id)

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.estado_id == 8).filter(
                    ItemUsuario.fase_id == idfase).filter(
                        or_(
                            ItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                            (ItemUsuario.cod_item.like('%' + str(expre_cad) +
                                                       '%')))).order_by(
                                                           ItemUsuario.id)
        else:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.fase_id == idfase).filter(
                    ItemUsuario.estado_id == 8).all()

        return dict(items=items,
                    fase=fase,
                    filtro=expresion,
                    itemSeleccionado=itemSeleccionado)

    print generar_linea_base.__doc__

    @expose()
    def guardar_linea_base(self, faseid, **named):

        itemselect = named.get('itemselect')

        try:
            itemselect = int(itemselect)
            itemselect = [itemselect]
            itemseleccionados = DBSession.query(ItemUsuario).filter(
                ItemUsuario.id.in_(itemselect)).all()

            listaIds = DBSession.query(LineaBase).order_by(LineaBase.id)
            if (listaIds.count() > 0):
                list = listaIds[-1]
                id = list.id + 1
            else:
                id = 1

            lb = LineaBase(id=int(id),
                           version=1,
                           estado_id=1,
                           fase_id=int(faseid))
            DBSession.add(lb)
            DBSession.flush()

            for item in itemseleccionados:
                lbAnterior = item.linea_base_ant
                itemsEnLbAnterior = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_ant == lbAnterior).all()
                for itemLbAnt in itemsEnLbAnterior:
                    if itemLbAnt.estado_id == 5:
                        itemLbAnt.estado_id = 3
                        itemLbAnt.linea_base_id = id
                        itemLbAnt.linea_base_ant = id
                item.estado_id = 3
                item.linea_base_id = id
                item.linea_base_ant = id
                DBSession.flush()
        except:
            itemseleccionados = DBSession.query(ItemUsuario).filter(
                ItemUsuario.id.in_(itemselect)).all()
            listaIds = DBSession.query(LineaBase).order_by(LineaBase.id)
            if (listaIds.count() > 0):
                list = listaIds[-1]
                id = list.id + 1
            else:
                id = 1

            lb = LineaBase(id=int(id),
                           version=1,
                           estado_id=1,
                           fase_id=int(faseid))
            DBSession.add(lb)
            DBSession.flush()

            for item in itemseleccionados:
                lbAnterior = item.linea_base_ant
                itemsEnLbAnterior = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_ant == lbAnterior).all()
                for itemLbAnt in itemsEnLbAnterior:
                    if itemLbAnt.estado_id == 5:
                        itemLbAnt.estado_id = 3
                        itemLbAnt.linea_base_id = id
                        itemLbAnt.linea_base_ant = id
                item.estado_id = 3
                item.linea_base_id = id
                item.linea_base_ant = id
                DBSession.flush()

        estados = [1, 2, 3, 4, 5, 8]
        itemsEnLB = DBSession.query(ItemUsuario).filter(
            ItemUsuario.fase_id == faseid).filter(
                ItemUsuario.estado_id.in_(estados)).order_by(
                    ItemUsuario.id).all()
        faseConLB = 0
        for itemP in itemsEnLB:
            if itemP.estado_id != 3:
                faseConLB = 1
        if faseConLB == 0:
            fase = DBSession.query(Fase).filter_by(id=faseid).one()
            fase.estado_id = 4
            DBSession.flush()

        redirect('/item/itemList/' + faseid)

    @expose(template="gestionitem.templates.lineaBase.lista_linea_base")
    def listar_linea_base(self, idproyecto, idfase, **named):

        expresion = ""

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtro')

            if expresion.isdigit():
                lista = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 1).filter(
                        LineaBase.fase_id == idfase).filter(
                            LineaBase.id == int(expresion)).all()
            else:
                lista = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 1).filter(
                        LineaBase.fase_id == idfase).all()
        else:
            lista = DBSession.query(LineaBase).filter(
                LineaBase.estado_id == 1).filter(
                    LineaBase.fase_id == idfase).all()

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()
        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == idproyecto).one()

        from webhelpers import paginate
        #count = items.count()
        count = lista.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            lista,
            page,
            item_count=count,
            items_per_page=2,
        )

        lista = currentPage.items

        return dict(lista=lista,
                    fase=fase,
                    proyecto=proyecto,
                    filtro=expresion,
                    currentPage=currentPage,
                    page=page)

    @expose(template="gestionitem.templates.lineaBase.lista_items_x_linea_base"
            )
    def items_linea_base(self, lb_id, idfase, **named):

        expresion = ""

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtro')
            expre_cad = expresion
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.estado_id == 3).filter(
                    ItemUsuario.linea_base_id == lb_id).filter(
                        or_(
                            ItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                            (ItemUsuario.cod_item.like('%' + str(expre_cad) +
                                                       '%')))).all()
        else:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.linea_base_id == lb_id).all()

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()
        lineabase = DBSession.query(LineaBase).filter(
            LineaBase.id == lb_id).one()

        from webhelpers import paginate
        #count = items.count()
        count = items.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            items,
            page,
            item_count=count,
            items_per_page=2,
        )
        items = currentPage.items

        return dict(items=items,
                    fase=fase,
                    filtro=expresion,
                    lineabase=lineabase,
                    page=page,
                    currentPage=currentPage)

    @expose(
        template="gestionitem.templates.lineaBase.cerrar_linea_base_abierta")
    def cerrar_linea_base_abierta(self, idFase, **named):

        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        #CONSULTA ALA BD
        lbSolicitadas = DBSession.query(LineaBase).filter(
            LineaBase.estado_id == 2).filter(
                LineaBase.fase_id == idFase).all()
        itemsLBSol = []
        for idLB in lbSolicitadas:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.linea_base_id == idLB.id).filter(
                    ItemUsuario.estado_id == 5).all()
            codigosItemsSol = ""
            for item in items:
                codigosItemsSol = codigosItemsSol + "|" + item.cod_item + " "
            itemsLBSol.append(codigosItemsSol)

        fase = DBSession.query(Fase).filter_by(id=idFase).one()
        # SI EXISTE FILTROS DE BUSQUEDAS
        itemSelec = named.get('itemselect', '0')
        filtro = named.get('filtros', '')
        if (filtro != ""):
            if filtro.isdigit():
                lbSolicitadas = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 2).filter(
                        LineaBase.fase_id == idFase).filter_by(
                            id=filtro).order_by(LineaBase.id).all()
            else:
                lbSolicitadas = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 2).filter(
                        LineaBase.fase_id == idFase).filter(
                            LineaBase.descripcion.like('%' + str(filtro) +
                                                       '%')).order_by(
                                                           LineaBase.id).all()
            lbIds = []
            itemsLB = []

            for idLB in lbSolicitadas:
                lbIds.append(idLB.id)
                items = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_id == idLB.id).all()
                codigosItems = ""
                for item in items:
                    codigosItems = codigosItems + "|" + item.cod_item + " "
                itemsLB.append(codigosItems)

        proyecto = DBSession.query(Proyecto).filter_by(
            id=fase.proyecto_id).one()
        from webhelpers import paginate
        count = items.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            items,
            page,
            item_count=count,
            items_per_page=3,
        )

        muestraBoton = "false"
        return dict(page='Solicitudes de Apertura',
                    user=user,
                    itemsLBSol=itemsLBSol,
                    muestraBoton=muestraBoton,
                    lbSolicitadas=lbSolicitadas,
                    named=named,
                    filtro=filtro,
                    itemSelec=itemSelec,
                    items=items,
                    fase=fase,
                    proyecto=proyecto,
                    currentPage=currentPage,
                    subtitulo='Solicitudes de Apertura')

    @expose()
    def accionSolicitud(self, idFase, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        lbs = DBSession.query(LineaBase).filter_by(fase_id=idFase).filter_by(
            estado_id=2).all()
        for lb in lbs:
            accion = named.get(str(lb.id), '')
            if (accion != "") and (accion == "Cerrar"):
                lb.estado_id = 1
                DBSession.flush()
                ###Cambia Estado del Item
                items = DBSession.query(ItemUsuario).filter_by(
                    linea_base_id=lb.id).all()
                for item in items:
                    if (item.estado_id == 5):
                        item.estado_id = 3
                        DBSession.flush
                estados = [1, 2, 3, 4, 5, 8]
                itemsEnLB = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.fase_id == idFase).filter(
                        ItemUsuario.estado_id.in_(estados)).order_by(
                            ItemUsuario.id).all()
                faseConLB = 0
                for itemP in itemsEnLB:
                    if itemP.estado_id != 3:
                        faseConLB = 1
                if faseConLB == 0:
                    fase = DBSession.query(Fase).filter_by(id=idFase).one()
                    fase.estado_id = 4
                    DBSession.flush()
        fase = DBSession.query(Fase).filter_by(id=idFase).one()

        redirect('/item/itemList/' + str(fase.id))

    @expose(
        template="gestionitem.templates.proyectoTmpl.listar_proyectos_definidos"
    )
    def listar_proyectos_definidos(self, idfaseDestino, **named):

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            proyectos = DBSession.query(Proyecto).filter(
                or_(Proyecto.estado == 2, Proyecto.estado == 3)).filter(
                    Proyecto.descripcion.like('%' + str(expre_cad) +
                                              '%')).all()
        else:
            proyectos = DBSession.query(Proyecto).filter(
                or_(Proyecto.estado == 2, Proyecto.estado == 3)).all()

        return dict(proyecto=proyectos,
                    filtro='',
                    proy='1',
                    idfaseDestino=idfaseDestino)

    @expose(
        template="gestionitem.templates.proyectoTmpl.listar_fases_definidas")
    def listar_fases_definidas(self, idfaseDestino, idproyecto, **named):
        expre_cad = ""
        proyecto = DBSession.query(Proyecto).filter_by(id=idproyecto).one()

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            fases = DBSession.query(Fase).filter(
                Fase.proyecto_id == idproyecto).filter(
                    Fase.descripcion.like('%' + str(expre_cad) + '%')).all()
        else:
            fases = DBSession.query(Fase).filter(
                Fase.proyecto_id == idproyecto).all()
        return dict(proyecto=proyecto,
                    fases=fases,
                    filtro=expre_cad,
                    idfaseDestino=idfaseDestino)

    @expose(
        template="gestionitem.templates.proyectoTmpl.importar_tipoItems_proyecto"
    )
    def importar_tipoItems_proyecto(self, idfaseDestino, idfase, **named):

        #proyecto= DBSession.query(Proyecto).filter(Proyecto.id == idproyecto).one()
        itemSeleccionado = DBSession.query(TipoItemUsuario).filter_by(id=-1)

        itemselect = named.get('itemselect', '0')

        if (itemselect != 0):

            try:
                itemselect = int(itemselect)
                itemselect = [itemselect]
                itemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.id.in_(itemselect)).order_by(
                        TipoItemUsuario.id)

            except:
                itemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.id.in_(itemselect)).order_by(
                        TipoItemUsuario.id)

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()

        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == fase.proyecto_id).one()

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            itemUsuarios = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.fase_id == idfase).filter(
                    or_(
                        TipoItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                        (TipoItemUsuario.codigo.like('%' + str(expre_cad) +
                                                     '%')))).all()
        else:
            itemUsuarios = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.fase_id == idfase).all()

        return dict(listaItemUser=itemUsuarios,
                    proyecto=proyecto,
                    itemSeleccionado=itemSeleccionado,
                    filtro="",
                    fase=fase,
                    idfaseDestino=idfaseDestino)

    @expose()
    def guardar_items_importados(self, idfaseDestino, **named):

        itemselect = named.get('itemselect')

        try:
            itemselect = int(itemselect)
            itemselect = [itemselect]
            tipoItemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.id.in_(itemselect)).all()

            tipoItemExiste = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.codigo == tipoItemSeleccionado.codigo).filter(
                    TipoItemUsuario.fase_id == idfaseDestino).all()

            if tipoItemExiste.__len__() == 0:
                listaIds = DBSession.query(TipoItemUsuario).order_by(
                    TipoItemUsuario.id)
                if (listaIds.count() > 0):
                    list = listaIds[-1]
                    id = list.id + 1
                else:
                    id = 1

                ti = TipoItemUsuario(
                    id=int(id),
                    descripcion=tipoItemSeleccionado.descripcion,
                    codigo=tipoItemSeleccionado.codigo,
                    fase_id=idfaseDestino)  #el parametro pasado aca debe ir.
                DBSession.add(ti)
                DBSession.flush()

                for atributo in tipoItemSeleccionado.atributos:

                    at = TipoItemUsuarioAtributos(
                        nombre_atributo=atributo.nombre_atributo,
                        tipo_item_id=int(id),
                        tipo_id=atributo.tipo_id)

                    DBSession.add(at)
                    DBSession.flush()

        except:

            itemseleccionados = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.id.in_(itemselect)).all()

            for tipoItemSelect in itemseleccionados:

                tipoItemExiste = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.codigo == tipoItemSelect.codigo).filter(
                        TipoItemUsuario.fase_id == idfaseDestino).all()

                if tipoItemExiste.__len__() == 0:

                    listaIds = DBSession.query(TipoItemUsuario).order_by(
                        TipoItemUsuario.id)
                    if (listaIds.count() > 0):
                        list = listaIds[-1]
                        id = list.id + 1
                    else:
                        id = 1

                    ti = TipoItemUsuario(
                        id=int(id),
                        descripcion=tipoItemSelect.descripcion,
                        codigo=tipoItemSelect.codigo,
                        fase_id=idfaseDestino
                    )  #el parametro pasado aca debe ir.
                    DBSession.add(ti)
                    DBSession.flush()

                    for atributo in tipoItemSelect.atributos:

                        at = TipoItemUsuarioAtributos(
                            nombre_atributo=atributo.nombre_atributo,
                            tipo_item_id=int(id),
                            tipo_id=atributo.tipo_id)

                        DBSession.add(at)
                        DBSession.flush()

        redirect("/tipoItems/tipoItemUsuario/" + idfaseDestino + "/lista")
Esempio n. 6
0
from baruwa.model.meta import Session
from baruwa.lib.audit import audit_log
from baruwa.lib.auth.predicates import OnlySuperUsers
from baruwa.tasks.settings import update_serial
from baruwa.model.accounts import Group, User, Relay
from baruwa.model.domains import Domain
from baruwa.forms.organizations import OrgForm, RelayForm, RelayEditForm
from baruwa.forms.organizations import DelOrgForm
from baruwa.forms.organizations import ImportCSVForm
from baruwa.tasks import importdomains
from baruwa.lib.audit.msgs.organizations import *

log = logging.getLogger(__name__)


@ControllerProtector(All(not_anonymous(), OnlySuperUsers()))
class OrganizationsController(BaseController):
    def __before__(self):
        "set context"
        BaseController.__before__(self)
        if self.identity:
            c.user = self.identity['user']
        else:
            c.user = None
        c.selectedtab = 'organizations'

    def _get_org(self, orgid):
        "Get organization"
        try:
            org = Session.query(Group).options(
                joinedload('domains')).get(orgid)
Esempio n. 7
0
from baruwa.lib.templates.helpers import media_url
from baruwa.lib.query import DailyTotals, MailQueue
from baruwa.lib.query import clean_sphinx_q, restore_sphinx_q
from baruwa.tasks.status import export_auditlog
from baruwa.tasks.status import preview_queued_msg, process_queued_msgs
from baruwa.tasks.status import systemstatus, salint, bayesinfo
from baruwa.lib.auth.predicates import OnlySuperUsers, OnlyAdminUsers
from baruwa.forms.status import MailQueueProcessForm
from baruwa.lib.audit.msgs.status import QUEUEPREVIEW_MSG, QUEUEDOWNLOAD_MSG
from baruwa.lib.audit.msgs.status import HOSTSTATUS_MSG, HOSTSALINT_MSG
from baruwa.lib.audit.msgs.status import HOSTBAYES_MSG, AUDITLOGEXPORT_MSG

log = logging.getLogger(__name__)


@ControllerProtector(All(not_anonymous()))
class StatusController(BaseController):
    def __before__(self):
        "set context"
        BaseController.__before__(self)
        if self.identity:
            c.user = self.identity['user']
        else:
            c.user = None
        c.selectedtab = 'status'

    def _get_server(self, serverid):
        "utility"
        try:
            server = Session.query(Server).get(serverid)
        except NoResultFound:
Esempio n. 8
0
class AccountsController(BaseController):
    "Accounts controller"

    def __before__(self):
        "set context"
        BaseController.__before__(self)
        if self.identity:
            c.user = self.identity['user']
        else:
            c.user = None
        c.selectedtab = 'accounts'

    def _get_address(self, addressid):
        "return address"
        try:
            address = Session.query(Address).get(addressid)
        except NoResultFound:
            address = None
        return address

    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > now():
                abort(409,
                      _('You have been banned after'
                        ' several failed logins'))
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = now() + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if now() > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            return render('/accounts/login.html')

    def loggedin(self):
        "Landing page"
        came_from = (unquote(str(request.params.get('came_from', '')))
                     or url('/'))
        if not self.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(
                url('/accounts/login',
                    came_from=came_from,
                    __logins=login_counter))
        userid = self.identity['repoze.who.userid']
        user = self.identity['user']
        if user is None:
            try:
                user = User(username=userid, email=userid)
                user.active = True
                local_part, domain = userid.split('@')
                domains = Session.query(Domain)\
                        .filter(Domain.name == domain)\
                        .all()
                user.domains = domains
                user.timezone = domains[0].timezone
                Session.add(user)
                Session.commit()
                msg = _('First time Login from external auth,'
                        ' your local account was created')
                addresses = []
                if ('tokens' in self.identity
                        and 'ldap' in self.identity['tokens']):
                    lsettings = Session.query(AuthServer.address,
                                    AuthServer.port, LDAPSettings.binddn,
                                    LDAPSettings.bindpw,
                                    LDAPSettings.usetls)\
                                    .join(Domain)\
                                    .filter(AuthServer.enabled == True)\
                                    .filter(Domain.name == domain)\
                                    .all()
                    lsettings = lsettings[0]
                    lurl = make_ldap_uri(lsettings.address, lsettings.port)
                    base_dn = get_user_dn(self.identity['tokens'][1])
                    attributes = [
                        'sn', 'givenName', 'proxyAddresses', 'mail', 'memberOf'
                    ]
                    ldapattributes = LDAPAttributes(lurl,
                                                    base_dn,
                                                    attributes=attributes,
                                                    bind_dn=lsettings.binddn,
                                                    bind_pass=lsettings.bindpw,
                                                    start_tls=lsettings.usetls)
                    ldapattributes()
                    attrmap = {
                        'sn': 'lastname',
                        'givenName': 'firstname',
                        'mail': 'email',
                    }

                    update_attrs = False

                    doms = [domains[0].name]
                    doms.extend([alias.name for alias in domains[0].aliases])

                    for attr in attrmap:
                        if (attr == 'mail' and attr in ldapattributes
                                and ldapattributes[attr][0] == user.email):
                            # Dont update if user.email = directory.email
                            continue
                        if (attr == 'mail' and attr in ldapattributes
                                and '@' in ldapattributes[attr][0]):
                            # Update if email is hosted by us
                            if ldapattributes[attr][0].split('@')[1] in doms:
                                setattr(user, attrmap[attr],
                                        ldapattributes[attr][0])
                                update_attrs = True
                            continue
                        if attr in ldapattributes:
                            setattr(user, attrmap[attr],
                                    ldapattributes[attr][0])
                            update_attrs = True

                    if update_attrs:
                        Session.add(user)
                        Session.commit()

                    # accounts aliases
                    if 'proxyAddresses' in ldapattributes:
                        for mailaddr in ldapattributes['proxyAddresses']:
                            try:
                                if mailaddr.startswith('SMTP:'):
                                    continue
                                if (mailaddr.startswith('smtp:') and
                                        mailaddr.strip('smtp:').lsplit('@')[1]
                                        in doms):
                                    # Only add domain if we host it
                                    address = Address(
                                        PROXY_ADDR_RE.sub('', mailaddr))
                                    address.user = user
                                    addresses.append(address)
                            except IndexError:
                                pass
                    # accounts groups
                    if 'memberOf' in ldapattributes:
                        for group_dn in ldapattributes['memberOf']:
                            groupattributes = LDAPAttributes(
                                lurl,
                                group_dn,
                                attributes=['proxyAddresses'],
                                bind_dn=lsettings.binddn,
                                bind_pass=lsettings.bindpw,
                                start_tls=lsettings.usetls)
                            groupattributes()
                            for mailaddr in groupattributes['proxyAddresses']:
                                try:
                                    mailaddr = mailaddr.lower()
                                    if (mailaddr.startswith('smtp:')
                                            and mailaddr.lstrip('smtp:').split(
                                                '@')[1] in doms):
                                        address = Address(
                                            PROXY_ADDR_RE.sub('', mailaddr))
                                        address.user = user
                                        addresses.append(address)
                                except IndexError:
                                    pass
                else:
                    for alias in domains[0].aliases:
                        address = Address('%s@%s' % (local_part, alias.name))
                        address.user = user
                        addresses.append(address)
                for unsaved in addresses:
                    try:
                        Session.add(unsaved)
                        Session.commit()
                    except IntegrityError:
                        Session.rollback()
            except IntegrityError:
                Session.rollback()
                redirect(url('/logout'))
        else:
            msg = _('Login successful, Welcome back %(username)s !' %
                    dict(username=userid))
        user.last_login = now()
        Session.add(user)
        Session.commit()
        if user.is_peleb:
            for domain in user.domains:
                if check_language(domain.language):
                    session['lang'] = domain.language
                    session.save()
                    break
        session['taskids'] = []
        session.save()
        info = ACCOUNTLOGIN_MSG % dict(u=user.username)
        audit_log(user.username, 6, info, request.host, request.remote_addr,
                  now())
        flash(msg)
        redirect(url(came_from))

    def loggedout(self):
        "Logged out page"
        # response.delete_cookie('baruwacsrf')
        if 'lang' in session:
            lang = session['lang']
        session.clear()
        if 'lang' in locals():
            session['lang'] = lang
        session.save()
        #flash(_('You have been logged out !'))
        came_from = (unquote(str(request.params.get('came_from', '')))
                     or url('/accounts/login/'))
        redirect(url(came_from))

    def passwdreset(self):
        """Render password reset page"""
        c.came_from = '/'
        c.login_counter = 0
        return render('/accounts/login.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def pwchange(self, userid):
        """Reset a user password"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        c.form = ChangePasswordForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            if user.local:
                user.set_password(c.form.password1.data)
                Session.add(user)
                Session.commit()
                flash(
                    _('The account password for %(name)s has been reset') %
                    dict(name=user.username))
                info = PASSWORDCHANGE_MSG % dict(u=user.username)
                audit_log(c.user.username, 2, info, request.host,
                          request.remote_addr, now())
            else:
                flash(
                    _('This is an external account, use'
                      ' external system to reset the password'))
            redirect(url('account-detail', userid=user.id))
        c.id = userid
        c.username = user.username
        c.posturl = 'accounts-pw-change'
        return render('/accounts/pwchange.html')

    @ActionProtector(not_anonymous())
    def upwchange(self, userid):
        """User change own password"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        if user.id != c.user.id or c.user.is_superadmin:
            abort(403)
        c.form = UserPasswordForm(request.POST, csrf_context=session)
        if (request.POST and c.form.validate()
                and user.validate_password(c.form.password3.data)):
            if user.local:
                user.set_password(c.form.password1.data)
                Session.add(user)
                Session.commit()
                flash(
                    _('The account password for %(name)s has been reset') %
                    dict(name=user.username))
                info = PASSWORDCHANGE_MSG % dict(u=user.username)
                audit_log(c.user.username, 2, info, request.host,
                          request.remote_addr, now())
            else:
                flash(
                    _('This is an external account, use'
                      ' external system to reset the password'))
            redirect(url('account-detail', userid=user.id))
        elif (request.POST
              and not user.validate_password(c.form.password3.data)
              and not c.form.password3.errors):
            flash_alert(
                _('The old password supplied does'
                  ' not match our records'))
        c.id = userid
        c.username = user.username
        c.posturl = 'accounts-pw-uchange'
        return render('/accounts/pwchange.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def index(self, page=1, orgid=None, domid=None, format=None):
        """GET /accounts/: Paginate items in the collection"""
        num_items = session.get('accounts_num_items', 10)
        c.form = BulkDelUsers(request.POST, csrf_context=session)
        if request.POST:
            if str(c.user.id) in c.form.accountid.data:
                c.form.accountid.data.remove(str(c.user.id))
            if c.form.accountid.data and c.form.whatdo.data == 'disable':
                Session.query(User)\
                .filter(User.id.in_(c.form.accountid.data))\
                .update({'active':False}, synchronize_session='fetch')
                Session.commit()
            if c.form.accountid.data and c.form.whatdo.data == 'enable':
                Session.query(User)\
                .filter(User.id.in_(c.form.accountid.data))\
                .update({'active':True}, synchronize_session='fetch')
                Session.commit()
            if c.form.accountid.data and c.form.whatdo.data == 'delete':
                session['bulk_account_delete'] = c.form.accountid.data
                session.save()
                # redirect for confirmation
                redirect(url('accounts-confirm-delete'))
        users = Session.query(User.id, User.username, User.firstname,
                              User.lastname, User.email, User.active,
                              User.local, User.account_type).order_by(User.id)
        usrcount = Session.query(User.id)
        if c.user.is_domain_admin:
            users = users.join(domain_users, (dom_owns,
                                domain_users.c.domain_id ==
                                dom_owns.c.domain_id),
                                (oas,
                                dom_owns.c.organization_id ==
                                oas.c.organization_id))\
                                .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                                    domain_users.c.domain_id ==
                                    dom_owns.c.domain_id),
                                    (oas,
                                    dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)
        if domid:
            users = users.filter(
                and_(domain_users.c.domain_id == domid,
                     domain_users.c.user_id == User.id))
            usrcount = usrcount.filter(
                and_(domain_users.c.domain_id == domid,
                     domain_users.c.user_id == User.id))
        if orgid:
            users = users.filter(
                and_(
                    domain_users.c.user_id == User.id,
                    domain_users.c.domain_id == dom_owns.c.domain_id,
                    dom_owns.c.organization_id == orgid,
                ))
            usrcount = usrcount.filter(
                and_(
                    domain_users.c.user_id == User.id,
                    domain_users.c.domain_id == dom_owns.c.domain_id,
                    dom_owns.c.organization_id == orgid,
                ))

        pages = paginate.Page(users,
                              page=int(page),
                              items_per_page=num_items,
                              item_count=usrcount.count())
        if format == 'json':
            response.headers['Content-Type'] = 'application/json'
            data = convert_acct_to_json(pages, orgid)
            return data

        c.page = pages
        c.domid = domid
        c.orgid = orgid
        return render('/accounts/index.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def search(self, format=None):
        "Search for accounts"
        total_found = 0
        search_time = 0
        num_items = session.get('accounts_num_items', 10)
        q = request.GET.get('q', '')
        d = request.GET.get('d', None)
        kwds = {'presliced_list': True}
        page = int(request.GET.get('p', 1))
        conn = SphinxClient()
        conn.SetMatchMode(SPH_MATCH_EXTENDED2)
        conn.SetFieldWeights(
            dict(username=50, email=30, firstname=10, lastname=10))
        if page == 1:
            conn.SetLimits(0, num_items, 500)
        else:
            page = int(page)
            offset = (page - 1) * num_items
            conn.SetLimits(offset, num_items, 500)
        if d:
            conn.SetFilter('domains', [
                int(d),
            ])
        if c.user.is_domain_admin:
            #crcs = get_dom_crcs(Session, c.user)
            domains = Session.query(Domain.id).join(dom_owns,
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)
            conn.SetFilter('domains', [domain[0] for domain in domains])
        q = clean_sphinx_q(q)
        results = conn.Query(q, 'accounts, accounts_rt')
        q = restore_sphinx_q(q)
        if results and results['matches']:
            ids = [hit['id'] for hit in results['matches']]
            total_found = results['total_found']
            search_time = results['time']
            users = Session.query(User.id,
                                    User.username,
                                    User.firstname,
                                    User.lastname,
                                    User.email,
                                    User.active,
                                    User.local,
                                    User.account_type)\
                                .filter(User.id.in_(ids))\
                                .order_by(User.id)\
                                .all()
            usercount = total_found
        else:
            users = []
            usercount = 0
        c.q = q
        c.d = d
        c.total_found = total_found
        c.search_time = search_time
        c.page = paginate.Page(users,
                               page=int(page),
                               items_per_page=num_items,
                               item_count=usercount,
                               **kwds)
        return render('/accounts/searchresults.html')

    @ActionProtector(All(not_anonymous(), CanAccessAccount()))
    def detail(self, userid):
        """GET /accounts/userid/ Show a specific item"""
        user = self._get_user(userid)
        if not user:
            abort(404)
        c.account = user
        return render('/accounts/account.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def add(self):
        """/accounts/new"""
        c.form = AddUserForm(request.POST, csrf_context=session)
        if c.user.is_domain_admin:
            account_types = (('3', 'User'), )
            c.form.account_type.choices = account_types
            c.form.domains.query = Session.query(Domain).join(dom_owns,
                                    (oas, dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)
        else:
            c.form.domains.query = Session.query(Domain)
        if request.POST and c.form.validate():
            try:
                user = User(username=c.form.username.data,
                            email=c.form.email.data)
                for attr in [
                        'firstname', 'lastname', 'email', 'active',
                        'account_type', 'send_report', 'spam_checks',
                        'low_score', 'high_score', 'timezone'
                ]:
                    setattr(user, attr, getattr(c.form, attr).data)
                user.local = True
                user.set_password(c.form.password1.data)
                if int(user.account_type) == 3:
                    user.domains = c.form.domains.data
                Session.add(user)
                Session.commit()
                update_serial.delay()
                info = ADDACCOUNT_MSG % dict(u=user.username)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(
                    _('The account: %(user)s was created successfully') %
                    {'user': c.form.username.data})
                redirect(url('account-detail', userid=user.id))
            except IntegrityError:
                Session.rollback()
                flash_alert(
                    _('Either the username or email address already exist'))
        return render('/accounts/new.html')

    @ActionProtector(All(not_anonymous(), CanAccessAccount()))
    def edit(self, userid):
        """GET /accounts/edit/id: Form to edit an existing item"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        if user.account_type != 3 or c.user.is_peleb:
            del c.form.domains
        if c.user.is_peleb:
            del c.form.username
            del c.form.email
            del c.form.active
        if request.POST and c.form.validate():
            update = False
            kwd = dict(userid=userid)
            for attr in FORM_FIELDS:
                field = getattr(c.form, attr)
                if field and field.data != getattr(user, attr):
                    setattr(user, attr, field.data)
                    update = True
            if update:
                try:
                    Session.add(user)
                    Session.commit()
                    update_serial.delay()
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                    info = UPDATEACCOUNT_MSG % dict(u=user.username)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active
                        and c.form.active.data == False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/edit.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        if request.POST and c.form.validate():
            username = user.username
            Session.delete(user)
            Session.commit()
            update_serial.delay()
            flash(_('The account has been deleted'))
            info = DELETEACCOUNT_MSG % dict(u=username)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            if userid == c.user.id:
                redirect(url('/logout'))
            redirect(url(controller='accounts', action='index'))
        else:
            flash_info(
                _('The account: %(a)s and all associated data'
                  ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/delete.html')

    @ActionProtector(not_anonymous())
    def confirm_delete(self):
        "Confirm mass delete"
        accountids = session.get('bulk_account_delete', [])
        if not accountids:
            redirect(url(controller='accounts', action='index'))

        num_items = 10
        if len(accountids) > num_items and len(accountids) <= 20:
            num_items = 20
        if len(accountids) > num_items and len(accountids) <= 50:
            num_items = 50
        if len(accountids) > num_items and len(accountids) <= 100:
            num_items = 100

        users = Session.query(User).filter(User.id.in_(accountids))
        usrcount = Session.query(User.id)

        if c.user.is_domain_admin and usrcount:
            users = users.join(domain_users, (dom_owns,
                    domain_users.c.domain_id == dom_owns.c.domain_id),
                    (oas, dom_owns.c.organization_id == oas.c.organization_id))\
                    .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                        domain_users.c.domain_id == dom_owns.c.domain_id),
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)

        if request.POST:
            tasks = []
            # try:
            for account in users.all():
                info = DELETEACCOUNT_MSG % dict(u=account.username)
                Session.delete(account)
                tasks.append([
                    c.user.username, 4, info, request.host,
                    request.remote_addr,
                    now()
                ])
            Session.commit()
            # except DataError:
            #     flash_alert(_('An error occured try again'))
            #     redirect(url(controller='accounts', action='index'))
            del session['bulk_account_delete']
            session.save()
            update_serial.delay()
            for task in tasks:
                audit_log(*task)
            flash(_('The accounts have been deleted'))
            redirect(url(controller='accounts'))
        else:
            flash(
                _('The following accounts are about to be deleted,'
                  ' this action is not reversible, Do you wish to '
                  'continue ?'))

        try:
            c.page = paginate.Page(users,
                                   page=1,
                                   items_per_page=num_items,
                                   item_count=usrcount.count())
        except DataError:
            flash_alert(_('An error occured try again'))
            redirect(url(controller='accounts', action='index'))
        return render('/accounts/confirmbulkdel.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def addaddress(self, userid):
        "Add address"
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = AddressForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                if c.user.is_domain_admin:
                    # check if they own the domain
                    domain = c.form.address.data.split('@')[1]
                    domain = Session.query(Domain).options(
                                joinedload('organizations')).join(
                                dom_owns, (oas,
                                dom_owns.c.organization_id ==
                                oas.c.organization_id))\
                                .filter(oas.c.user_id == c.user.id)\
                                .filter(Domain.name == domain).one()
                addr = Address(address=c.form.address.data)
                addr.enabled = c.form.enabled.data
                addr.user = user
                Session.add(addr)
                Session.commit()
                update_serial.delay()
                info = ADDRADD_MSG % dict(a=addr.address, ac=user.username)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(
                    _('The alias address %(address)s was successfully created.'
                      % dict(address=addr.address)))
            except IntegrityError:
                flash_alert(
                    _('The address %(addr)s already exists') %
                    dict(addr=addr.address))
            except NoResultFound:
                flash(
                    _('Domain: %(d)s does not belong to you') % dict(d=domain))
            redirect(url(controller='accounts', action='detail',
                         userid=userid))
        c.id = userid
        return render('/accounts/addaddress.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def editaddress(self, addressid):
        "Edit address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                if (address.address != c.form.address.data
                        or address.enabled != c.form.enabled.data):
                    if c.user.is_domain_admin:
                        # check if they own the domain
                        domain = c.form.address.data.split('@')[1]
                        domain = Session.query(Domain).options(
                                    joinedload('organizations')).join(
                                    dom_owns, (oas,
                                    dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)\
                                    .filter(Domain.name == domain).one()
                    address.address = c.form.address.data
                    address.enabled = c.form.enabled.data
                    Session.add(address)
                    Session.commit()
                    update_serial.delay()
                    info = ADDRUPDATE_MSG % dict(a=address.address,
                                                 ac=address.user.username)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                flash_alert(
                    _('The address %(addr)s already exists') %
                    dict(addr=c.form.address.data))
            except NoResultFound:
                flash(
                    _('Domain: %(d)s does not belong to you') % dict(d=domain))
            redirect(
                url(controller='accounts',
                    action='detail',
                    userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/editaddress.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers(),
                         CanAccessAccount()))
    def deleteaddress(self, addressid):
        "Delete address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            user_id = address.user_id
            addr = address.address
            username = address.user.username
            Session.delete(address)
            Session.commit()
            update_serial.delay()
            info = ADDRDELETE_MSG % dict(a=addr, ac=username)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The address has been deleted'))
            redirect(
                url(controller='accounts', action='detail', userid=user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/deleteaddress.html')

    def set_language(self):
        "Set the language"
        nextpage = request.params.get('next', None)
        if not nextpage:
            nextpage = request.headers.get('Referer', None)
        if not nextpage:
            nextpage = '/'
        if '://' in nextpage:
            from_url = urlparse(nextpage)
            nextpage = from_url[2]
        lang_code = request.params.get('language', None)
        if lang_code and check_language(lang_code):
            session['lang'] = lang_code
            session.save()
        params = []
        for param in request.params:
            if not param in ['language', 'amp']:
                value = request.params[param]
                if value:
                    if (param == 'came_from'
                            and '://' in urllib2.unquote(value)):
                        urlparts = urlparse(urllib2.unquote(value))
                        value = urlparts[2] or '/'
                    params.append('%s=%s' %
                                  (urllib2.quote(param), urllib2.quote(value)))
        if params:
            nextpage = "%s?%s" % (nextpage, '&amp;'.join(params))
        redirect(nextpage)

    @ActionProtector(All(not_anonymous(), OwnsDomain()))
    def import_accounts(self, domainid):
        "import accounts"
        try:
            cachekey = u'domain-%s' % domainid
            domain = Session.query(Domain.id, Domain.name)\
                    .filter(Domain.id==domainid)\
                    .options(FromCache('sql_cache_med', cachekey)).one()
        except NoResultFound:
            abort(404)

        c.form = ImportCSVForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            basedir = config['pylons.cache_dir']
            csvdata = request.POST['csvfile']
            if hasattr(csvdata, 'filename'):
                dstfile = os.path.join(basedir, 'uploads',
                                       csvdata.filename.lstrip(os.sep))
                if not os.path.exists(dstfile) and iscsv(csvdata.file):
                    csvfile = open(dstfile, 'w')
                    shutil.copyfileobj(csvdata.file, csvfile)
                    csvdata.file.close()
                    csvfile.close()
                    task = importaccounts.apply_async(args=[
                        domainid, dstfile, c.form.skipfirst.data, c.user.id
                    ])
                    session['taskids'].append(task.task_id)
                    session['acimport-count'] = 1
                    session['acimport-file'] = dstfile
                    session.save()
                    flash(
                        _('File uploaded, and is being processed, this page'
                          ' will automatically refresh to show the status'))
                    redirect(url('accounts-import-status',
                                 taskid=task.task_id))
                else:
                    filename = csvdata.filename.lstrip(os.sep)
                    if not iscsv(csvdata.file):
                        flash_alert(
                            _('The file: %s is not a CSV file') % filename)
                    else:
                        flash_alert(
                            _('The file: %s already exists and'
                              ' is being processed.') % filename)
                    csvdata.file.close()
            else:
                flash_alert(_('No CSV was file uploaded, try again'))

        c.domain = domain
        return render('/accounts/importaccounts.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def import_status(self, taskid):
        "import status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(
                        _('Error occured in processing %s') % result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='accounts'))
            update_serial.delay()
            audit_log(c.user.username, 3, ACCOUNTIMPORT_MSG, request.host,
                      request.remote_addr, now())
        else:
            session['acimport-count'] += 1
            if (session['acimport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['acimport-file'])
                except OSError:
                    pass
                del session['acimport-count']
                session.save()
                flash_alert(
                    _('The import could not be processed,'
                      ' try again later'))
                redirect(url(controller='accounts'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return render('/accounts/importstatus.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def export_accounts(self, domainid=None, orgid=None):
        "export domains"
        task = exportaccounts.apply_async(args=[domainid, c.user.id, orgid])
        if not 'taskids' in session:
            session['taskids'] = []
        session['taskids'].append(task.task_id)
        session['acexport-count'] = 1
        session.save()
        flash(_('Accounts export is being processed'))
        redirect(url('accounts-export-status', taskid=task.task_id))

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def export_status(self, taskid):
        "export status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(
                        _('Error occured in processing %s') % result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='accounts', action='index'))
            results = dict(
                f=True if not result.result['global_error'] else False,
                id=taskid,
                global_error=result.result['global_error'])
            audit_log(c.user.username, 5, ACCOUNTEXPORT_MSG, request.host,
                      request.remote_addr, now())
        else:
            session['acexport-count'] += 1
            if (session['acexport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['acexport-count']
                session.save()
                flash_alert(
                    _('The export could not be processed, try again later'))
                redirect(url(controller='accounts', action='index'))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            response.content_type = 'text/csv'
            response.headers['Cache-Control'] = 'max-age=0'
            csvdata = result.result['f']
            disposition = 'attachment; filename=accounts-export-%s.csv' % taskid
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(csvdata)
            return csvdata
        return render('/accounts/exportstatus.html')

    @ActionProtector(All(not_anonymous(), OnlyAdminUsers()))
    def setnum(self, format=None):
        "Set number of account items returned"
        num = check_num_param(request)

        if num and num in [10, 20, 50, 100]:
            session['accounts_num_items'] = num
            session.save()
        nextpage = request.headers.get('Referer', '/')
        if '://' in nextpage:
            from_url = urlparse(nextpage)
            nextpage = from_url[2]
        redirect(nextpage)