Export authentication default views.
767267
protected function exportViews()
    {
        foreach ($this->views as $pathIn => $pathOut) {
            if ($this->files->exists($view = resource_path('views/'.$pathOut)) && ! $this->option('force')) {
                if (! $this->confirm("The [{$pathOut}] view already exists. Do you want to overwrite it?")) {
                    continue;
                }
            }

            $this->files->copy(
                __DIR__.'/stubs/make/views/'.$pathIn,
                $view
            );
        }
    }
694966
def export_view(self, request, form_url=''):
        """"""

        info = self.opts.app_label, self.opts.model_name

        if not self.has_export_permission(request):
            raise PermissionDenied

        form = SubmissionExportForm(data=request.POST if request.method == 'POST' else None)

        if form.is_valid():
            data = form.cleaned_data
            queryset = self.get_queryset(request) \
                .filter(plugin_id=data.get('form')) \
                .select_related('created_by', 'plugin', )

            from_date, to_date = data.get('from_date'), data.get('to_date')
            headers = data.get('headers', [])

            if from_date:
                queryset = queryset.filter(creation_date__gte=from_date)
            if to_date:
                queryset = queryset.filter(creation_date__lt=to_date + datetime.timedelta(days=1))

            if not queryset.exists():
                message = _('No matching %s found for the given criteria. '
                            'Please try again.') % self.opts.verbose_name_plural
                self.message_user(request, message, level=messages.WARNING)
                if request.is_ajax():
                    data = {
                        'reloadBrowser': True,
                        'submissionCount': 0,
                    }
                    return JsonResponse(data)
                return redirect('admin:%s_%s_export' % info)

            latest_submission = queryset[:1].get()
            dataset = Dataset(title=Truncator(latest_submission.plugin.name).chars(31))

            if not headers:
                headers = [field['label'].strip() for field in latest_submission.form_data]
                for submission in queryset:
                    for field in submission.form_data:
                        label = field['label'].strip()
                        if label not in headers:
                            headers.append(label)

                if request.is_ajax():
                    data = {
                        'reloadBrowser': False,
                        'submissionCount': queryset.count(),
                        'availableHeaders': headers,
                    }
                    return JsonResponse(data)

            headers.extend(['Submitted By', 'Submitted on', 'Sender IP', 'Referrer URL'])
            dataset.headers = headers

            def humanize(field):
                value = field['value']
                field_type = field['type']

                if value in (None, '', [], (), {}):
                    return None

                if field_type == 'checkbox':
                    value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
                if field_type == 'checkbox_multiple':
                    value = ', '.join(list(value))
                return value

            for submission in queryset:
                row = [None] * len(headers)
                for field in submission.form_data:
                    label = field['label'].strip()
                    if label in headers:
                        row[headers.index(label)] = humanize(field)

                    row[-4] = force_text(submission.created_by or _('Unknown')) 
                    row[-3] = submission.creation_date.strftime(
                        settings.DJANGOCMS_FORMS_DATETIME_FORMAT)
                    row[-2] = submission.ip
                    row[-1] = submission.referrer
                dataset.append(row)

            mimetype = {
                'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'csv': 'text/csv',
                'html': 'text/html',
                'yaml': 'text/yaml',
                'json': 'application/json',
            }

            file_type = data.get('file_type', 'xlsx')
            filename = settings.DJANGOCMS_FORMS_EXPORT_FILENAME.format(
                form_name=slugify(latest_submission.plugin.name))
            filename = timezone.now().strftime(filename)
            filename = '%s.%s' % (filename, file_type)

            response = HttpResponse(
                getattr(dataset, file_type), {
                    'content_type': mimetype.get(file_type, 'application/octet-stream')
                })

            response['Content-Disposition'] = 'attachment; filename=%s' % filename
            return response

        # Wrap in all admin layout
        fieldsets = ((None, {'fields': form.fields.keys()}),)
        adminform = AdminForm(form, fieldsets, {}, model_admin=self)
        media = self.media + adminform.media

        context = {
            'title': _('Export %s') % force_text(self.opts.verbose_name_plural),
            'adminform': adminform,
            'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),
            'media': mark_safe(media),
            'errors': AdminErrorList(form, ()),
            'app_label': self.opts.app_label,
        }
        return self.render_export_form(request, context, form_url)
1196720
def export_roles(self):
        
        # prepare the report by removing unnecessary fields
        del self.report["state"]
        del self.report["stats"]
        for role in self.report["roles"]:
            del self.report["roles"][role]["state"]

            defaults_path = os.path.join(self.roles_path, role,
                                         "defaults", "main.yml")
            if os.path.exists(defaults_path):
                defaults = self.report["roles"][role]["defaults"]
                self.report["roles"][role]["defaults"] = \
                    utils.yaml_load("", defaults)

        Export(self.roles_path, self.report, self.config, self.options)
870796
def export(self):
        """"""
        fields = ['id', 'host', 'port', 'user']
        out = {}
        for field in fields:
            out[field] = getattr(self, field, None)
        out['mountOptions'] = self.mount_opts
        out['mountPoint'] = self.mount_point
        out['beforeMount'] = self.cmd_before_mount
        out['authType'] = self.auth_method
        out['sshKey'] = self.ssh_key
        return json.dumps(out, indent=4)
480882
def authentications_spec(self):
        """"""
        return container_spec(authentication_objs.Authentication
              , dictof(string_spec(), set_options(
                  reading = optional_spec(authentication_spec())
                , writing = optional_spec(authentication_spec())
                )
              )
            )
1090602
def process_view(self, request, view_func, view_args, view_kwargs):
        

        if view_func == login:
            return cas_login(request, *view_args, **view_kwargs)
        elif view_func == logout:
            return cas_logout(request, *view_args, **view_kwargs)

        if view_func in (cas_login, cas_logout):
            return None

        if settings.CAS_ADMIN_PREFIX:
            if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
                return None
        elif not view_func.__module__.startswith('django.contrib.admin.'):
            return None

        if request.user.is_authenticated:
            if request.user.is_staff:
                return None
            else:
                raise PermissionDenied(_('You do not have staff privileges.'))
        params = urllib_parse.urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
        return HttpResponseRedirect(reverse(settings.CAS_LOGIN_URL_NAME) + '?' + params)
300843
def index_view(request, auth_form=None, force_login=False, added_context=None):
    """"""
    if request.user.is_authenticated and not force_login:
        return dashboard_view(request)
    else:
        auth_form = auth_form or AuthenticateForm()
        request.session.set_test_cookie()

        fcps_emerg = get_fcps_emerg(request)

        try:
            login_warning = settings.LOGIN_WARNING
        except AttributeError:
            login_warning = None

        if fcps_emerg and not login_warning:
            login_warning = fcps_emerg

        ap_week = get_ap_week_warning(request)

        if ap_week and not login_warning:
            login_warning = ap_week

        events = Event.objects.filter(time__gte=datetime.now(), time__lte=(datetime.now().date() + relativedelta(weeks=1)), public=True).this_year()
        sports_events = events.filter(approved=True, category="sports").order_by('time')[:3]
        school_events = events.filter(approved=True, category="school").order_by('time')[:3]

        data = {
            "auth_form": auth_form,
            "request": request,
            "git_info": settings.GIT,
            "bg_pattern": get_bg_pattern(),
            "theme": get_login_theme(),
            "login_warning": login_warning,
            "senior_graduation": settings.SENIOR_GRADUATION,
            "senior_graduation_year": settings.SENIOR_GRADUATION_YEAR,
            "sports_events": sports_events,
            "school_events": school_events
        }
        schedule = schedule_context(request)
        data.update(schedule)
        if added_context is not None:
            data.update(added_context)
        return render(request, "auth/login.html", data)
713357
private function exportViews()
    {
        if (false === $this->dumpSettings['no-create-info']) {
            // Exporting views one by one
            foreach ($this->views as $view) {
                if ($this->matches($view, $this->dumpSettings['exclude-tables'])) {
                    continue;
                }
                $this->tableColumnTypes[$view] = $this->getTableColumnTypes($view);
                $this->getViewStructureTable($view);
            }
            foreach ($this->views as $view) {
                if ($this->matches($view, $this->dumpSettings['exclude-tables'])) {
                    continue;
                }
                $this->getViewStructureView($view);
            }
        }
    }
930230
def login_view(self):
        """"""

        # Authenticate username/email and login authenticated users.

        safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT)
        safe_reg_next = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT)

        # Immediately redirect already logged in users
        if self.call_or_get(current_user.is_authenticated) and self.USER_AUTO_LOGIN_AT_LOGIN:
            return redirect(safe_next_url)

        # Initialize form
        login_form = self.LoginFormClass(request.form)  # for login.html
        register_form = self.RegisterFormClass()  # for login_or_register.html
        if request.method != 'POST':
            login_form.next.data = register_form.next.data = safe_next_url
            login_form.reg_next.data = register_form.reg_next.data = safe_reg_next

        # Process valid POST
        if request.method == 'POST' and login_form.validate():
            # Retrieve User
            user = None
            user_email = None
            if self.USER_ENABLE_USERNAME:
                # Find user record by username
                user = self.db_manager.find_user_by_username(login_form.username.data)

                # Find user record by email (with form.username)
                if not user and self.USER_ENABLE_EMAIL:
                    user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.username.data)
            else:
                # Find user by email (with form.email)
                user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.email.data)

            if user:
                # Log user in
                safe_next_url = self.make_safe_url(login_form.next.data)
                return self._do_login_user(user, safe_next_url, login_form.remember_me.data)

        # Render form
        self.prepare_domain_translations()
        template_filename = self.USER_LOGIN_AUTH0_TEMPLATE if self.USER_ENABLE_AUTH0 else self.USER_LOGIN_TEMPLATE
        return render_template(template_filename,
                      form=login_form,
                      login_form=login_form,
                      register_form=register_form)
1121754
def render_or_default(name, args = {})
      render name, args
    rescue ActionView::MissingTemplate
      render args.merge(:template => "#{self.class.default_views}/#{name}", :prefix => '')
    end
1269101
def app_view(name, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('app:view', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })
21912
def protected_resource_view(scopes=None):
    
    if scopes is None:
        scopes = []

    def wrapper(view):
        def view_wrapper(request,  *args, **kwargs):
            access_token = extract_access_token(request)

            try:
                try:
                    kwargs['token'] = Token.objects.get(access_token=access_token)
                except Token.DoesNotExist:
                    logger.debug('[UserInfo] Token does not exist: %s', access_token)
                    raise BearerTokenError('invalid_token')

                if kwargs['token'].has_expired():
                    logger.debug('[UserInfo] Token has expired: %s', access_token)
                    raise BearerTokenError('invalid_token')

                if not set(scopes).issubset(set(kwargs['token'].scope)):
                    logger.debug('[UserInfo] Missing openid scope.')
                    raise BearerTokenError('insufficient_scope')
            except BearerTokenError as error:
                response = HttpResponse(status=error.status)
                response['WWW-Authenticate'] = 'error="{0}", error_description="{1}"'.format(
                    error.code, error.description)
                return response

            return view(request,  *args, **kwargs)

        return view_wrapper

    return wrapper
1368520
def load_views(self):
        """"""
        view_path = os.path.join(self.path, StatikProject.VIEWS_DIR)
        logger.debug("Loading views from: %s", view_path)
        if not os.path.isdir(view_path):
            raise MissingProjectFolderError(StatikProject.VIEWS_DIR)

        view_files = list_files(view_path, ['yml', 'yaml'])
        logger.debug("Found %d view(s) in project", len(view_files))
        views = {}
        for view_file in view_files:
            view_name = extract_filename(view_file)
            views[view_name] = StatikView(
                filename=os.path.join(view_path, view_file),
                encoding=self.config.encoding,
                name=view_name,
                models=self.models,
                template_engine=self.template_engine,
                error_context=self.error_context
            )

        return views
1218542
def authenticated(viewfunc):
    """"""
    @wraps(viewfunc)
    def wrapper(*args, **kwargs):
        ctx = stack.top
        if ctx and hasattr(ctx, 'htauth'):
            auth_header = request.headers.get('Authorization', None)
            if not auth_header:
                return _unauthorized_response()

            if not auth_header.startswith('Basic '):
                raise RuntimeError('Flask-HTAuth supports only Basic auth.')

            auth_header = auth_header.replace('Basic ', '')
            auth_header = base64.b64decode(auth_header)
            username, password = auth_header.split(':', 1)

            if not username in ctx.htauth['users']:
                return _unauthorized_response()

            if not check_password(password, ctx.htauth['users'][username]):
                return _unauthorized_response()

            g.htauth_user = username

        return viewfunc(*args, **kwargs)

    return wrapper
818503
private void updateViewDefaultTemplateWhenGovernanceIsNotInstalled(DbSession dbSession, PermissionTemplateDto template, DefaultTemplates defaultTemplates) {
    String viewDefaultTemplateUuid = defaultTemplates.getApplicationsUuid();
    if (viewDefaultTemplateUuid != null && viewDefaultTemplateUuid.equals(template.getUuid())) {
      defaultTemplates.setApplicationsUuid(null);
      dbClient.organizationDao().setDefaultTemplates(dbSession, template.getOrganizationUuid(), defaultTemplates);
    }
  }
1324751
def preview(request):
    
    if settings.MARKDOWN_PROTECT_PREVIEW:
        user = getattr(request, 'user', None)
        if not user or not user.is_staff:
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(request.get_full_path())

    return render(
        request, settings.MARKDOWN_PREVIEW_TEMPLATE, dict(
            content=request.POST.get('data', 'No content posted'),
            css=settings.MARKDOWN_STYLE
        ))
570336
def get_default_credentials(scopes):
    """"""
    credentials, _ = google.auth.default(scopes=scopes)
    return credentials