def wrapped_f(request, *args, **kwargs): # print self.arg1,'aaaaaaaaaaaaaaaaaaaa' user = request.user path = request.build_absolute_uri() # 用户登录 if not user.is_authenticated(): messages.error(request, "您尚未登录。") return redirect_to_login(path) # 老师用户 try: school = helpers.get_schools(request.user)[0] # print school,'ssssssss' if not school: return f(request, *args, **kwargs) except: messages.error(request, "您的权限不足无法访问。") return redirect(reverse("userena_signin") + "?lack_perm=lack&next=" + str(path)) # return redirect_to_login(path) # 权限判断 code_list = [c.code for c in helpers.user_access_list(user)] # print code_list,'cccccccccc' if self.arg1 in code_list: # print 'in' return f(request, *args, **kwargs) elif user.is_authenticated(): # print 'out' messages.error(request, "您的权限不足无法访问。") return redirect(reverse("userena_signin") + "?lack_perm=lack&next=" + str(path)) # return redirect_to_login(path) else: return redirect_to_login(path)
def dispatch(self, request, *args, **kwargs): self._check_permissions_attr() perms_all = self.permissions.get("all") or None perms_any = self.permissions.get("any") or None self._check_permissions_keys_set(perms_all, perms_any) self._check_perms_keys("all", perms_all) self._check_perms_keys("any", perms_any) # If perms_all, check that user has all permissions in the list/tuple if perms_all: if not request.user.has_perms(perms_all): if self.raise_exception: raise PermissionDenied return redirect_to_login(request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) # If perms_any, check that user has at least one in the list/tuple if perms_any: has_one_perm = False for perm in perms_any: if request.user.has_perm(perm): has_one_perm = True break if not has_one_perm: if self.raise_exception: raise PermissionDenied return redirect_to_login(request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) return super(MultiplePermissionsRequiredMixin, self).dispatch(request, *args, **kwargs)
def activateEmail(request,userid,activation_key): mlogger.debug("Activating email.........................") error = '' try : u = User.objects.get(pk=userid) profile = u.get_profile() if len(profile.activation_key) > 0 : if profile.activation_key == activation_key : #logic for activation key expiration todaydate = datetime.datetime.now() if profile.createddate < todaydate - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) : #activation key has been expired create_message(request,"Activation key has been expired.Please request for a new one") return render_to_response("institution/activation_error.html",RequestContext(request)) #activate the user profile.emailverified = True #reset the activation key profile.activation_key = '' profile.save() create_message(request,"Successfully activated your email") #either login or directly transfer him to the corresponding page return redirect_to_login(next='') else : create_message(request,"Invalid activation key") else : create_message(request,"Invalid Userid and activation key combination...............") return redirect_to_login(next='') return render_to_response("institution/activation_error.html",RequestContext(request)) except User.DoesNotExist : create_message(request,"Invalid Userid and activation key combination...............") return render_to_response("institution/activation_error.html",RequestContext(request))
def _wrapped_view(request, *args, **kwargs): path = request.build_absolute_uri() ext = getattr(request, 'user_extension', None) if ext and not ext.is_deleted: if not (ext.is_merchant and ext.description): # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse.urlparse(login_url or settings.MERCHANT_LOGIN_URL)[:2] current_scheme, current_netloc = urlparse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login(path,'/merchants/register/', redirect_field_name) if not ext.is_approved: return redirect_to_login(path, '/merchants/waiting_approval', redirect_field_name) else: return view_func(request, *args, **kwargs) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse.urlparse(login_url or settings.MERCHANT_LOGIN_URL)[:2] current_scheme, current_netloc = urlparse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login(path, login_url or settings.MERCHANT_LOGIN_URL, redirect_field_name)
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated() or \ (not request.user.is_verified() and default_device(request.user)): # If the user has not authenticated raise or redirect to the login # page. Also if the user just enabled two-factor authentication and # has not yet logged in since should also have the same result. If # the user receives a 'you need to enable TFA' by now, he gets # confuses as TFA has just been enabled. So we either raise or # redirect to the login page. if self.raise_anonymous: raise PermissionDenied() else: return redirect_to_login(request.get_full_path(), self.get_login_url()) if not request.user.is_verified(): if self.raise_unverified: raise PermissionDenied() elif self.get_verification_url(): return redirect_to_login(request.get_full_path(), self.get_verification_url()) else: return TemplateResponse( request=request, template='two_factor/core/otp_required.html', status=403, ) return super(OTPRequiredMixin, self).dispatch(request, *args, **kwargs)
def wrap(request, *args, **kwargs): if not request.user.is_authenticated(): return redirect_to_login(request.get_full_path()) elif not request.user.userprofile.is_jobseeker(): return redirect_to_login(request.get_full_path()) else: return function(request, *args, **kwargs)
def restricted_email(request, form=None, form_template='', message_template='', subject='', recipients=None, redirect_to='/thanks/', uses_captcha=False, editor_required=False): """ Wraps handle_form_and_email() to require users to be staff members (or editors, if you'd prefer). """ if is_editor(request.user) or not editor_required: return handle_form_and_email(request, form=form, form_template=form_template, message_template=message_template, subject=subject, recipients=recipients, redirect_to=redirect_to, uses_captcha=uses_captcha) else: # Make the user log in first. redirect_to_login(next=request.META['PATH_INFO'])
def __call__(self, request): # add school_year property to request type(request).school_year = school_year() # add leprikon leader to request try: request.leader = request.user.leprikon_leader except (AttributeError, Leader.DoesNotExist): request.leader = None # add leprikon site to request request.leprikon_site = LeprikonSite.objects.get_current() # add leprikon version to request request.leprikon_version = __version__ # check user agreement if ( request.leprikon_site.user_agreement_changed and request.user.is_authenticated() and not request.session.get('user_agreement_ok') ): if UserAgreement.objects.filter( user=request.user, granted__gt=request.leprikon_site.user_agreement_changed, ).exists(): request.session['user_agreement_ok'] = 1 elif request.path != self.user_agreement_url: return redirect_to_login( request.path, login_url=self.user_agreement_url, redirect_field_name=settings.LEPRIKON_PARAM_BACK, ) # check user email if request.user.is_authenticated() and not request.user.email: if request.path not in ( self.user_email_url, self.user_login_url, self.user_logout_url, ): return redirect_to_login( request.path, login_url=self.user_email_url, redirect_field_name=settings.LEPRIKON_PARAM_BACK, ) # set session expiry if request.user.is_authenticated(): if request.user.is_staff: request.session.set_expiry(settings.SESSION_STAFF_COOKIE_AGE) else: request.session.set_expiry(settings.SESSION_COOKIE_AGE) return self.get_response(request)
def _wrapped(request, *args, **kwargs): from django.contrib.auth.views import redirect_to_login if not request.user.is_authenticated(): return redirect_to_login(next=request.path) phone = request.session.get('user_phone') or user_phone(request.user) if not phone: redirect_to = add_phone_url or reverse('add_phone') or settings.ADD_PHONE_URL return redirect_to_login(request.path, redirect_to, 'next') request.session['user_phone'] = phone return function(request, *args, **kwargs)
def check_perms(request, *args, **kwargs): user = request.user path = request.build_absolute_uri() if is_teacher(user): return view_func(request, *args, **kwargs) elif user.is_authenticated(): messages.error(request, '你不是老师用户,无权访问。请用老师账号登录。') return redirect_to_login(path) else: #messages.info(request, '') return redirect_to_login(path)
def check_perms(request, *args, **kwargs): user = request.user path = request.build_absolute_uri() if user.has_perm('kinger.can_manage_school'): return view_func(request, *args, **kwargs) elif user.is_authenticated(): messages.error(request, '你不是学校管理员,无权访问。请用学校管理员帐号登录。') return redirect_to_login(path) else: messages.info(request, '访问学校管理后台,请用学校管理员账号登录') return redirect_to_login(path)
def check_perms(request, *args, **kwargs): user = request.user path = request.build_absolute_uri() code_list = [c.code for c in helpers.user_access_list(user)] if "school_teacher" in code_list: return view_func(request, *args, **kwargs) elif user.is_authenticated(): messages.error(request, "您的权限不足无法访问。") return redirect_to_login(path) else: return redirect_to_login(path)
def check_perms(request, *args, **kwargs): user = request.user path = request.build_absolute_uri() if user.has_perm('aq.can_answer_parent'): return view_func(request, *args, **kwargs) elif user.is_authenticated(): messages.error(request, '你不是运营人员,无权访问专家问答。请用运营人员帐号登录。') return redirect_to_login(path) else: messages.info(request, '访问专家问答,请用运营人员帐号登录') return redirect_to_login(path)
def check_perms(request, *args, **kwargs): user = request.user path = request.build_absolute_uri() if user.has_perm('waiter.can_answer_customer'): return view_func(request, *args, **kwargs) elif user.is_authenticated(): messages.error(request, '你不是客服人员,无权访问客服后台。请用客服人员账号登录。') return redirect_to_login(path) else: messages.info(request, '访问客服后台,请用客服人员账号登录') return redirect_to_login(path)
def showpage(request, url): """ Flat page wiki view. template hardcoded for now """ if not url.startswith('/'): url = "/" + url if not url.endswith('/'): url = url + "/" wikipath = url.split('/')[1] if not wikipath in settings.FLATPAGEWIKI_PATHS: raise Http404 try: f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) except Http404: return newpage(request, url) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): return redirect_to_login(request.path) if f.template_name: t = 'wiki/%s' % f.template_name else: t = DEFAULT_TEMPLATE edit = '0' if request.method == 'POST': if not request.user.has_perm('flatpages.change_flatpage'): raise Http404 if request.POST['result'] == 'Cancel': return HttpResponseRedirect(f.url) else: if not request.user.is_authenticated(): return redirect_to_login(request.path) form = WikiPageForm(request.POST) if form.is_valid(): f.title = form.cleaned_data['title'] f.content = (form.cleaned_data['content']) if settings.EMAIL_FLATPAGE_SAVES: fp_change(request, f) f.save() return HttpResponseRedirect(f.url) else: if request.user.has_perm('flatpages.change_flatpage'): edit = request.GET.get('edit', '0') form = WikiPageForm({'url': f.url, 'title': f.title, 'content': f.content }) response = render_to_response(t, RequestContext( request, { 'form': form, 'object': f, 'edit': edit }) ) populate_xheaders(request, response, FlatPage, f.id) return response
def new_f(request): path = request.get_full_path() try: if request.user.is_authenticated(): return fun(request) else: if request.session['fbid'] : return fun(request) else: return redirect_to_login(path, '/accounts/login/') except KeyError: return redirect_to_login(path, '/accounts/login/')
def dispatch(self, request, *args, **kwargs): if not hasattr(request.user,'type'): return redirect_to_login(request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) if not request.user.is_staff and not (request.user.type == 'AD'): if self.raise_exception: raise PermissionDenied else: return redirect_to_login(request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) return super(AuthorizationRequiredMixin, self).dispatch( request, *args, **kwargs)
def render_workspace_view(request, owner, name): if ALLOW_ANONYMOUS_ACCESS is False and request.user.is_authenticated() is False: return redirect_to_login(request.get_full_path()) get_workspace_list(request.user) workspace = get_object_or_404(Workspace, creator__username=owner, name=name) if not workspace.public and request.user not in workspace.users.all(): if request.user.is_authenticated(): return build_error_response(request, 403, 'forbidden') else: return redirect_to_login(request.get_full_path()) return render_wirecloud(request)
def render_fatpage(request, f): """ Internal interface to the fat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in fatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'fatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FatPage, f.id) return response
def cas_login(request): ticket_request = TicketRequest() ticket_request.renewed = 'renew' in request.GET ticket_request.url = request.GET.get('service') if ticket_request.url: try: policy = ServicePolicy.objects.get_by_url(ticket_request.url) ticket_request.policy = policy if (not request.user.is_authenticated() or 'renew' in request.GET or not policy.allow_single_login): if 'gateway' in request.GET: return redirect(ticket_request.url) else: ticket_request.save() target = reverse('cas_issue', kwargs={'ticket_request_uuid': ticket_request.id}) return redirect_to_login(target) else: ticket_request.user = request.user ticket_request.session_id = request.session.session_key ticket_request.save() target = reverse('cas_issue', kwargs={'ticket_request_uuid': ticket_request.id}) return redirect(target) except ServicePolicy.DoesNotExist: return TemplateResponse(request, 'webapp/unknown.html') else: return redirect('index')
def process_exception(self, request, exception): """Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated)): auth_url = settings.LOGIN_URL next_url = iri_to_uri(request.get_full_path()) if next_url != auth_url: field_name = REDIRECT_FIELD_NAME else: field_name = None login_url = request.build_absolute_uri(auth_url) response = redirect_to_login(next_url, login_url=login_url, redirect_field_name=field_name) if request.is_ajax(): response_401 = http.HttpResponse(status=401) response_401['X-Horizon-Location'] = response['location'] return response_401 return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance(exception, exceptions.NotFound): raise http.Http404(exception) if isinstance(exception, exceptions.Http302): # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts.redirect(exception.location)
def wrapped_view(request, *args, **kwargs): if request.user.is_authenticated: return view(request, *args, **kwargs) now = datetime.datetime.now() if 'AUTO_LOGIN_ATTEMPT' in request.session: auto_login_attempt = datetime.datetime.strptime( request.session['AUTO_LOGIN_ATTEMPT'], ISO_8601_format) if auto_login_attempt >= (now - RETRY_AFTER): return view(request, *args, **kwargs) # datetime needs to be JSON serializable: request.session['AUTO_LOGIN_ATTEMPT'] = now.isoformat() path = request.build_absolute_uri() attempt_only_login_url = ( force_str(settings.LOGIN_URL) + '?attempt_login_only=true') login_scheme, login_netloc = urlparse(attempt_only_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme # noqa: W503 or login_scheme == current_scheme) and # noqa: W504, W503 (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() # the 'next' param is set with this redirect: return redirect_to_login(path, attempt_only_login_url)
def view(request, nidb64): try: node = Node(nidb64, user=request.user) except ObjectDoesNotExist: from django.http import Http404 raise Http404 if request.method == 'POST': return post(request, node) elif request.method == 'PUT': return put(request, node) elif request.method == 'DELETE': return delete(request, node) elif request.method != 'GET': return not_allowed(request, ['GET', 'POST', 'PUT', 'DELETE']) if not node.can_view(): if not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) else: raise PermissionDenied if request.is_ajax(): return get(request, node) else: params = { 'node': node } if node.is_folder(): return render(request, 'docs/folder.html', params) else: return render(request, 'docs/file.html', params)
def edit(request, title): if not allow_anonymous_edits() and not request.user.is_authenticated(): return redirect_to_login(request.get_full_path()) url_title = utils.urlize_title(title) if title != url_title: return HttpResponseRedirect(reverse('djiki-page-edit', kwargs={'title': url_title})) page_title = utils.deurlize_title(title) try: page = models.Page.objects.get(title=page_title) last_content = page.last_revision().content except models.Page.DoesNotExist: page = models.Page(title=page_title) last_content = '' revision = models.PageRevision(page=page, author=request.user if request.user.is_authenticated() else None) form = forms.PageEditForm( data=request.POST or None, instance=revision, page=page, initial={'content': last_content}) preview_content = None if request.method == 'POST': is_preview = request.POST.get('action') == 'preview' if form.is_valid(): if is_preview: preview_content = form.cleaned_data.get('content', form.data['content']) messages.info(request, mark_safe(_("The content you see on this page is shown only as " "a preview. <strong>No changes have been saved yet.</strong> Please " "review the modifications and use the <em>Save</em> button to store " "them permanently."))) else: form.save() return HttpResponseRedirect( reverse('djiki-page-view', kwargs={'title': url_title})) return direct_to_template(request, 'djiki/edit.html', {'form': form, 'page': page, 'preview_content': preview_content})
def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): self.user = request.user else: if defaults.PYBB_ENABLE_ANONYMOUS_POST: self.user, new = User.objects.get_or_create(**{username_field: defaults.PYBB_ANONYMOUS_USERNAME}) else: from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.get_full_path()) self.forum = None self.topic = None if 'forum_id' in kwargs: self.forum = get_object_or_404(perms.filter_forums(request.user, Forum.objects.all()), pk=kwargs['forum_id']) if not perms.may_create_topic(self.user, self.forum): raise PermissionDenied elif 'topic_id' in kwargs: self.topic = get_object_or_404(perms.filter_topics(request.user, Topic.objects.all()), pk=kwargs['topic_id']) if not perms.may_create_post(self.user, self.topic): raise PermissionDenied self.quote = '' if 'quote_id' in request.GET: try: quote_id = int(request.GET.get('quote_id')) except TypeError: raise Http404 else: post = get_object_or_404(Post, pk=quote_id) self.quote = defaults.PYBB_QUOTE_ENGINES[defaults.PYBB_MARKUP](post.body, getattr(post.user, username_field)) if self.quote and request.is_ajax(): return HttpResponse(self.quote) return super(AddPostView, self).dispatch(request, *args, **kwargs)
def attachment_download(request, pk): """ Allow user to download the given attachment. :param request: The current request. :param pk: The desired attachment pk. :return: StreamingHttpResponse """ # Get the attachment object attachment_obj = get_object_or_404(FileAttachment, pk=pk) # Check access rights if not attachment_obj.parent_post.has_access(request.user): raise PermissionDenied() # Check authentication if FILE_ATTACHMENTS_DOWNLOAD_REQUIRE_LOGIN and not request.user.is_authenticated(): return redirect_to_login(attachment_obj.get_absolute_url()) # Stream the file content securely mimetype = attachment_obj.content_type response = StreamingHttpResponse(FileWrapper(attachment_obj.file.open()), content_type=mimetype) response['Content-Length'] = attachment_obj.size if mimetype not in FILE_ATTACHMENTS_WHITELIST_FOR_INLINE_DISPLAY: response['Content-Disposition'] = "attachment; filename=%s" % attachment_obj.filename response['X-Content-Type-Options'] = 'nosniff' # TODO Use serve() if DEBUG=True and http://wiki.nginx.org/X-accel#X-Accel-Redirect on production # Maybe add support by settings for https://tn123.org/mod_xsendfile/ (Apache version of X-Accel-Redirect) return response
def revert(request, title, revision_pk): if not allow_anonymous_edits() and not request.user.is_authenticated(): return redirect_to_login(request.get_full_path()) url_title = utils.urlize_title(title) if title != url_title: return HttpResponseRedirect( reverse('djiki-page-revert', kwargs={'title': url_title, 'revision_pk': revision_pk})) page_title = utils.deurlize_title(title) page = get_object_or_404(models.Page, title=page_title) src_revision = get_object_or_404(models.PageRevision, page=page, pk=revision_pk) new_revision = models.PageRevision(page=page, author=request.user if request.user.is_authenticated() else None) if request.method == 'POST': form = forms.PageEditForm(data=request.POST or None, instance=new_revision, page=page) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('djiki-page-view', kwargs={'title': url_title})) else: if src_revision.author: description = _("Reverted to revision of %(time)s by %(user)s.") % \ {'time': src_revision.created, 'user': src_revision.user.username} else: description = _("Reverted to anonymous revision of %(time)s.") % \ {'time': src_revision.created} form = forms.PageEditForm(data=request.POST or None, instance=new_revision, page=page, initial={'content': src_revision.content, 'description': description}) return direct_to_template(request, 'djiki/edit.html', {'page': page, 'form': form, 'src_revision': src_revision})
def view(request, title, revision_pk=None): if not user_or_site(request): return redirect_to_login(request.get_full_path()) url_title = utils.urlize_title(title) if title != url_title: if revision_pk: return HttpResponseRedirect(reverse('djiki-page-revision', kwargs={'title': url_title, 'revision_pk': revision_pk})) return HttpResponseRedirect(reverse('djiki-page-view', kwargs={'title': url_title})) page_title = utils.deurlize_title(title) try: page = models.Page.objects.get(title=page_title) except models.Page.DoesNotExist: t = loader.get_template('djiki/not_found.html') c = RequestContext(request, {'title': page_title}) return HttpResponseNotFound(t.render(c)) if revision_pk: try: revision = page.revisions.get(pk=revision_pk) except models.PageRevision.DoesNotExist: return HttpResponseNotFound() messages.info(request, mark_safe(_("The version you are viewing is not the latest one, " "but represents an older revision of this page, which may have been " "significantly modified. If it is not what you intended to view, " "<a href=\"%(url)s\">proceed to the latest version</a>.") % { 'url': reverse('djiki-page-view', kwargs={'title': url_title})})) else: revision = page.last_revision() if request.REQUEST.get('raw', ''): response = HttpResponse(mimetype='text/plain') response['Content-Disposition'] = 'attachment; filename=%s.txt' % quote(title.encode('utf-8')) response.write(revision.content) return response return direct_to_template(request, 'djiki/view.html', {'page': page, 'revision': revision})
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated(): if not self.community.is_public: return redirect_to_login(request.build_absolute_uri()) if hasattr(self, 'get_required_permission'): perm = self.get_required_permission() else: perm = self.required_permission or "communities.access_community" if not has_community_perm(request.user, self.community, perm): if settings.DEBUG: return HttpResponseForbidden("403 %s" % perm) return HttpResponseForbidden("403 Unauthorized") if request.method == "POST": if hasattr(self, 'get_required_permission_for_post'): perm = self.get_required_permission_for_post() else: perm = self.required_permission_for_post or "communities.access_community" if not has_community_perm(request.user, self.community, perm): if settings.DEBUG: return HttpResponseForbidden("403 POST %s" % perm) return HttpResponseForbidden("403 Unauthorized") resp = super(ProtectedMixin, self).dispatch(request, *args, **kwargs) # Disable client side cache resp['Expires'] = '0' resp['Pragma'] = 'no-cache' resp['Cache-Control'] = 'no-cache, no-store, must-revalidate' return resp
def flatpage(request, url): """ Extended editable flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not request.GET.get('action') in ('create', 'edit', 'delete'): return flatpage_detail(request, url) if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_none(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) if not f: if not request.user.has_perm('flatpages.add_flatpage'): raise Http404 f = FlatPage(url=url) # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f and f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if request.method == 'POST': form = FlatPageEditForm(request.POST, instance=f) if form.is_valid(): # All validation rules pass f.save() current_site = Site.objects.get_current() if not current_site in f.sites.all(): # Assign page to current site f.sites.add(current_site) f.save() msg = _("The %(verbose_name)s was updated successfully.") %\ {"verbose_name": FlatPage._meta.verbose_name} messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(f.url) else: if request.GET.get('action') == 'delete': f.delete() msg = _("The %(verbose_name)s was deleted.") %\ {"verbose_name": FlatPage._meta.verbose_name} messages.success(request, msg, fail_silently=True) return HttpResponseRedirect('/') form = FlatPageEditForm(instance=f) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) c = RequestContext(request, { 'form': form, 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
def vote_on_object(request, model, direction, post_vote_redirect=None, object_id=None, slug=None, slug_field=None, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', allow_xmlhttprequest=False): """ Generic object vote function. The given template will be used to confirm the vote if this view is fetched using GET; vote registration will only be performed if this view is POSTed. If ``allow_xmlhttprequest`` is ``True`` and an XMLHttpRequest is detected by examining the ``HTTP_X_REQUESTED_WITH`` header, the ``xmlhttp_vote_on_object`` view will be used to process the request - this makes it trivial to implement voting via XMLHttpRequest with a fallback for users who don't have JavaScript enabled. Templates:``<app_label>/<model_name>_confirm_vote.html`` Context: object The object being voted on. direction The type of vote which will be registered for the object. """ if allow_xmlhttprequest and request.is_ajax(): return xmlhttprequest_vote_on_object(request, model, direction, object_id=object_id, slug=slug, slug_field=slug_field) if extra_context is None: extra_context = {} if not request.user.is_authenticated(): return redirect_to_login(request.path) try: vote = dict(VOTE_DIRECTIONS)[direction] except KeyError: raise AttributeError("'%s' is not a valid vote type." % direction) # Look up the object to be voted on lookup_kwargs = {} if object_id: lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise AttributeError('Generic vote view must be called with either ' 'object_id or slug and slug_field.') try: obj = model._default_manager.get(**lookup_kwargs) except ObjectDoesNotExist: raise Http404('No %s found for %s.' % (model._meta.app_label, lookup_kwargs)) if request.method == 'POST': if post_vote_redirect is not None: next = post_vote_redirect elif 'next' in request.REQUEST: next = request.REQUEST['next'] elif hasattr(obj, 'get_absolute_url'): if callable(getattr(obj, 'get_absolute_url')): next = obj.get_absolute_url() else: next = obj.get_absolute_url else: raise AttributeError( 'Generic vote view must be called with either ' 'post_vote_redirect, a "next" parameter in ' 'the request, or the object being voted on ' 'must define a get_absolute_url method or ' 'property.') Vote.objects.record_vote(obj, request.user, vote) return HttpResponseRedirect(next) else: if not template_name: template_name = '%s/%s_confirm_vote.html' % ( model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, 'direction': direction, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c)) return response
def __call__(self, request, *args, **kwargs): if not request.user.is_authenticated(): return redirect_to_login(request.get_full_path()) return self.child(request, *args, **kwargs)
def get(self, request, course_id, chapter=None, section=None, position=None): """ Displays courseware accordion and associated content. If course, chapter, and section are all specified, renders the page, or returns an error if they are invalid. If section is not specified, displays the accordion opened to the right chapter. If neither chapter or section are specified, displays the user's most recent chapter, or the first chapter if this is the user's first visit. Arguments: request: HTTP request course_id (unicode): course id chapter (unicode): chapter url_name section (unicode): section url_name position (unicode): position in module, eg of <sequential> module """ self.course_key = CourseKey.from_string(course_id) if not (request.user.is_authenticated or self.enable_unenrolled_access): return redirect_to_login(request.get_full_path()) self.original_chapter_url_name = chapter self.original_section_url_name = section self.chapter_url_name = chapter self.section_url_name = section self.position = position self.chapter, self.section = None, None self.course = None self.url = request.path try: set_custom_attributes_for_course_key(self.course_key) self._clean_position() with modulestore().bulk_operations(self.course_key): self.view = STUDENT_VIEW self.course = get_course_with_access( request.user, 'load', self.course_key, depth=CONTENT_DEPTH, check_if_enrolled=True, check_if_authenticated=True) self.course_overview = CourseOverview.get_from_id( self.course.id) self.is_staff = has_access(request.user, 'staff', self.course) # There's only one situation where we want to show the public view if (not self.is_staff and self.enable_unenrolled_access and self.course.course_visibility == COURSE_VISIBILITY_PUBLIC and not CourseEnrollment.is_enrolled( request.user, self.course_key)): self.view = PUBLIC_VIEW self.can_masquerade = request.user.has_perm( MASQUERADE_AS_STUDENT, self.course) self._setup_masquerade_for_effective_user() return self.render(request) except Exception as exception: # pylint: disable=broad-except return CourseTabView.handle_exceptions(request, self.course_key, self.course, exception)
def get(self, request, course_id, chapter=None, section=None, position=None): """ Displays courseware accordion and associated content. If course, chapter, and section are all specified, renders the page, or returns an error if they are invalid. If section is not specified, displays the accordion opened to the right chapter. If neither chapter or section are specified, displays the user's most recent chapter, or the first chapter if this is the user's first visit. Arguments: request: HTTP request course_id (unicode): course id chapter (unicode): chapter url_name section (unicode): section url_name position (unicode): position in module, eg of <sequential> module """ self.course_key = CourseKey.from_string(course_id) if not (request.user.is_authenticated or self.enable_unenrolled_access): return redirect_to_login(request.get_full_path()) self.original_chapter_url_name = chapter self.original_section_url_name = section self.chapter_url_name = chapter self.section_url_name = section self.position = position self.chapter, self.section = None, None self.course = None self.url = request.path try: set_custom_metrics_for_course_key(self.course_key) self._clean_position() with modulestore().bulk_operations(self.course_key): self.view = STUDENT_VIEW # Do the enrollment check if enable_unenrolled_access is not enabled. self.course = get_course_with_access( request.user, 'load', self.course_key, depth=CONTENT_DEPTH, check_if_enrolled=not self.enable_unenrolled_access, ) if self.enable_unenrolled_access: # Check if the user is considered enrolled (i.e. is an enrolled learner or staff). try: check_course_access( self.course, request.user, 'load', check_if_enrolled=True, ) except CourseAccessRedirect as exception: # If the user is not considered enrolled: if self.course.course_visibility == COURSE_VISIBILITY_PUBLIC: # If course visibility is public show the XBlock public_view. self.view = PUBLIC_VIEW else: # Otherwise deny them access. raise exception else: # If the user is considered enrolled show the default XBlock student_view. pass self.is_staff = has_access(request.user, 'staff', self.course) self._setup_masquerade_for_effective_user() return self.render(request) except Exception as exception: # pylint: disable=broad-except return CourseTabView.handle_exceptions(request, self.course_key, self.course, exception)
def wrapped(request, *args, **kwargs): if request.user.is_anonymous(): path = request.build_absolute_uri() return redirect_to_login(path, reverse_lazy('login')) else: return view_func(request, *args, **kwargs)
def details(request, slug): """ The main view of the Django-CMS! Takes a request and a slug, renders the page. """ from django.core.cache import cache if get_cms_setting("PAGE_CACHE") and ( not hasattr(request, 'toolbar') or (not request.toolbar.edit_mode and not request.toolbar.show_toolbar and not request.user.is_authenticated())): cache_content = cache.get(_get_cache_key(request), version=_get_cache_version()) if not cache_content is None: content, headers = cache_content response = HttpResponse(content) response._headers = headers return response # Get a Page model object from the request page = get_page_from_request(request, use_path=slug) if not page: return _handle_no_page(request, slug) current_language = request.REQUEST.get('language', None) if current_language: current_language = get_language_code(current_language) if not current_language in get_language_list(page.site_id): current_language = None if current_language is None: current_language = get_language_code( getattr(request, 'LANGUAGE_CODE', None)) if current_language: current_language = get_language_code(current_language) if not current_language in get_language_list(page.site_id): current_language = None if current_language is None: current_language = get_language_code(get_language()) # Check that the current page is available in the desired (current) language available_languages = [] page_languages = list(page.get_languages()) if hasattr(request, 'user') and request.user.is_staff: user_languages = get_language_list() else: user_languages = get_public_languages() for frontend_lang in user_languages: if frontend_lang in page_languages: available_languages.append(frontend_lang) # Check that the language is in FRONTEND_LANGUAGES: own_urls = [ 'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path), '/%s' % request.path, request.path, ] if not current_language in user_languages: #are we on root? if not slug: #redirect to supported language languages = [] for language in available_languages: languages.append((language, language)) if languages: # get supported language new_language = get_language_from_request(request, page) if new_language in get_public_languages(): with force_language(new_language): pages_root = reverse('pages-root') if hasattr( request, 'toolbar' ) and request.user.is_staff and request.toolbar.edit_mode: request.toolbar.redirect_url = pages_root elif pages_root not in own_urls: return HttpResponseRedirect(pages_root) elif not hasattr(request, 'toolbar') or not request.toolbar.redirect_url: _handle_no_page(request, slug) else: return _handle_no_page(request, slug) if current_language not in available_languages: # If we didn't find the required page in the requested (current) # language, let's try to find a fallback found = False for alt_lang in get_fallback_languages(current_language): if alt_lang in available_languages: if get_redirect_on_fallback(current_language) or slug == "": with force_language(alt_lang): path = page.get_absolute_url(language=alt_lang, fallback=True) # In the case where the page is not available in the # preferred language, *redirect* to the fallback page. This # is a design decision (instead of rendering in place)). if hasattr( request, 'toolbar' ) and request.user.is_staff and request.toolbar.edit_mode: request.toolbar.redirect_url = path elif path not in own_urls: return HttpResponseRedirect(path) else: found = True if not found and (not hasattr(request, 'toolbar') or not request.toolbar.redirect_url): # There is a page object we can't find a proper language to render it _handle_no_page(request, slug) if apphook_pool.get_apphooks(): # There are apphooks in the pool. Let's see if there is one for the # current page # since we always have a page at this point, applications_page_check is # pointless # page = applications_page_check(request, page, slug) # Check for apphooks! This time for real! app_urls = page.get_application_urls(current_language, False) skip_app = False if not page.is_published(current_language) and hasattr( request, 'toolbar') and request.toolbar.edit_mode: skip_app = True if app_urls and not skip_app: app = apphook_pool.get_apphook(app_urls) pattern_list = [] for urlpatterns in get_app_urls(app.urls): pattern_list += urlpatterns try: view, args, kwargs = resolve('/', tuple(pattern_list)) return view(request, *args, **kwargs) except Resolver404: pass # Check if the page has a redirect url defined for this language. redirect_url = page.get_redirect(language=current_language) if redirect_url: if (is_language_prefix_patterns_used() and redirect_url[0] == "/" and not redirect_url.startswith('/%s/' % current_language)): # add language prefix to url redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/")) # prevent redirect to self if hasattr(request, 'toolbar' ) and request.user.is_staff and request.toolbar.edit_mode: request.toolbar.redirect_url = redirect_url elif redirect_url not in own_urls: return HttpResponseRedirect(redirect_url) # permission checks if page.login_required and not request.user.is_authenticated(): return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL) if hasattr(request, 'toolbar'): request.toolbar.set_object(page) template_name = get_template_from_request(request, page, no_current_page=True) # fill the context context = RequestContext(request) context['lang'] = current_language context['current_page'] = page context['has_change_permissions'] = page.has_change_permission(request) context['has_view_permissions'] = page.has_view_permission(request) if not context['has_view_permissions']: return _handle_no_page(request, slug) response = TemplateResponse(request, template_name, context) response.add_post_render_callback(_cache_page) # Add headers for X Frame Options - this really should be changed upon moving to class based views xframe_options = page.get_xframe_options() if xframe_options == Page.X_FRAME_OPTIONS_INHERIT: # This is when we defer to django's own clickjacking handling return response # We want to prevent django setting this in their middlewear response.xframe_options_exempt = True if xframe_options == Page.X_FRAME_OPTIONS_ALLOW: # Do nothing, allowed is no header. return response elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN: response['X-Frame-Options'] = 'SAMEORIGIN' elif xframe_options == Page.X_FRAME_OPTIONS_DENY: response['X-Frame-Options'] = 'DENY' return response
def coding_problem(request, slug): problem = CodingProblem.objects.get(slug=slug) user = request.user if request.method == 'POST': if not user.is_authenticated: path = request.build_absolute_uri() resolved_login_url = resolve_url(settings.LOGIN_URL) login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login(path, resolved_login_url, REDIRECT_FIELD_NAME) submission = CodeSubmission(problem=problem, user=user) submission_form = CodeSubmissionForm(request.POST, instance=submission) if submission_form.is_valid(): submission_form.save() # send task judge_code_submission.delay(submission.id) # keep only the top 10 submissions for n, s in enumerate( CodeSubmission.objects.filter( user=user, problem=problem).order_by( "submission_time").reverse()): if n >= 10: s.delete() messages.success(request, _('Your code was successfully submitted')) return redirect('coding-problem-detail', slug) else: messages.success(request, _('Your code was successfully submitted')) messages.error(request, _('Please correct the error below.')) else: submission_form = CodeSubmissionForm() if user.is_authenticated: submissions = problem.user_submissions(user) try: latest_submission = submissions.earliest() submission_form.initial[ "language"] = latest_submission.language submission_form.initial["code"] = latest_submission.code except CodeSubmission.DoesNotExist: pass else: submissions = [] return render( request, 'candidates/codingproblem_detail.html', { 'problem': problem, 'submission_form': submission_form, 'examples': problem.examples, 'submissions': submissions })
def details(request, slug): """ The main view of the Django-CMS! Takes a request and a slug, renders the page. """ response_timestamp = now() if get_cms_setting("PAGE_CACHE") and ( not hasattr(request, 'toolbar') or (not request.toolbar.edit_mode_active and not request.toolbar.show_toolbar and not request.user.is_authenticated)): cache_content = get_page_cache(request) if cache_content is not None: content, headers, expires_datetime = cache_content response = HttpResponse(content) response.xframe_options_exempt = True if DJANGO_2_2 or DJANGO_3_0 or DJANGO_3_1: response._headers = headers else: response.headers = headers # Recalculate the max-age header for this cached response max_age = int((expires_datetime - response_timestamp).total_seconds() + 0.5) patch_cache_control(response, max_age=max_age) return response # Get a Page model object from the request site = get_current_site() page = get_page_from_request(request, use_path=slug) toolbar = get_toolbar_from_request(request) tree_nodes = TreeNode.objects.get_for_site(site) if not page and not slug and not tree_nodes.exists(): # render the welcome page if the requested path is root "/" # and there's no pages return _render_welcome_page(request) if not page: # raise 404 _handle_no_page(request) request.current_page = page if hasattr(request, 'user') and request.user.is_staff: user_languages = get_language_list(site_id=site.pk) else: user_languages = get_public_languages(site_id=site.pk) request_language = get_language_from_request(request, check_path=True) if not page.is_home and request_language not in user_languages: # The homepage is treated differently because # when a request goes to the root of the site (/) # without a language, Django will redirect to the user's # browser language which might not be a valid cms language, # this means we need to correctly redirect that request. return _handle_no_page(request) # get_published_languages will return all languages in draft mode # and published only in live mode. # These languages are then filtered out by the user allowed languages available_languages = [ language for language in user_languages if language in list(page.get_published_languages()) ] own_urls = [ request.build_absolute_uri(request.path), '/%s' % request.path, request.path, ] try: redirect_on_fallback = get_redirect_on_fallback(request_language, site_id=site.pk) except LanguageError: redirect_on_fallback = False if request_language not in user_languages: # Language is not allowed # Use the default site language default_language = get_default_language_for_site(site.pk) fallbacks = get_fallback_languages(default_language, site_id=site.pk) fallbacks = [default_language] + fallbacks else: fallbacks = get_fallback_languages(request_language, site_id=site.pk) # Only fallback to languages the user is allowed to see fallback_languages = [ language for language in fallbacks if language != request_language and language in available_languages ] language_is_unavailable = request_language not in available_languages if language_is_unavailable and not fallback_languages: # There is no page with the requested language # and there's no configured fallbacks return _handle_no_page(request) elif language_is_unavailable and (redirect_on_fallback or page.is_home): # There is no page with the requested language and # the user has explicitly requested to redirect on fallbacks, # so redirect to the first configured / available fallback language fallback = fallback_languages[0] redirect_url = page.get_absolute_url(fallback, fallback=False) else: page_path = page.get_absolute_url(request_language) page_slug = page.get_path(request_language) or page.get_slug( request_language) if slug and slug != page_slug and request.path[:len(page_path )] != page_path: # The current language does not match its slug. # Redirect to the current language. return HttpResponseRedirect(page_path) # Check if the page has a redirect url defined for this language. redirect_url = page.get_redirect(request_language, fallback=False) or '' redirect_url = _clean_redirect_url(redirect_url, request_language) if redirect_url: if request.user.is_staff and toolbar.edit_mode_active: toolbar.redirect_url = redirect_url elif redirect_url not in own_urls: # prevent redirect to self return HttpResponseRedirect(redirect_url) # permission checks if page.login_required and not request.user.is_authenticated: return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL) if hasattr(request, 'toolbar'): request.toolbar.set_object(page) structure_requested = get_cms_setting( 'CMS_TOOLBAR_URL__BUILD') in request.GET if user_can_change_page(request.user, page) and structure_requested: return render_object_structure(request, page) return render_page(request, page, current_language=request_language, slug=slug)
def handle_no_permission(self): return auth_views.redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
def handle_no_authenticated(self): if self.request.is_ajax(): return JsonResponse({'error': 'Not Authorized'}, status=401) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
def single_linky(request, guid): """ Given a Perma ID, serve it up. """ # Create a canonical version of guid (non-alphanumerics removed, hyphens every 4 characters, uppercase), # and forward to that if it's different from current guid. canonical_guid = Link.get_canonical_guid(guid) # We only do the redirect if the correctly-formatted GUID actually exists -- # this prevents actual 404s from redirecting with weird formatting. link = get_object_or_404(Link.objects.all_with_deleted(), guid=canonical_guid) if canonical_guid != guid: return HttpResponsePermanentRedirect( reverse('single_linky', args=[canonical_guid])) # Forward to replacement link if replacement_link is set. if link.replacement_link_id: return HttpResponseRedirect( reverse('single_linky', args=[link.replacement_link_id])) # If we get an unrecognized archive type (which could be an old type like 'live' or 'pdf'), forward to default version serve_type = request.GET.get('type') if serve_type is None: serve_type = 'source' elif serve_type not in valid_serve_types: return HttpResponsePermanentRedirect( reverse('single_linky', args=[canonical_guid])) # serve raw WARC if serve_type == 'warc_download': if request.user.can_view(link): response = StreamingHttpResponse(FileWrapper( default_storage.open(link.warc_storage_file()), 1024 * 8), content_type="application/gzip") response[ 'Content-Disposition'] = "attachment; filename=%s.warc.gz" % link.guid return response else: return HttpResponseForbidden('Private archive.') # Special handling for private links on Safari: # Safari won't let us set the auth cookie for the WARC_HOST domain inside the iframe, unless we've already set a # cookie on that domain outside the iframe. So do a redirect to WARC_HOST to set a cookie and then come back. # safari=1 in the query string indicates that the redirect has already happened. # See http://labs.fundbox.com/third-party-cookies-with-ie-at-2am/ if link.is_private and not request.GET.get('safari'): user_agent = user_agent_parser.ParseUserAgent( request.META.get('HTTP_USER_AGENT', '')) if user_agent.get('family') == 'Safari': return redirect_to_login( request.build_absolute_uri(), "//%s%s" % (settings.WARC_HOST, reverse('user_management_set_safari_cookie'))) # handle requested capture type if serve_type == 'image': capture = link.screenshot_capture else: capture = link.primary_capture # if primary capture did not work, but screenshot did work, forward to screenshot if ( not capture or capture.status != 'success' ) and link.screenshot_capture and link.screenshot_capture.status == 'success': return HttpResponseRedirect( reverse('single_linky', args=[guid]) + "?type=image") # If this record was just created by the current user, show them a new record message new_record = request.user.is_authenticated() and link.created_by_id == request.user.id and not link.user_deleted \ and link.creation_timestamp > timezone.now() - timedelta(seconds=300) # Provide the max upload size, in case the upload form is used max_size = settings.MAX_ARCHIVE_FILE_SIZE / 1024 / 1024 protocol = "https://" if settings.SECURE_SSL_REDIRECT else "http://" if not link.submitted_description: link.submitted_description = "This is an archive of %s from %s" % ( link.submitted_url, link.creation_timestamp.strftime("%A %d, %B %Y")) context = { 'link': link, 'can_view': request.user.can_view(link), 'can_edit': request.user.can_edit(link), 'can_delete': request.user.can_delete(link), 'can_toggle_private': request.user.can_toggle_private(link), 'capture': capture, 'serve_type': serve_type, 'new_record': new_record, 'this_page': 'single_link', 'max_size': max_size, 'link_url': settings.HOST + '/' + link.guid, 'protocol': protocol, } response = render(request, 'archive/single-link.html', context) date_header = format_date_time(mktime(link.creation_timestamp.timetuple())) link_memento = protocol + settings.HOST + '/' + link.guid link_timegate = protocol + settings.WARC_HOST + settings.TIMEGATE_WARC_ROUTE + '/' + link.safe_url link_timemap = protocol + settings.WARC_HOST + settings.WARC_ROUTE + '/timemap/*/' + link.safe_url response['Memento-Datetime'] = date_header link_memento_headers = '<{0}>; rel="original"; datetime="{1}",<{2}>; rel="memento"; datetime="{1}",<{3}>; rel="timegate",<{4}>; rel="timemap"; type="application/link-format"' response['Link'] = link_memento_headers.format(link.safe_url, date_header, link_memento, link_timegate, link_timemap) return response
def redirect_for_login_or_domain(request, login_url=None): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.get_full_path(), login_url)
except ProtocolError, why: # This means the incoming request was invalid. return direct_to_template(request, 'provider/endpoint.html', {'error': str(why)}) # If we did not get a request, display text indicating that this # is an endpoint. if openid_request is None: return direct_to_template(request, 'provider/endpoint.html', {}) # We got a request; if the mode is checkid_*, we will handle it by # getting feedback from the user or by checking the session. if openid_request.mode in ["checkid_immediate", "checkid_setup"]: if not request.user or request.user.is_authenticated() == False: #TODO: verificar porque o openid_request.encodeToURL() remove os parâmetros relacionados com a extensão SREG return redirect_to_login(request.get_full_path() + '?' + urllib.urlencode(query)) user_identity = request.build_absolute_uri( request.user.get_profile().get_absolute_url()) if not openid_request.identity == user_identity and not openid_request.idSelect( ): raise Exception, "User " + request.user.username + " is not the owner of " + openid_request.identity + " identity" return handle_check_id_request(request, openid_request) else: # We got some other kind of OpenID request, so we let the # server handle this. openid_response = s.handleRequest(openid_request) return display_response(request, openid_response)
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) return super().dispatch(request, *args, **kwargs)
def layout(request, slug, display=None): if display is None and not request.user.is_authenticated: return redirect_to_login(request.get_full_path()) if request.user.is_superuser or display: layout = get_object_or_404(Layout, slug=slug) else: layout = get_object_or_404(Layout, slug=slug, owner=request.user) # Build unique widget list from layout.design.widgets, with backsupport for layout.design uwl = [] # unique widget list if 'widgets' in layout.design: widgets = layout.design['widgets'] else: widgets = layout.design for key, value in widgets.items(): if 'widget' in value and value['widget'] not in uwl: uwl.append(value['widget']) dependencies_list = generate_dependencies_list(uwl) # If there are any traffic-map widgets, then get a Google API key - # either the first custom key found in a traffic-map widget # configuration, or the default from settings. Use this to add # a custom URL to dependencies_list for inclusion in the rendered # page if 'traffic_map' in uwl: api_key = settings.GOOGLE_API_KEY for widget_config in widgets.values(): if widget_config['widget'] == 'traffic_map': custom_key = widget_config['data'].get('api_key', None) if custom_key: api_key = custom_key break url = "https://maps.googleapis.com/maps/api/js?key={}".format(api_key) dependencies_list['js'].append({"src": url}) if display is None: # layout gets a 10-minute rt_token token_uri = reverse('smartpanel-layout', kwargs={'slug': slug}) rt_token = rt_crypto.rt_token(token_uri, { "uses": "5", "duration": timedelta(minutes=10) }) else: # display gets a 25-hour rt_token token_uri = reverse('smartpanel-display', kwargs={'slug': display.slug}) rt_token = rt_crypto.rt_token(token_uri, { "uses": "5", "duration": timedelta(hours=25) }) return render( request, 'smartpanel/layout.html', { 'layout': layout, 'stylesheets': dependencies_list['css'], 'scripts': dependencies_list['js'], 'display': display, 'rt_token': rt_token, 'RTMONITOR_URI': settings.RTMONITOR_URI, 'settings': smartpanel_settings() })
def __call__(self, request, invitation_id, **kwargs): logging.info( "Don't use this view in more apps until it gets cleaned up.") # add the correct parameters to this instance self.request = request self.inv_id = invitation_id if 'domain' in kwargs: self.domain = kwargs['domain'] if request.GET.get('switch') == 'true': logout(request) return redirect_to_login(request.path) if request.GET.get('create') == 'true': logout(request) return HttpResponseRedirect(request.path) try: invitation = Invitation.get(invitation_id) except ResourceNotFound: messages.error( request, _("Sorry, it looks like your invitation has expired. " "Please check the invitation link you received and try again, or request a " "project administrator to send you the invitation again.")) return HttpResponseRedirect(reverse("login")) if invitation.is_accepted: messages.error( request, _("Sorry, that invitation has already been used up. " "If you feel this is a mistake please ask the inviter for " "another invitation.")) return HttpResponseRedirect(reverse("login")) self.validate_invitation(invitation) if invitation.is_expired: return HttpResponseRedirect(reverse("no_permissions")) # Add zero-width space to username for better line breaking username = self.request.user.username.replace("@", "​@") context = { 'create_domain': False, 'formatted_username': username, 'domain': self.domain, 'invite_to': self.domain, 'invite_type': _('Project'), 'hide_password_feedback': settings.ENABLE_DRACONIAN_SECURITY_FEATURES, } if request.user.is_authenticated: context['current_page'] = {'page_name': _('Project Invitation')} else: context['current_page'] = { 'page_name': _('Project Invitation, Account Required') } if request.user.is_authenticated: is_invited_user = request.couch_user.username.lower( ) == invitation.email.lower() if self.is_invited(invitation, request.couch_user ) and not request.couch_user.is_superuser: if is_invited_user: # if this invite was actually for this user, just mark it accepted messages.info( request, _("You are already a member of {entity}.").format( entity=self.inviting_entity)) invitation.is_accepted = True invitation.save() else: messages.error( request, _("It looks like you are trying to accept an invitation for " "{invited} but you are already a member of {entity} with the " "account {current}. Please sign out to accept this invitation " "as another user.").format( entity=self.inviting_entity, invited=invitation.email, current=request.couch_user.username, )) return HttpResponseRedirect(self.redirect_to_on_success) if not is_invited_user: messages.error( request, _("The invited user {invited} and your user {current} do not match!" ).format(invited=invitation.email, current=request.couch_user.username)) if request.method == "POST": couch_user = CouchUser.from_django_user(request.user, strict=True) self._invite(invitation, couch_user) track_workflow( request.couch_user.get_email(), "Current user accepted a project invitation", {"Current user accepted a project invitation": "yes"}) send_hubspot_form(HUBSPOT_EXISTING_USER_INVITE_FORM, request) return HttpResponseRedirect(self.redirect_to_on_success) else: mobile_user = CouchUser.from_django_user( request.user).is_commcare_user() context.update({ 'mobile_user': mobile_user, "invited_user": invitation.email if request.couch_user.username != invitation.email else "", }) return render(request, self.template, context) else: if request.method == "POST": form = WebUserInvitationForm(request.POST) if form.is_valid(): # create the new user user = activate_new_user(form, domain=invitation.domain) user.save() messages.success( request, _("User account for %s created!") % form.cleaned_data["email"]) self._invite(invitation, user) authenticated = authenticate( username=form.cleaned_data["email"], password=form.cleaned_data["password"]) if authenticated is not None and authenticated.is_active: login(request, authenticated) track_workflow( request.POST['email'], "New User Accepted a project invitation", {"New User Accepted a project invitation": "yes"}) send_hubspot_form(HUBSPOT_NEW_USER_INVITE_FORM, request, user) return HttpResponseRedirect( reverse("domain_homepage", args=[invitation.domain])) else: if CouchUser.get_by_username(invitation.email): return HttpResponseRedirect( reverse("login") + '?next=' + reverse('domain_accept_invitation', args=[invitation.domain, invitation.get_id])) form = WebUserInvitationForm( initial={ 'email': invitation.email, 'hr_name': invitation.domain, 'create_domain': False, }) context.update({"form": form}) return render(request, self.template, context)
def process_request(self, request): if request.path.startswith('/admin/'): if not request.user.is_superuser: return redirect_to_login(request.path) # Continue processing the request as usual: return None
def get(self, request, *args, **kwargs): self.activate_user() messages.success(request, self.success_message) return redirect_to_login('/', login_url=self.url)
def finalize_response(self, request, response, *args, **kwargs): response = super(RedirectToLoginMixin, self).finalize_response(request, response, *args, **kwargs) if not request.user.is_authenticated() and isinstance(response.accepted_renderer, self.redirected_classes): response = redirect_to_login(request.path) response.data = {} return response
def safe_login_prompt(request): return redirect_to_login(app_settings.EXPLORER_LOGIN_URL)
def archive_list(request, model=None, options=None, query_name=None, query=None, page=1, viewmode_name=None, **kwargs): """ List view for archives """ # Check if the view is restricted to internal access: _authorize_internal(request, kwargs) # # Initial error checking - make sure we have a query # # options and model classes required if options is None or model is None: raise ImproperlyConfigured( "Generic archive list view must be installed in the URL conf with model and options parameters." ) # query name or a query required if not (query_name or query): raise Http404 if query_name: query = getattr(options.Queries, query_name, None) if not (query is not None and isinstance(query, ArchiveQuery)): raise Http404 # Check if request is internal and generate cache key if is_internal(request): key = '%s_archive_list_internal_%s' % (model.get_cache_key_prefix(), str(request.path.__hash__())) else: key = '%s_archive_list_external_%s' % (model.get_cache_key_prefix(), str(request.path.__hash__())) # # Determine archive browser # if viewmode_name is None: if query.viewmode_param is not None: viewmode_name = request.GET.get(query.viewmode_param, query.default_browser) else: viewmode_name = query.default_browser if not query.has_browser(viewmode_name): raise Http404 try: browser = getattr(options.Browsers, viewmode_name) except AttributeError: raise Http404 # Check if view in cache: ca = model.cache_get(key) # # Authorize view # if not query.has_permissions(request): if request.user.is_authenticated(): return HttpResponseForbidden( render_to_string('403.html', request=request)) else: return redirect_to_login(next=request.get_full_path()) # Check parameters and redirect if necessary: redirect_url = query.check_parameters(model, options, request) if redirect_url: return redirect(redirect_url) # We don't used cached view if we have GET data (to prevent # caching search queries) if ca and not request.GET: return browser.response(ca) # # Get Query Set # (qs, query_data) = query.queryset(model, options, request, **kwargs) # Exclude all non-published archive items (if archive uses published attribute) # FIXME: this results in duplicates "published=1" in the SQL. Really this # should be done in the query, like in AllPublicQuery, however some queries # such as SubjectCategoryNamePublicQuery need to be updated (SubjectCategoryNameQuery should for example # inherit from AllPublicQuery instead of SubjectCategoryNameQuery) if model.Archive.Meta.published: if hasattr(qs, 'filter'): qs = qs.filter(**{model.Archive.Meta.published_fieldname: True}) if options.select_related: qs = qs.select_related(*options.select_related) if options.prefetch_related: qs = qs.prefetch_related(*options.prefetch_related) if options.archive_list_only_fields: qs = qs.only(*options.archive_list_only_fields) # # Search in query set if query is searchable. # search_str = request.GET.get(SEARCH_VAR, '').strip() search_str = query_data.get('adv_search_str', search_str) if search_str and '\0' in urlunquote(search_str): # Tell Nginx to drop connection if someone is passing null bytes # to the query return HttpResponse(status=444) if query.searchable and search_str and not query_data.get( 'adv_search_str', False): qs = options.search(request, qs, search_str) # # Render results # kwargs.update({'page': page, 'viewmode_name': viewmode_name}) # Temp hack content = browser.render(request, model, options, query, query_name, qs, query_data, search_str, **kwargs) if not request.GET: model.cache_set(key, content) return browser.response(content)
def dispatch(self, request, *args, **kwargs): if request.user.user_type == settings.STAFF_ACCOUNT_TYPE: return super().dispatch(request, *args, **kwargs) else: return redirect_to_login(self.request.get_full_path())
def wrapper(request, *args, **kwargs): if not test_func(request, *args, **kwargs): return redirect_to_login(request.get_full_path()) else: return view_func(request, *args, **kwargs)
def require_wagtail_login(next): login_url = getattr(settings, 'WAGTAIL_FRONTEND_LOGIN_URL', reverse('wagtailcore_login')) return redirect_to_login(next, login_url)
def dispatch(self, request, *args, **kwargs): if self.get_user_profile() is None: path = request.get_full_path() return redirect_to_login(path) return super(LoginRequired, self).dispatch(request, *args, **kwargs)
def _wrapped_view(request, *args, **kwargs): if not is_X509_authenticated(request): return redirect_to_login(request.get_full_path(), reverse('auth')) return view_func(request, *args, **kwargs)
def get_html_response(self, request): getattr(messages, self.level)(request, self.message) return redirect_to_login(self.next, self.login_url)
def handle_no_permission(self): if self.raise_exception: raise PermissionDenied(self.get_permission_denied_message()) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
def get(self, request, *args, **kwargs): authorize = AuthorizeEndpoint(request) try: authorize.validate_params() if request.user.is_authenticated(): # Check if there's a hook setted. hook_resp = settings.get('OIDC_AFTER_USERLOGIN_HOOK', import_str=True)( request=request, user=request.user, client=authorize.client) if hook_resp: return hook_resp if settings.get('OIDC_SKIP_CONSENT_ALWAYS') and not (authorize.client.client_type == 'public') \ and not (authorize.params.prompt == 'consent'): return redirect(authorize.create_response_uri()) if settings.get('OIDC_SKIP_CONSENT_ENABLE'): # Check if user previously give consent. if authorize.client_has_user_consent() and not (authorize.client.client_type == 'public') \ and not (authorize.params.prompt == 'consent'): return redirect(authorize.create_response_uri()) # Generate hidden inputs for the form. context = { 'params': authorize.params, } hidden_inputs = render_to_string( 'oidc_provider/hidden_inputs.html', context) # Remove `openid` from scope list # since we don't need to print it. if 'openid' in authorize.params.scope: authorize.params.scope.remove('openid') context = { 'client': authorize.client, 'hidden_inputs': hidden_inputs, 'params': authorize.params, } if authorize.params.prompt == 'none': raise AuthorizeError(authorize.params.redirect_uri, 'interaction_required', authorize.grant_type) if authorize.params.prompt == 'login': return redirect_to_login(request.get_full_path()) if authorize.params.prompt == 'select_account': # TODO: see how we can support multiple accounts for the end-user. raise AuthorizeError(authorize.params.redirect_uri, 'account_selection_required', authorize.grant_type) return render(request, 'oidc_provider/authorize.html', context) else: if authorize.params.prompt == 'none': raise AuthorizeError(authorize.params.redirect_uri, 'login_required', authorize.grant_type) return redirect_to_login(request.get_full_path()) except (ClientIdError, RedirectUriError) as error: context = { 'error': error.error, 'description': error.description, } return render(request, 'oidc_provider/error.html', context) except (AuthorizeError) as error: uri = error.create_uri( authorize.params.redirect_uri, authorize.params.state) return redirect(uri)
def dispatch(self, request, *args, **kwargs): """ Only dispatches the view if the user is authenticated to update his profile """ if not self.user_passes_test(request): return redirect_to_login(request.get_full_path()) return super(ProfileUpdate, self).dispatch( request, *args, **kwargs)