def makeNewPaginationChoices(limit=DEF_DEFAULT_PAGINATION, choices=DEF_PAGINATION_CHOICES): """Updates the pagination limit selection form. Args: limit: the initial value of the selection control; default is DEF_DEFAULT_PAGINATION choices: see soc.views.helper.forms.makeSelectQueryArgForm(); default is DEF_PAGINATION_CHOICES Returns: a new pagination choices list if limit is not in DEF_PAGINATION_CHOICES, or DEF_PAGINATION_CHOICES otherwise """ new_choices = [] new_choice = (str(limit), '%s items per page' % limit) new_choices.append(new_choice) new_choices.extend(choices) if user_logic.isDeveloper(): new_choices.extend(DEF_DEVELOPER_CHOICES) new_choices = set(new_choices) return sorted(new_choices, key=lambda (x, y): int(x))
def getUniversalContext(request): """Constructs a template context dict will many common variables defined. Args: request: the Django HTTP request object Returns: a new context dict containing: { 'request': the Django HTTP request object passed in by the caller 'account': the logged-in Google Account if there is one 'user': the User entity corresponding to the Google Account in context['account'] 'is_admin': True if users.is_current_user_admin() is True 'is_debug': True if system.isDebug() is True 'sign_in': a Google Account login URL 'sign_out': a Google Account logout URL 'sidebar_menu_html': an HTML string that renders the sidebar menu } """ account = accounts.getCurrentAccount() user = None is_admin = False context = {} context['request'] = request if account: user = user_logic.getForAccount(account) is_admin = user_logic.isDeveloper(account=account, user=user) context['account'] = account context['user'] = user context['is_admin'] = is_admin context['is_local'] = system.isLocal() context['is_debug'] = system.isDebug() context['sign_in'] = users.create_login_url(request.path) context['sign_out'] = users.create_logout_url(request.path) context['sidebar_menu_items'] = callback.getCore().getSidebar(account, user) context['gae_version'] = system.getAppVersion() context['soc_release'] = system.getMelangeVersion() settings = site.logic.getSingleton() context['ga_tracking_num'] = settings.ga_tracking_num context['gmaps_api_key'] = settings.gmaps_api_key context['site_name'] = settings.site_name context['site_notice'] = settings.site_notice context['tos_link'] = redirects.getToSRedirect(settings) context['in_maintenance'] = timeline.isActivePeriod(site, 'maintenance') return context
def getListParameters(request, list_index): """Retrieves, converts and validates values for one list Args: list_index, int: which list to get the values for. (there may be multiple lists on one page, which are multiplexed by an integer.) Returns: a dictionary of str -> str. field name -> field value. """ offset = request.GET.get(makeOffsetKey(list_index)) limit = request.GET.get(makeLimitKey(list_index)) if offset is None: offset = '' if limit is None: limit = '' try: offset = int(offset) except ValueError: offset = 0 try: limit = int(limit) except ValueError: limit = getPreferredListPagination() offset = max(0, offset) limit = max(1, limit) if user_logic.isDeveloper(): limit = min(DEF_MAX_DEV_PAGINATION, limit) else: limit = min(DEF_MAX_PAGINATION, limit) result = dict(limit=limit, offset=offset) offset_linkid = request.GET.get(makeOffsetLinkidKey(list_index), '') # TODO(dbentley): URL unescape result['offset_linkid'] = offset_linkid reverse_direction = makeReverseDirectionKey(list_index) in request.GET result['reverse_direction'] = reverse_direction return result
def view_wrapper(request, *args, **kwds): """View decorator wrapper method. """ try: site = site_logic.getSingleton() # don't redirect admins, or if we're at /maintenance already no_redirect = user_logic.isDeveloper() or request.path == "/maintenance" if (not no_redirect) and timeline.isActivePeriod(site, "maintenance"): return http.HttpResponseRedirect("/maintenance") return func(request, *args, **kwds) except DeadlineExceededError, exception: logging.exception(exception) return http.HttpResponseRedirect("/soc/content/deadline_exceeded.html")
def getListParameters(request, list_index): """Retrieves, converts and validates values for one list Args: list_index, int: which list to get the values for. (there may be multiple lists on one page, which are multiplexed by an integer.) Returns: a dictionary of str -> str. field name -> field value. """ offset = request.GET.get(makeOffsetKey(list_index)) limit = request.GET.get(makeLimitKey(list_index)) if offset is None: offset = '' if limit is None: limit = '' try: offset = int(offset) except ValueError: offset = 0 try: limit = int(limit) except ValueError: limit = getPreferredListPagination() offset = max(0, offset) limit = max(1, limit) if user_logic.isDeveloper(): limit = min(DEF_MAX_DEV_PAGINATION, limit) else: limit = min(DEF_MAX_PAGINATION, limit) return dict(limit=limit, offset=offset)
def checkIsDeveloper(self, django_args=None): """Raises an alternate HTTP response if Google Account is not a Developer. Args: django_args: a dictionary with django's arguments, not used Raises: AccessViolationResponse: * if User is not a Developer, or * if no User exists for the logged-in Google Account, or * if no Google Account is logged in at all """ self.checkIsUser() if user_logic.isDeveloper(account=self.id, user=self.user): return login_message_fmt = DEF_DEV_LOGOUT_LOGIN_MSG_FMT % { 'role': 'a Site Developer ', } raise out_of_band.LoginRequest(message_fmt=login_message_fmt)
def getDevMenu(id, user, params): """Returns the developer menu entries for this view. Args: params: a dict with params for this View """ from soc.logic.models.user import logic as user_logic if not user_logic.isDeveloper(account=id, user=user): return dev_items = params['sidebar_developer'] items = getItemsFromDefaults(dev_items, params) if not items: return dev = {} dev['heading'] = "" dev['items'] = [dict(url=u, title=t) for u, t, _ in items] dev['group'] = "Developer" return dev
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)
def getUniversalContext(request): """Constructs a template context dict will many common variables defined. Args: request: the Django HTTP request object Returns: a new context dict containing: { 'request': the Django HTTP request object passed in by the caller 'account': the logged-in Google Account if there is one 'user': the User entity corresponding to the Google Account in context['account'] 'is_admin': True if users.is_current_user_admin() is True 'is_debug': True if system.isDebug() is True 'sign_in': a Google Account login URL 'sign_out': a Google Account logout URL 'sidebar_menu_html': an HTML string that renders the sidebar menu } """ core = callback.getCore() context = core.getRequestValue('context', {}) if context: return context account = accounts.getCurrentAccount() user = None is_admin = False context['request'] = request if account: user = user_logic.getForAccount(account) is_admin = user_logic.isDeveloper(account=account, user=user) context['account'] = account context['user'] = user context['is_admin'] = is_admin context['is_local'] = system.isLocal() context['is_debug'] = system.isDebug() context['sign_in'] = users.create_login_url(request.path) context['sign_out'] = users.create_logout_url(request.path) context['sidebar_menu_items'] = core.getSidebar(account, user) context['gae_version'] = system.getAppVersion() context['soc_release'] = system.getMelangeVersion() settings = site.logic.getSingleton() context['ga_tracking_num'] = settings.ga_tracking_num context['gmaps_api_key'] = settings.gmaps_api_key context['site_name'] = settings.site_name context['site_notice'] = settings.site_notice context['tos_link'] = redirects.getToSRedirect(settings) context['in_maintenance'] = timeline.isActivePeriod( settings, 'maintenance') # Only one xsrf_token is generated per request. xsrf_secret_key = site.logic.getXsrfSecretKey(settings) context['xsrf_token'] = xsrfutil.getGeneratedTokenForCurrentUser( xsrf_secret_key) core.setRequestValue('context', context) return context
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)