Exemple #1
0
  def listTasks(self, request, access_type, page_name=None, params=None,
                **kwargs):
    """View where all the tasks can be searched from.
    """

    from soc.modules.gci.views.models.task import view as task_view

    logic = params['logic']

    program_entity = logic.getFromKeyFieldsOr404(kwargs)

    page_name = '%s %s' % (page_name, program_entity.name)

    list_params = task_view.getParams().copy()

    user_account = user_logic.getCurrentUser()
    user_fields = {
        'user': user_account,
        'status': 'active'
        }

    host_entity = host_logic.getForFields(user_fields, unique=True)

    tasks_filter = {
        'program': program_entity,
        'status': ['Open', 'Reopened', 'ClaimRequested']
    }

    if host_entity:
      list_params['list_description'] = self.DEF_LIST_VALID_TASKS_MSG_FMT % (
          program_entity.name)
      tasks_filter['status'].extend([
          'Claimed', 'ActionNeeded', 'Closed', 'AwaitingRegistration',
          'NeedsWork', 'NeedsReview','Unapproved', 'Unpublished'])
    else:
      list_params.setdefault('public_field_ignore', []).append('mentors')
      list_params['list_description'] = self.DEF_LIST_PUBLIC_TASKS_MSG_FMT % (
          program_entity.name)

    list_params['public_row_extra'] = lambda entity, *args: {
        'link': redirects.getPublicRedirect(entity, list_params)
        }

    list_params['public_conf_min_num'] = list_params['public_conf_limit'] = 100

    if lists.isDataRequest(request):
        return self.getListTasksData(request, list_params, tasks_filter)

    contents = []
    order = ['-modified_on']

    tasks_list = lists.getListGenerator(request, list_params,
                                        order=order, idx=0)
    contents.append(tasks_list)

    return self._list(request, list_params, contents, page_name)
Exemple #2
0
    def checkRoleAndStatusForStudentProposal(self, django_args, allowed_roles,
                                             role_status, proposal_status):
        """Checks if the current user has access to the given proposal.

    Args:
      django_args: a dictionary with django's arguments
      allowed_roles: list with names for the roles allowed to pass access check
      role_status: list with states allowed for the role
      proposal_status: a list with states allowed for the proposal

     Raises:
       AccessViolationResponse:
         - If there is no proposal found
         - If the proposal is not in one of the required states.
         - If the user does not have any ofe the required roles
    """

        self.checkIsUser(django_args)

        # bail out with 404 if no proposal is found
        proposal_entity = student_proposal_logic.getFromKeyFieldsOr404(
            django_args)

        if not proposal_entity.status in proposal_status:
            # this proposal can not be accessed at the moment
            raise out_of_band.AccessViolation(
                message_fmt=access.DEF_NO_ACTIVE_ENTITY_MSG)

        user_entity = self.user

        if 'proposer' in allowed_roles:
            # check if this proposal belongs to the current user
            student_entity = proposal_entity.scope
            if (user_entity.key()
                    == student_entity.user.key()) and (student_entity.status
                                                       in role_status):
                return

        filter = {'user': user_entity, 'status': role_status}

        if 'host' in allowed_roles:
            # check if the current user is a host for this proposal's program
            filter['scope'] = proposal_entity.program.scope

            if host_logic.getForFields(filter, unique=True):
                return

        if 'org_admin' in allowed_roles:
            # check if the current user is an admin for this proposal's org
            filter['scope'] = proposal_entity.org

            if org_admin_logic.getForFields(filter, unique=True):
                return

        if 'mentor' in allowed_roles:
            # check if the current user is a mentor for this proposal's org
            filter['scope'] = proposal_entity.org

            if mentor_logic.getForFields(filter, unique=True):
                return

        # no roles found, access denied
        raise out_of_band.AccessViolation(message_fmt=access.DEF_NEED_ROLE_MSG)
Exemple #3
0
  def checkRoleAndStatusForStudentProposal(self, django_args, allowed_roles,
                                           role_status, proposal_status):
    """Checks if the current user has access to the given proposal.

    Args:
      django_args: a dictionary with django's arguments
      allowed_roles: list with names for the roles allowed to pass access check
      role_status: list with states allowed for the role
      proposal_status: a list with states allowed for the proposal

     Raises:
       AccessViolationResponse:
         - If there is no proposal found
         - If the proposal is not in one of the required states.
         - If the user does not have any ofe the required roles
    """

    self.checkIsUser(django_args)

    # bail out with 404 if no proposal is found
    proposal_entity = student_proposal_logic.getFromKeyFieldsOr404(django_args)

    if not proposal_entity.status in proposal_status:
      # this proposal can not be accessed at the moment
      raise out_of_band.AccessViolation(
          message_fmt=access.DEF_NO_ACTIVE_ENTITY_MSG)

    user_entity = self.user

    if 'proposer' in allowed_roles:
      # check if this proposal belongs to the current user
      student_entity = proposal_entity.scope
      if (user_entity.key() == student_entity.user.key()) and (
          student_entity.status in role_status):
        return

    filter = {'user': user_entity,
        'status': role_status}

    if 'host' in allowed_roles:
      # check if the current user is a host for this proposal's program
      filter['scope'] =  proposal_entity.program.scope

      if host_logic.getForFields(filter, unique=True):
        return

    if 'org_admin' in allowed_roles:
      # check if the current user is an admin for this proposal's org
      filter['scope'] = proposal_entity.org

      if org_admin_logic.getForFields(filter, unique=True):
        return

    if 'mentor' in allowed_roles:
      # check if the current user is a mentor for this proposal's org
      filter['scope'] = proposal_entity.org

      if mentor_logic.getForFields(filter, unique=True):
        return

    # no roles found, access denied
    raise out_of_band.AccessViolation(
        message_fmt=access.DEF_NEED_ROLE_MSG)
Exemple #4
0
    def listTasks(self,
                  request,
                  access_type,
                  page_name=None,
                  params=None,
                  **kwargs):
        """View where all the tasks can be searched from.
    """

        from soc.modules.gci.views.models.task import view as task_view

        logic = params['logic']

        program_entity = logic.getFromKeyFieldsOr404(kwargs)

        page_name = '%s %s' % (page_name, program_entity.name)

        list_params = task_view.getParams().copy()

        user_account = user_logic.getCurrentUser()
        user_fields = {'user': user_account, 'status': 'active'}

        host_entity = host_logic.getForFields(user_fields, unique=True)

        tasks_filter = {
            'program': program_entity,
            'status': ['Open', 'Reopened', 'ClaimRequested']
        }

        if host_entity:
            list_params[
                'list_description'] = self.DEF_LIST_VALID_TASKS_MSG_FMT % (
                    program_entity.name)
            tasks_filter['status'].extend([
                'Claimed', 'ActionNeeded', 'Closed', 'AwaitingRegistration',
                'NeedsWork', 'NeedsReview', 'Unapproved', 'Unpublished'
            ])
        else:
            list_params.setdefault('public_field_ignore', []).append('mentors')
            list_params[
                'list_description'] = self.DEF_LIST_PUBLIC_TASKS_MSG_FMT % (
                    program_entity.name)

        list_params['public_row_extra'] = lambda entity, *args: {
            'link': redirects.getPublicRedirect(entity, list_params)
        }

        list_params['public_conf_min_num'] = list_params[
            'public_conf_limit'] = 100

        if lists.isDataRequest(request):
            return self.getListTasksData(request, list_params, tasks_filter)

        contents = []
        order = ['-modified_on']

        tasks_list = lists.getListGenerator(request,
                                            list_params,
                                            order=order,
                                            idx=0)
        contents.append(tasks_list)

        return self._list(request, list_params, contents, page_name)
Exemple #5
0
    def _getTimeDependentEntries(self, gci_program_entity, params, id, user):
        """Returns a list with time dependent menu items.
    """

        items = []

        timeline_entity = gci_program_entity.timeline

        # add show ranking item
        if timeline_helper.isAfterEvent(timeline_entity,
                                        'tasks_publicly_visible'):
            items += [(gci_redirects.getShowRankingRedirect(
                gci_program_entity,
                {'url_name': 'gci/program'}), 'Show Ranking', 'any_access')]

        mentor_entity = None
        org_admin_entity = None

        org_app_survey = org_app_logic.getForProgram(gci_program_entity)

        if org_app_survey and \
            timeline_helper.isActivePeriod(org_app_survey, 'survey'):
            # add the organization signup link
            items += [
                (redirects.getTakeSurveyRedirect(org_app_survey,
                                                 {'url_name': 'gci/org_app'}),
                 "Apply to become an Organization", 'any_access')
            ]

        if user and org_app_survey and timeline_helper.isAfterEvent(
                org_app_survey, 'survey_start'):

            main_admin_fields = {
                'main_admin': user,
                'survey': org_app_survey,
            }

            backup_admin_fields = {
                'backup_admin': user,
                'survey': org_app_survey
            }

            org_app_record_logic = org_app_logic.getRecordLogic()

            if org_app_record_logic.getForFields(main_admin_fields, unique=True) or \
                org_app_record_logic.getForFields(backup_admin_fields, unique=True):
                # add the 'List my Organization Applications' link
                items += [(redirects.getListSelfRedirect(
                    org_app_survey, {'url_name': 'gci/org_app'}),
                           "List My Organization Applications", 'any_access')]

        # get the student entity for this user and program
        filter = {
            'user': user,
            'scope': gci_program_entity,
            'status': ['active', 'inactive']
        }
        student_entity = gci_student_logic.logic.getForFields(filter,
                                                              unique=True)

        # students can register after successfully completing their first
        # task. So if a user has completed one task he is still a student
        filter = {
            'user': user,
            'program': gci_program_entity,
        }
        has_completed_task = gci_task_logic.logic.getForFields(filter,
                                                               unique=True)

        if student_entity or (user and has_completed_task):
            items += self._getStudentEntries(gci_program_entity,
                                             student_entity, params, id, user,
                                             'gci')
        else:
            # get mentor and org_admin entity for this user and program
            filter = {
                'user': user,
                'program': gci_program_entity,
                'status': 'active'
            }
            mentor_entity = gci_mentor_logic.logic.getForFields(filter,
                                                                unique=True)
            org_admin_entity = gci_org_admin_logic.logic.getForFields(
                filter, unique=True)

            if timeline_helper.isAfterEvent(
                    timeline_entity,
                    'accepted_organization_announced_deadline'):
                if mentor_entity or org_admin_entity:
                    items += self._getOrganizationEntries(
                        gci_program_entity, org_admin_entity, mentor_entity,
                        params, id, user)
                if timeline_helper.isBeforeEvent(timeline_entity,
                                                 'program_end'):
                    # add apply to become a mentor link
                    items += [('/gci/org/apply_mentor/%s' %
                               (gci_program_entity.key().id_or_name()),
                               "Apply to become a Mentor", 'any_access')]

        if timeline_helper.isAfterEvent(
                timeline_entity, 'accepted_organization_announced_deadline'):
            url = redirects.getAcceptedOrgsRedirect(gci_program_entity, params)
            # add a link to list all the organizations
            items += [(url, "List participating Organizations", 'any_access')]

        user_fields = {'user': user, 'status': 'active'}
        host_entity = host_logic.getForFields(user_fields, unique=True)

        # for org admins this link should be visible only after accepted
        # organizations are announced and for other public after the tasks
        # are public but for program host it must be visible always
        if (host_entity or ((org_admin_entity or mentor_entity)
                            and timeline_helper.isAfterEvent(
                                timeline_entity, 'tasks_publicly_visible'))
                or (timeline_helper.isAfterEvent(timeline_entity,
                                                 'tasks_publicly_visible'))):
            url = gci_redirects.getListAllTasksRedirect(
                gci_program_entity, params)
            # add a link to list all the organizations
            items += [(url, "List all tasks", 'any_access')]

            if user:
                # add a link to show all tasks of interest
                items += [(gci_redirects.getListMyTasksRedirect(
                    gci_program_entity,
                    params), 'List my Tasks', 'any_access')]

        return items
Exemple #6
0
    def showRanking(self,
                    request,
                    access_type,
                    page_name=None,
                    params=None,
                    **kwargs):
        """Shows the ranking for the program specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        from soc.modules.gci.views.models.student_ranking import view as ranking_view
        from soc.modules.gci.views.models.student import view as student_view

        sparams = student_view.getParams()

        user_account = user_logic.getCurrentUser()
        user_fields = {'user': user_account, 'status': 'active'}
        host_entity = host_logic.getForFields(user_fields, unique=True)
        is_host = host_entity or user_logic.isDeveloper(user=user_account)

        logic = params['logic']
        program = logic.getFromKeyFieldsOr404(kwargs)

        list_params = ranking_view.getParams().copy()

        list_params['list_description'] = self.DEF_LIST_RANKING_MSG_FMT % (
            program.name)

        list_params['public_field_keys'] = ["student", "points", "number"]
        list_params['public_field_names'] = [
            "Student", "Points", "Number of tasks"
        ]
        list_params['public_conf_extra'] = {
            "rowNum": -1,
            "rowList": [],
        }
        list_params['public_field_prefetch'] = ['student']

        def getExtraFields(entity, *args):
            res = {
                'student': entity.student.user.name,
                'number': len(entity.tasks)
            }
            if is_host:
                fields = sparams['admin_field_keys']
                extra = dicts.toDict(entity.student, fields)
                res.update(extra)
                res['group_name'] = entity.student.scope.name
                res['birth_date'] = entity.student.birth_date.isoformat()
                res['account_name'] = accounts.normalizeAccount(
                    entity.student.user.account).email()
                res['forms_submitted'] = "Yes" if (
                    entity.student.consent_form
                    and entity.student.student_id_form) else "No"
            return res

        list_params['public_field_extra'] = getExtraFields
        list_params['public_row_extra'] = lambda entity, *args: {
            'link': gci_redirects.getShowRankingDetails(entity, list_params)
        }

        list_params['public_field_props'] = {
            'points': {
                'sorttype': 'integer',
            },
            'number': {
                'sorttype': 'integer',
            },
        }
        if is_host:
            list_params['public_field_keys'] += ["forms_submitted"]
            list_params['public_field_names'] += ["Forms submitted"]
            list_params['public_field_hidden'] = sparams[
                'admin_field_hidden'] + sparams['admin_field_keys']
            list_params['public_field_keys'].extend(
                sparams['admin_field_keys'])
            list_params['public_field_names'].extend(
                sparams['admin_field_names'])

        ranking_filter = {'scope': program}

        order = ['-points']

        if lists.isDataRequest(request):
            contents = lists.getListData(request, list_params, ranking_filter)
            return lists.getResponse(request, contents)

        contents = [
            lists.getListGenerator(request, list_params, order=order, idx=0)
        ]

        return self._list(request,
                          list_params,
                          contents=contents,
                          page_name=page_name)
Exemple #7
0
  def showRanking(self, request, access_type,
                  page_name=None, params=None, **kwargs):
    """Shows the ranking for the program specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    from soc.modules.gci.views.models.student_ranking import view as ranking_view
    from soc.modules.gci.views.models.student import view as student_view

    sparams = student_view.getParams()

    user_account = user_logic.getCurrentUser()
    user_fields = {
        'user': user_account,
        'status': 'active'
        }
    host_entity = host_logic.getForFields(user_fields, unique=True)
    is_host = host_entity or user_logic.isDeveloper(user=user_account)

    logic = params['logic']
    program = logic.getFromKeyFieldsOr404(kwargs)

    list_params = ranking_view.getParams().copy()

    list_params['list_description'] = self.DEF_LIST_RANKING_MSG_FMT % (
        program.name)

    list_params['public_field_keys'] = ["student", "points", "number"]
    list_params['public_field_names'] = ["Student", "Points", "Number of tasks"]
    list_params['public_conf_extra'] = {
        "rowNum": -1,
        "rowList": [],
        }
    list_params['public_field_prefetch'] = ['student']
    def getExtraFields(entity, *args):
      res = {
          'student': entity.student.user.name,
          'number': len(entity.tasks)
      }
      if is_host:
        fields = sparams['admin_field_keys']
        extra = dicts.toDict(entity.student, fields)
        res.update(extra)
        res['group_name'] = entity.student.scope.name
        res['birth_date'] = entity.student.birth_date.isoformat()
        res['account_name'] = accounts.normalizeAccount(entity.student.user.account).email()
        res['forms_submitted'] = "Yes" if (entity.student.consent_form and entity.student.student_id_form) else "No"
      return res

    list_params['public_field_extra'] = getExtraFields
    list_params['public_row_extra'] = lambda entity, *args: {
        'link': gci_redirects.getShowRankingDetails(entity, list_params)
    }

    list_params['public_field_props'] = {
        'points': {
            'sorttype': 'integer',
        },
        'number': {
            'sorttype': 'integer',
        },
    }
    if is_host:
      list_params['public_field_keys'] += ["forms_submitted"]
      list_params['public_field_names'] += ["Forms submitted"]
      list_params['public_field_hidden'] = sparams['admin_field_hidden'] + sparams['admin_field_keys']
      list_params['public_field_keys'].extend(sparams['admin_field_keys'])
      list_params['public_field_names'].extend(sparams['admin_field_names'])

    ranking_filter = {
        'scope': program
        }

    order = ['-points']

    if lists.isDataRequest(request):
      contents = lists.getListData(request, list_params, ranking_filter)
      return lists.getResponse(request, contents)

    contents = [lists.getListGenerator(
        request, list_params, order=order, idx=0)]

    return self._list(request, list_params, contents=contents,
        page_name=page_name)
Exemple #8
0
  def _getTimeDependentEntries(self, gci_program_entity, params, id, user):
    """Returns a list with time dependent menu items.
    """

    items = []

    timeline_entity = gci_program_entity.timeline

    # add show ranking item
    if timeline_helper.isAfterEvent(timeline_entity, 'tasks_publicly_visible'):
      items += [(gci_redirects.getShowRankingRedirect(
           gci_program_entity, {'url_name': 'gci/program'}),
           'Show Ranking', 'any_access')]

    mentor_entity = None
    org_admin_entity = None

    org_app_survey = org_app_logic.getForProgram(gci_program_entity)

    if org_app_survey and \
        timeline_helper.isActivePeriod(org_app_survey, 'survey'):
      # add the organization signup link
      items += [
          (redirects.getTakeSurveyRedirect(
               org_app_survey, {'url_name': 'gci/org_app'}),
          "Apply to become an Organization", 'any_access')]

    if user and org_app_survey and timeline_helper.isAfterEvent(
        org_app_survey, 'survey_start'):

      main_admin_fields = {
          'main_admin': user,
          'survey': org_app_survey,
          }

      backup_admin_fields = {
          'backup_admin': user,
          'survey': org_app_survey
          }

      org_app_record_logic = org_app_logic.getRecordLogic()

      if org_app_record_logic.getForFields(main_admin_fields, unique=True) or \
          org_app_record_logic.getForFields(backup_admin_fields, unique=True):
        # add the 'List my Organization Applications' link
        items += [
            (redirects.getListSelfRedirect(org_app_survey,
                                           {'url_name' : 'gci/org_app'}),
             "List My Organization Applications", 'any_access')]

    # get the student entity for this user and program
    filter = {'user': user,
              'scope': gci_program_entity,
              'status': ['active', 'inactive']}
    student_entity = gci_student_logic.logic.getForFields(filter, unique=True)

    # students can register after successfully completing their first
    # task. So if a user has completed one task he is still a student
    filter = {
        'user': user,
        'program': gci_program_entity,
        }
    has_completed_task = gci_task_logic.logic.getForFields(
        filter, unique=True)

    if student_entity or (user and has_completed_task):
      items += self._getStudentEntries(gci_program_entity, student_entity,
                                       params, id, user, 'gci')
    else:
      # get mentor and org_admin entity for this user and program
      filter = {
          'user': user,
          'program': gci_program_entity,
          'status': 'active'
          }
      mentor_entity = gci_mentor_logic.logic.getForFields(filter, unique=True)
      org_admin_entity = gci_org_admin_logic.logic.getForFields(
          filter, unique=True)

      if timeline_helper.isAfterEvent(
          timeline_entity, 'accepted_organization_announced_deadline'):
        if mentor_entity or org_admin_entity:
          items += self._getOrganizationEntries(
              gci_program_entity, org_admin_entity,
              mentor_entity, params, id, user)
        if timeline_helper.isBeforeEvent(timeline_entity, 'program_end'):
          # add apply to become a mentor link
          items += [
              ('/gci/org/apply_mentor/%s' % (
                  gci_program_entity.key().id_or_name()),
                  "Apply to become a Mentor", 'any_access')]

    if timeline_helper.isAfterEvent(
        timeline_entity, 'accepted_organization_announced_deadline'):
      url = redirects.getAcceptedOrgsRedirect(
          gci_program_entity, params)
      # add a link to list all the organizations
      items += [(url, "List participating Organizations", 'any_access')]

    user_fields = {
        'user': user,
        'status': 'active'
        }
    host_entity = host_logic.getForFields(user_fields, unique=True)

    # for org admins this link should be visible only after accepted
    # organizations are announced and for other public after the tasks
    # are public but for program host it must be visible always
    if (host_entity or
        ((org_admin_entity or mentor_entity) and timeline_helper.isAfterEvent(
        timeline_entity, 'tasks_publicly_visible')) or
        (timeline_helper.isAfterEvent(
        timeline_entity, 'tasks_publicly_visible'))):
      url = gci_redirects.getListAllTasksRedirect(
          gci_program_entity, params)
      # add a link to list all the organizations
      items += [(url, "List all tasks", 'any_access')]

      if user:
        # add a link to show all tasks of interest
        items += [(gci_redirects.getListMyTasksRedirect(
            gci_program_entity, params),
            'List my Tasks', 'any_access')]

    return items