Beispiel #1
0
def mail_followee(request, fwee, fwer):
    followee_name = user_display(fwee)
    follower_name = user_display(fwer)

    subject = _("%(followee)s, %(follower)s is now following you on NewCo.")
    subject_kwargs = {"followee": followee_name, "follower": follower_name}

    txt_template = get_template("mail/_follow_notification_email.txt")
    html_template = get_template("mail/_follow_notification_email.html")

    context = Context({
        "followee":
        fwee,
        "follower":
        fwer,
        "followee_name":
        followee_name,
        "follower_name":
        follower_name,
        "followee_url":
        request.build_absolute_uri(fwee.get_absolute_url()),
        "follower_url":
        request.build_absolute_uri(fwer.get_absolute_url()),
        "request":
        request,
        "message_subject":
        subject
    })

    send_mail(subject, subject_kwargs, fwee, txt_template, html_template,
              context, fwer)
Beispiel #2
0
def mail_question_author(request, answer):
    question = answer.question
    receiver = question.author
    receiver_name = user_display(question.author)
    answerer = answer.author
    answerer_name = user_display(answer.author)

    subject = _("%(receiver)s, %(answerer)s has answered your question!")
    subject_kwargs = {"receiver": receiver_name, "answerer": answerer_name}

    txt_template = get_template("mail/_answer_notification_email.txt")
    html_template = get_template("mail/_answer_notification_email.html")

    context = Context({
        "answer":
        answer,
        "request":
        request,
        "receiver":
        receiver_name,
        "receiver_url":
        request.build_absolute_uri(receiver.get_absolute_url()),
        "answerer":
        answerer_name,
        "answerer_url":
        request.build_absolute_uri(answerer.get_absolute_url()),
        "message_subject":
        subject,
    })
    send_mail(subject, subject_kwargs, receiver, txt_template, html_template,
              context, answerer)
Beispiel #3
0
    def render(self, context):
        try:
            content = self.content.resolve(context)
            display = self.display.resolve(context)
            args, kwargs = self.resolve_template_args(context)
        except:
            return ""

        pic_size = kwargs.get("pic_size", None)
        pic_size = args[0] if not pic_size and len(args) > 0 else pic_size

        template, author = ["content/info.html", content.author]
        ctx = {"created": content.created}
        if "signature" in display or display == "detail":
            ctx.update({"case": "signature"})
            if display in ["signature", "detail"]:
                ctx.update({
                    "signature_author": True,
                    "signature_pic": True,
                    "author_name": user_display(author),
                    "reputation": author.reputation.reputation_incremented,
                    "author_url": author.get_absolute_url(),
                    "profile_pic": profile_pic(author, size=pic_size)
                })
            elif display == "signature-author":
                ctx.update({
                    "signature_author": True,
                    "author_name": user_display(author),
                    "reputation": author.reputation.reputation_incremented,
                    "author_url": author.get_absolute_url()
                })
            elif display == "signature-pic":
                ctx.update({
                    "signature_pic": True,
                    "profile_pic": profile_pic(author, size=pic_size)
                })
            else:
                raise TemplateSyntaxError("'content_info': wrong display.")
        elif display == "header":
            ctx.update({
                "case": "header",
                # "author_name": user_display(author),
                # "author_url": author.get_absolute_url(),
                "author": author,
                "reputation": author.reputation.reputation_incremented,
                "about": author.get_profile().about
            })
        elif display in ["date", "list"]:
            ctx.update({"case": "date"})
        else:
            raise TemplateSyntaxError("'content_info': wrong display value.")
        return render_to_string(template, ctx, context_instance=context)
Beispiel #4
0
def confirm_email(request, confirmation_key, **kwargs):
    """
    Confirms the email as normal, but then also logs the user in if succesful
    """
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)
    email_address = None
    user = authenticate(confirmation_key=confirmation_key)
    if user:
        auth_login(request, user)
        try:
            email_confirmation = EmailConfirmation.objects.get(confirmation_key=confirmation_key)
            email_address = email_confirmation.email_address
            # now delete the confirmation
            email_confirmation.delete()
            if success_url is None:
                success_url = get_default_redirect(request, redirect_field_name)
            messages.add_message(
                request,
                messages.SUCCESS,
                ugettext(u"You have confirmed that %(email)s is an email address for user '%(user)s'.")
                % {"user": user_display(email_address.user), "email": email_address.email},
            )
            return HttpResponseRedirect(success_url)
        except:
            pass

    return render_to_response(
        "emailconfirmation/confirm_email.html",
        {"email_address": email_address},
        context_instance=RequestContext(request),
    )
Beispiel #5
0
def folder_share(request, pk):
    User = get_user_model()
    qs = Folder.objects.for_user(request.user)
    folder = get_object_or_404(qs, pk=pk)
    if not folder.can_share(request.user):
        raise Http404()
    form_kwargs = {
        "colleagues": User.objects.all()  # @@@ make this a hookset to be defined at site level
    }
    if request.method == "POST":
        if "remove" in request.POST:
            user_to_remove = User.objects.get(pk=request.POST["remove"])
            messages.success(request, "{} has been removed from folder share".format(user_display(user_to_remove)))
            return redirect("documents_folder_share", folder.pk)
        else:
            form = ColleagueFolderShareForm(request.POST, **form_kwargs)
            if form.is_valid():
                folder.share(form.cleaned_data["participants"])
                return redirect(folder)
    else:
        form = ColleagueFolderShareForm(**form_kwargs)
    ctx = {
        "folder": folder,
        "form": form,
        "participants": folder.shared_with(),
    }
    return render(request, "documents/folder_share.html", ctx)
Beispiel #6
0
 def render(self, context):
     user = self.user_var.resolve(context)
     display = user_display(user)
     if self.as_var:
         context[self.as_var] = display
         return ""
     return conditional_escape(display)
 def render(self, context):
     user = self.user_var.resolve(context)
     display = user_display(user)
     if self.as_var:
         context[self.as_var] = display
         return ""
     return conditional_escape(display)
Beispiel #8
0
    def render(self, context):
        try:
            obj = self.obj.resolve(context)
            display = self.display.resolve(context)
            args, kwargs = self.resolve_template_args(context)
        except:
            return ""

        ctx = {"object": obj, "display": display}

        color = kwargs.get("color", None)
        color = args[0] if not color and len(args) > 0 else color
        if color:
            ctx.update({"color": color})

        if obj.__class__ is Item:
            template = "items/_product_display.html"
        elif obj.__class__ is User:
            template = "profiles/_profile_display.html"
            skills = obj.get_profile().skills
            ctx.update({"username": user_display(obj)})
            if skills.count():
                ctx.update({"skills": skills})
        else:
            raise TemplateSyntaxError("'object_display' only renders Item "
                                      "and User instances")
        html = render_to_string(template, ctx, context_instance=context)

        return self.render_output(context, html)
Beispiel #9
0
    def process_following(self, request, obj, success_url):
        user = request.user
        kwargs = {}
        if not user == obj:
            is_following = Follow.objects.is_following(user, obj)
            follow_obj = unfollow(user, obj) if is_following else \
                follow(user, obj)
            is_following = not is_following

            if follow_obj.target.__class__ is User:
                if is_following:
                    mail_followee(request, follow_obj.target, user)
                title = user_display(follow_obj.target)
            else:
                title = unicode(follow_obj.target)

            key = "follow" if is_following else "unfollow"
            kwargs.update({"object": title})
        else:
            key = "follow-warning"
        add_message(key, request, **kwargs)

        if request.is_ajax():
            messages = render_messages(request)
            data = {"is_following": is_following, "messages": messages}
            return HttpResponse(json.dumps(data), mimetype="application/json")
        else:
            return HttpResponseRedirect(success_url)
Beispiel #10
0
def login(request, **kwargs):

    form_class = kwargs.pop("form_class", LoginForm)
    template_name = kwargs.pop("template_name", "account/login.html")
    success_url = (request.GET.get("success_url")
                   or request.POST.get("success_url")
                   or kwargs.pop("success_url", None))
    associate_openid = kwargs.pop("associate_openid", False)
    openid_success_url = kwargs.pop("openid_success_url", None)
    url_required = kwargs.pop("url_required", False)
    extra_context = kwargs.pop("extra_context", {})
    redirect_field_name = kwargs.pop("redirect_field_name", "next")

    group, bridge = group_and_bridge(kwargs)

    if extra_context is None:
        extra_context = {}
    if success_url is None:
        if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
            fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
        else:
            fallback_url = settings.LOGIN_REDIRECT_URL
        success_url = get_default_redirect(request, fallback_url,
                                           redirect_field_name)

    if request.method == "POST" and not url_required:
        form = form_class(request.POST, group=group)
        if form.is_valid():
            form.login(request)
            if associate_openid and association_model is not None:
                for openid in request.session.get("openids", []):
                    assoc, created = UserOpenidAssociation.objects.get_or_create(
                        user=form.user, openid=openid.openid)
                success_url = openid_success_url or success_url
            messages.add_message(
                request, messages.SUCCESS,
                ugettext(u"Successfully logged in as %(user)s.") %
                {"user": user_display(form.user)})
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(group=group)

    ctx = group_context(group, bridge)
    ctx.update({
        "form":
        form,
        "url_required":
        url_required,
        "redirect_field_name":
        redirect_field_name,
        "redirect_field_value":
        request.GET.get(redirect_field_name,
                        request.POST.get(redirect_field_name)),
        "success_url":
        success_url,
    })
    ctx.update(extra_context)

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #11
0
def signup(request, **kwargs):

    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/signup.html")
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)

    group, bridge = group_and_bridge(kwargs)
    ctx = group_context(group, bridge)
    ctx['invite_parameters'] = get_invite_parameters(request)

    if success_url is None:
        if hasattr(settings, "SIGNUP_REDIRECT_URLNAME"):
            fallback_url = reverse(settings.SIGNUP_REDIRECT_URLNAME)
        else:
            if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
                fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
            else:
                fallback_url = settings.LOGIN_REDIRECT_URL
        success_url = get_default_redirect(request, fallback_url,
                                           redirect_field_name)

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, group=group)
        if form.is_valid():
            user = form.save(request=request)
            accept_invite(request, user)
            if settings.ACCOUNT_EMAIL_VERIFICATION:
                ctx.update({
                    "email": form.cleaned_data["email"],
                    "success_url": success_url,
                })
                ctx = RequestContext(request, ctx)
                return render_to_response("account/verification_sent.html",
                                          ctx)
            else:
                form.login(request, user)
                messages.add_message(
                    request, messages.SUCCESS,
                    ugettext("Successfully logged in as %(user)s.") %
                    {"user": user_display(user)})
                return HttpResponseRedirect(success_url)
    else:
        form = form_class(group=group,
                          initial={
                              'username': ugettext('Username'),
                              'email': ugettext('Email address')
                          })

    ctx.update({
        "form":
        form,
        "redirect_field_name":
        redirect_field_name,
        "redirect_field_value":
        request.REQUEST.get(redirect_field_name),
    })

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #12
0
def login(request, **kwargs):

    form_class = kwargs.pop("form_class", LoginForm)
    template_name = kwargs.pop("template_name", "account/login.html")
    success_url = (request.GET.get("success_url")
                   or request.POST.get("success_url")
                   or kwargs.pop("success_url", None))
    associate_openid = kwargs.pop("associate_openid", False)
    openid_success_url = kwargs.pop("openid_success_url", None)
    url_required = kwargs.pop("url_required", False)
    extra_context = kwargs.pop("extra_context", {})
    redirect_field_name = kwargs.pop("redirect_field_name", "next")

    group, bridge = group_and_bridge(kwargs)

    if extra_context is None:
        extra_context = {}
    if success_url is None:
        if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
            fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
        else:
            fallback_url = settings.LOGIN_REDIRECT_URL
        success_url = get_default_redirect(
            request, fallback_url, redirect_field_name)

    if request.method == "POST" and not url_required:
        form = form_class(request.POST, group=group)
        if form.is_valid():
            form.login(request)
            if associate_openid and association_model is not None:
                for openid in request.session.get("openids", []):
                    assoc, created = UserOpenidAssociation.objects.get_or_create(
                        user=form.user, openid=openid.openid
                    )
                success_url = openid_success_url or success_url
            messages.add_message(
                request, messages.SUCCESS,
                ugettext(u"Successfully logged in as %(user)s.") % {
                    "user": user_display(form.user)
                })
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(group=group)

    ctx = group_context(group, bridge)
    ctx.update({
        "form": form,
        "url_required": url_required,
        "redirect_field_name": redirect_field_name,
        "redirect_field_value": request.GET.get(
            redirect_field_name,
            request.POST.get(redirect_field_name)
        ),
        "success_url": success_url,
    })
    ctx.update(extra_context)

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #13
0
def signup(request, **kwargs):

    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/signup.html")
    template_name_failure = kwargs.pop("template_name_failure", "signup_codes/failure.html")
    success_url = kwargs.pop("success_url", None)

    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)

    if success_url is None:
        if hasattr(settings, "SIGNUP_REDIRECT_URLNAME"):
            fallback_url = reverse(settings.SIGNUP_REDIRECT_URLNAME)
        else:
            if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
                fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
            else:
                fallback_url = settings.LOGIN_REDIRECT_URL
        success_url = get_default_redirect(request, fallback_url)

    code = request.GET.get("code")

    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            user = form.save(request=request)

            signup_code = form.cleaned_data["signup_code"]
            if signup_code:
                signup_code.use(user)

            form.login(request, user)
            messages.add_message(
                request,
                messages.SUCCESS,
                ugettext("Successfully logged in as %(username)s.") % {"username": user_display(user)},
            )
            return HttpResponseRedirect(success_url)
    else:
        signup_code = SignupCode.check(code)
        if signup_code:
            initial = {"signup_code": code, "email": signup_code.email}
            form = form_class(initial=initial, group=group)
        else:
            if not settings.ACCOUNT_OPEN_SIGNUP:
                ctx.update({"code": code})
                ctx = RequestContext(request, ctx)
                # if account signup is not open we want to fail when there is
                # no sign up code or what was provided failed.
                return render_to_response(template_name_failure, ctx)
            else:
                form = form_class(group=group)

    ctx.update({"code": code, "form": form})

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #14
0
 def form_valid(self, form):
     self.created_user = self.create_user(form, commit=False)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED:
         self.created_user.is_active = False
     # prevent User post_save signal from creating an Account instance
     # we want to handle that ourself.
     self.created_user._disable_account_creation = True
     self.created_user.save()
     self.create_account(form)
     email_kwargs = {
         "primary": True,
         "verified": False,
         "confirm": settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL,
     }
     if self.signup_code:
         self.signup_code.use(self.created_user)
         if self.signup_code.email and self.created_user.email == self.signup_code.email:
             email_kwargs["verified"] = True
     EmailAddress.objects.add_email(self.created_user, self.created_user.email, **email_kwargs)
     self.after_signup(form)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_kwargs["verified"]:
         response_kwargs = {
             "request": self.request,
             "template": self.template_name_email_confirmation_sent,
             "context": {
                 "email": self.created_user.email,
                 "success_url": self.get_success_url(),
             }
         }
         return self.response_class(**response_kwargs)
     else:
         show_message = [
             settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL,
             self.messages.get("email_confirmation_sent"),
             not email_kwargs["verified"]
         ]
         if all(show_message):
             messages.add_message(
                 self.request,
                 self.messages["email_confirmation_sent"]["level"],
                 self.messages["email_confirmation_sent"]["text"] % {
                     "email": form.cleaned_data["email"]
                 }
             )
         self.login_user()
         if self.messages.get("logged_in"):
             messages.add_message(
                 self.request,
                 self.messages["logged_in"]["level"],
                 self.messages["logged_in"]["text"] % {
                     "user": user_display(self.created_user)
                 }
             )
     return redirect(self.get_success_url())
Beispiel #15
0
 def form_valid(self, form):
     new_user = self.create_user(form, commit=False)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED:
         new_user.is_active = False
     # prevent User post_save signal from creating an Account instance
     # we want to handle that ourself.
     new_user._disable_account_creation = True
     new_user.save()
     self.create_account(new_user, form)
     email_kwargs = {
         "primary": True,
         "verified": False,
         "confirm": settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL,
     }
     if self.signup_code:
         self.signup_code.use(new_user)
         if self.signup_code.email and new_user.email == self.signup_code.email:
             email_kwargs["verified"] = True
     EmailAddress.objects.add_email(new_user, new_user.email, **email_kwargs)
     self.after_signup(new_user, form)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_kwargs["verified"]:
         response_kwargs = {
             "request": self.request,
             "template": self.template_name_email_confirmation_sent,
             "context": {
                 "email": new_user.email,
                 "success_url": self.get_success_url(),
             }
         }
         return self.response_class(**response_kwargs)
     else:
         show_message = [
             settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL,
             self.messages.get("email_confirmation_sent"),
             not email_kwargs["verified"]
         ]
         if all(show_message):
             messages.add_message(
                 self.request,
                 self.messages["email_confirmation_sent"]["level"],
                 self.messages["email_confirmation_sent"]["text"] % {
                     "email": form.cleaned_data["email"]
                 }
             )
         self.login_user(new_user)
         if self.messages.get("logged_in"):
             messages.add_message(
                 self.request,
                 self.messages["logged_in"]["level"],
                 self.messages["logged_in"]["text"] % {
                     "user": user_display(new_user)
                 }
             )
     return redirect(self.get_success_url())
Beispiel #16
0
def signup(request, **kwargs):

    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/signup.html")
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)

    group, bridge = group_and_bridge(kwargs)
    ctx = group_context(group, bridge)

    if success_url is None:
        if hasattr(settings, "SIGNUP_REDIRECT_URLNAME"):
            fallback_url = reverse(settings.SIGNUP_REDIRECT_URLNAME)
        else:
            if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
                fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
            else:
                fallback_url = settings.LOGIN_REDIRECT_URL
        success_url = get_default_redirect(
            request, fallback_url, redirect_field_name)

    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            user = form.save(request=request)
            if settings.ACCOUNT_EMAIL_VERIFICATION:
                ctx.update({
                    "email": form.cleaned_data["email"],
                    "success_url": success_url,
                })
                ctx = RequestContext(request, ctx)
                return render_to_response("account/verification_sent.html",
                                          ctx)
            else:
                form.login(request, user)
                messages.add_message(
                    request, messages.SUCCESS,
                    ugettext("Successfully logged in as %(user)s.") % {
                        "user": user_display(user)
                    })
                return HttpResponseRedirect(success_url)
    else:
        form = form_class(group=group)

    ctx.update({
        "form": form,
        "redirect_field_name": redirect_field_name,
        "redirect_field_value": request.GET.get(
            redirect_field_name,
            request.POST.get(redirect_field_name)),
    })

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #17
0
def signup(request, **kwargs):
    
    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/signup.html")
    template_name_failure = kwargs.pop("template_name_failure", "signup_codes/failure.html")
    success_url = kwargs.pop("success_url", None)
    
    group, bridge = group_and_bridge(kwargs)
    ctx = group_context(group, bridge)
    
    if success_url is None:
        success_url = get_default_redirect(request)
    
    code = request.GET.get("code")
    
    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            username, password = form.save()
            user = authenticate(username=username, password=password)
            
            signup_code = form.cleaned_data["signup_code"]
            signup_code.use(user)
            
            auth_login(request, user)
            messages.add_message(request, messages.SUCCESS,
                ugettext("Successfully logged in as %(username)s.") % {
                    "username": user_display(user),
                }
            )
            return HttpResponseRedirect(success_url)
    else:
        signup_code = check_signup_code(code)
        if signup_code:
            form = form_class(initial={"signup_code": code}, group=group)
        else:
            if not settings.ACCOUNT_OPEN_SIGNUP:
                ctx.update({
                    "code": code,
                })
                ctx = RequestContext(request, ctx)
                # if account signup is not open we want to fail when there is
                # no sign up code or what was provided failed.
                return render_to_response(template_name_failure, ctx)
            else:
                form = form_class(group=group)
    
    ctx.update({
        "code": code,
        "form": form,
    })
    
    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #18
0
def signup(request, **kwargs):

    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/account_signup.html")
    template_name_failure = kwargs.pop("template_name_failure",
                                       "signup_codes/failure.html")
    success_url = kwargs.pop("success_url", None)

    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)

    if success_url is None:
        success_url = get_default_redirect(request)

    code = request.GET.get("code")

    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            user = form.save(request=request)

            signup_code = form.cleaned_data["signup_code"]
            signup_code.use(user)

            form.login(request, user)
            messages.add_message(
                request, messages.SUCCESS,
                ugettext("Successfully logged in as %(username)s.") % {
                    "username": user_display(user),
                })
            return HttpResponseRedirect(success_url)
    else:
        signup_code = check_signup_code(code)
        if signup_code:
            form = form_class(initial={"signup_code": code}, group=group)
        else:
            if not settings.ACCOUNT_OPEN_SIGNUP:
                ctx.update({
                    "code": code,
                })
                ctx = RequestContext(request, ctx)
                # if account signup is not open we want to fail when there is
                # no sign up code or what was provided failed.
                return render_to_response(template_name_failure, ctx)
            else:
                form = form_class(group=group)

    ctx.update({
        "code": code,
        "form": form,
    })

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #19
0
    def form_valid(self, form):
        if "ask" not in self.request.POST:
            return super(AskForHelpMixin, self).form_valid(form)

        receiver_profiles = []
        request, user = [self.request, self.request.user]
        question = Question.objects.get(id=form.question_id)
        username = user_display(user)

        for key, value in form.cleaned_data.items():
            if key in ["experts", "users"] and value:
                profile_ids = map(int, re.split("\D+", value))
                receiver_profiles.extend(Profile.objects.filter(
                    id__in=profile_ids).select_related("user"))
            elif key == "email" and value:
                m = EMAIL_PATTERN.match(request.POST["email"])
                if m:
                    receiver_profile = Profile(user=User(email=m.group()),
                                               name=m.group("username"))
                    receiver_profile.user.account = Account()
                    receiver_profile.user.get_absolute_url = void
                    receiver_profiles.append(receiver_profile)
                else:
                    kwargs = {"user": username, "email": request.POST["email"]}
                    add_message("email-error", request, **kwargs)

        for receiver_profile in receiver_profiles:
            receiver = receiver_profile.user

            receiver_name = user_display(receiver_profile)

            if receiver != user:
                mail_helper(request, receiver, user, question, receiver_name,
                            username)
                kwargs = {"user": username, "receiver": receiver_name}
                add_message("email-sent", request, **kwargs)
            else:
                add_message("ask-warning", request, user=username)

        return HttpResponseRedirect(request.path)
Beispiel #20
0
def mail_helper(request,
                receiver,
                requester,
                question,
                receiver_name=None,
                requester_name=None):
    if not receiver_name:
        receiver_name = user_display(receiver)
    if not requester_name:
        requester_name = user_display(requester)

    subject = _("%(receiver)s, %(requester)s needs your help.")
    subject_kwargs = {"receiver": receiver_name, "requester": requester_name}

    txt_template = get_template("mail/_ask_notification_email.txt")
    html_template = get_template("mail/_ask_notification_email.html")

    context = Context({
        "receiver":
        receiver_name,
        "receiver_url":
        request.build_absolute_uri(receiver.get_absolute_url()),
        "asker":
        requester_name,
        "asker_url":
        request.build_absolute_uri(requester.get_absolute_url()),
        "request":
        request,
        "message_subject":
        subject,
        "question":
        question,
        "question_url":
        request.build_absolute_uri(question.get_absolute_url()),
        "settings_url":
        request.build_absolute_uri(reverse("account_settings"))
    })

    send_mail(subject, subject_kwargs, receiver, txt_template, html_template,
              context, requester)
Beispiel #21
0
 def form_valid(self, form):
     email_confirmed = False
     new_user = self.create_user(form, commit=False)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED:
         new_user.is_active = False
     new_user.save()
     signup_code = form.cleaned_data.get("code")
     if signup_code:
         signup_code.use(new_user)
         if signup_code.email and form.cleaned_data["email"] == signup_code.email:
             EmailAddress.objects.create(
                 user=new_user,
                 email=form.cleaned_data["email"],
                 primary=True,
                 verified=True
             )
             email_confirmed = True
         else:
             EmailAddress.objects.add_email(new_user, form.cleaned_data["email"])
     else:
         EmailAddress.objects.add_email(new_user, form.cleaned_data["email"])
     self.after_signup(new_user, form)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_confirmed:
         response_kwargs = {
             "request": self.request,
             "template": self.template_name_email_confirmation_sent,
             "context": {
                 "email": form.cleaned_data["email"],
                 "success_url": self.get_success_url(),
             }
         }
         return self.response_class(**response_kwargs)
     else:
         if self.messages.get("email_confirmation_sent") and not email_confirmed:
             messages.add_message(
                 self.request,
                 self.messages["email_confirmation_sent"]["level"],
                 self.messages["email_confirmation_sent"]["text"] % {
                     "email": form.cleaned_data["email"]
                 }
             )
         self.login_user(new_user)
         if self.messages.get("logged_in"):
             messages.add_message(
                 self.request,
                 self.messages["logged_in"]["level"],
                 self.messages["logged_in"]["text"] % {
                     "user": user_display(new_user)
                 }
             )
     return super(SignupView, self).form_valid(form)
Beispiel #22
0
def login(request, **kwargs):

    form_class = kwargs.pop("form_class", LoginForm)
    template_name = kwargs.pop("template_name", "account/login.html")
    success_url = kwargs.pop("success_url", None)
    associate_openid = kwargs.pop("associate_openid", False)
    openid_success_url = kwargs.pop("openid_success_url", None)
    url_required = kwargs.pop("url_required", False)
    extra_context = kwargs.pop("extra_context", {})
    redirect_field_name = kwargs.pop("redirect_field_name", "next")

    group, bridge = group_and_bridge(kwargs)

    if extra_context is None:
        extra_context = {}

    if request.method == "POST" and not url_required:
        form = form_class(request.POST, group=group)
        if form.login(request):
            if associate_openid and association_model is not None:
                for openid in request.session.get("openids", []):
                    assoc, created = UserOpenidAssociation.objects.get_or_create(user=form.user, openid=openid.openid)
                success_url = openid_success_url or success_url
            message = ugettext(u"Successfully logged in as %(user)s.") % {"user": user_display(form.user)}
            messages.add_message(request, messages.SUCCESS, message)
            extra_context["message"] = message
            if success_url is None:
                success_url = get_default_redirect(request, redirect_field_name)
            if request.is_ajax():
                extra_context["TEMPLATE"] = ""
                return extra_context
            return HttpResponseRedirect(success_url)
        else:
            extra_context["message"] = "Login failed"
    else:
        form = form_class(group=group)

    ctx = group_context(group, bridge)
    ctx.update(
        {
            "form": form,
            "url_required": url_required,
            "redirect_field_name": redirect_field_name,
            "redirect_field_value": request.GET.get(redirect_field_name),
            "TEMPLATE": template_name,
        }
    )
    ctx.update(extra_context)

    return ctx
Beispiel #23
0
 def login(self, request):
     if self.is_valid():
         login(request, self.user)
         request.user.message_set.create(
             message = ugettext(u"Successfully logged in as %(user)s.") % {
                 'user': user_display(self.user)
             }
         )
         if self.cleaned_data['remember']:
             request.session.set_expiry(60 * 60 * 24 * 7 * 3)
         else:
             request.session.set_expiry(0)
         return True
     return False
Beispiel #24
0
def update_kwargs(key, request, **kwargs):
    WORDS = {"object-created": "created", "object-updated": "updated"}

    kwargs.update({"user": user_display(request.user)})
    if "model" in kwargs:
        model = kwargs.pop("model")
        kwargs.update({
            "article": pgettext(model._meta.module_name, "the "),
            "verbose_name": model._meta.verbose_name
        })
        if key in WORDS:
            word = WORDS[key]
            kwargs.update({word: pgettext(model._meta.module_name, word)})
    return kwargs
Beispiel #25
0
    def get_context_data(self, **kwargs):
        history = self.page_user.content_set.public().prefetch_related(
            "author__reputation", "items")
        fwers_ids = Follow.objects.get_follows(self.page_user).values_list(
            "user_id", flat=True)
        obj_fwed = Follow.objects.filter(user=self.page_user)
        fwees_ids = obj_fwed.values_list("target_user_id", flat=True)
        items_fwed_ids = obj_fwed.values_list("target_item_id", flat=True)

        empty_msg = _("%(page_user_display)s have not contributed yet.") % {
            "page_user_display": user_display(self.page_user)
        }

        context = super(ProfileDetailView, self).get_context_data(**kwargs)
        followers = User.objects.filter(pk__in=fwers_ids)
        followees = User.objects.filter(pk__in=fwees_ids)
        scores, votes = history.get_scores_and_votes(self.request.user, True)
        context.update({
            "empty_msg":
            empty_msg,
            "reputation":
            self.page_user.reputation,
            "fwers":
            followers.order_by("-reputation__reputation_incremented"),
            "fwees":
            followees.order_by("-reputation__reputation_incremented"),
            "items_fwed":
            Item.objects.filter(pk__in=items_fwed_ids),
            "scores":
            scores,
            "votes":
            votes,
        })

        # Next step would be to be able to "merge" the get_context_data of both
        # DetailView (SingleObjectMixin) and MultipleObjectMixin
        m = MultipleObjectMixin()
        m.request = self.request
        m.kwargs = self.kwargs
        m.paginate_by = self.paginate_by

        history = history.select_subclasses()
        context.update(m.get_context_data(object_list=history))

        return context
Beispiel #26
0
def signup(request, **kwargs):

    form_class = kwargs.pop("form_class", SignupForm)
    template_name = kwargs.pop("template_name", "account/signup.html")
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)

    group, bridge = group_and_bridge(kwargs)

    if success_url is None:
        success_url = get_default_redirect(request, redirect_field_name)

    if request.method == "POST":
        form = form_class(request.POST, group=group)
        if form.is_valid():
            credentials = form.save(request=request)
            if settings.ACCOUNT_EMAIL_VERIFICATION:
                return render_to_response(
                    "account/verification_sent.html",
                    {"email": form.cleaned_data["email"]},
                    context_instance=RequestContext(request),
                )
            else:
                user = authenticate(**credentials)
                auth_login(request, user)
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    ugettext("Successfully logged in as %(user)s.") % {"user": user_display(user)},
                )
                return HttpResponseRedirect(success_url)
    else:
        form = form_class(group=group)

    ctx = group_context(group, bridge)
    ctx.update(
        {
            "form": form,
            "redirect_field_name": redirect_field_name,
            "redirect_field_value": request.GET.get(redirect_field_name),
        }
    )

    return render_to_response(template_name, RequestContext(request, ctx))
Beispiel #27
0
 def form_valid(self, form):
     email_confirmed = False
     new_user = self.create_user(form, commit=False)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED:
         new_user.is_active = False
     new_user.save()
     self.create_account(new_user, form)
     email_kwargs = {"primary": True}
     if self.signup_code:
         self.signup_code.use(new_user)
         if self.signup_code.email and new_user.email == self.signup_code.email:
             email_kwargs["verified"] = True
             email_confirmed = True
     EmailAddress.objects.add_email(new_user, new_user.email, **email_kwargs)
     self.after_signup(new_user, form)
     if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_confirmed:
         response_kwargs = {
             "request": self.request,
             "template": self.template_name_email_confirmation_sent,
             "context": {
                 "email": new_user.email,
                 "success_url": self.get_success_url(),
             }
         }
         return self.response_class(**response_kwargs)
     else:
         if self.messages.get("email_confirmation_sent") and not email_confirmed:
             messages.add_message(
                 self.request,
                 self.messages["email_confirmation_sent"]["level"],
                 self.messages["email_confirmation_sent"]["text"] % {
                     "email": form.cleaned_data["email"]
                 }
             )
         self.login_user(new_user)
         if self.messages.get("logged_in"):
             messages.add_message(
                 self.request,
                 self.messages["logged_in"]["level"],
                 self.messages["logged_in"]["text"] % {
                     "user": user_display(new_user)
                 }
             )
     return redirect(self.get_success_url())
Beispiel #28
0
def mixpanel(request):
    user = request.user
    if user.is_authenticated():
        profile = user.get_profile()
        data = {
            "userId": user.id,
            "email": user.email,
            "bio": profile.about,
            "created": user.date_joined,
            "name": user_display(profile),
            "reputation": user.reputation.reputation_incremented
        }
    else:
        data = {"userId": 0}
    user = json.dumps(data, cls=DjangoJSONEncoder).replace("\\r",
                                                           "\\\\r").replace(
                                                               "\\n", "\\\\n")
    output = {"MIXPANEL_KEY_ID": settings.MIXPANEL_KEY_ID, "user_json": user}
    return output
Beispiel #29
0
    def test_post_successful(self):
        qs = User.objects.filter(email="*****@*****.**")
        if qs:
            qs.delete()
        post = {
            "email": "*****@*****.**",
            "password": "******",
            "password_confirm": "pwd",
            "profile_name": "bob"
        }
        request = self.factory.post(reverse("account_signup"), post)
        request.user = AnonymousUser()

        # workaround bug in django 1.4
        from django.contrib.messages.storage.fallback import FallbackStorage
        setattr(request, 'session', self.session)
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = SignupEnabledView.as_view()(request)
        self.assertEqual(response.status_code, 302)
        user = User.objects.get(email="*****@*****.**")
        self.assertEqual(user_display(user), "bob")
        user.delete()
Beispiel #30
0
 def label_from_instance(self, obj):
     return user_display(obj)
    def do_register(self, request, message=None):
        """
        do_register implementation is copied from django-openid so we can
        ensure Pinax functionality in OpenID registration. django-openid
        didn't quite give enough hooks.
        
        This implementation modifies the POST case and will not run
        create_user, confirm_email_step or on_registration_complete hooks.
        """
        # Show a registration / signup form, provided the user is not
        # already logged in
        if not request.user.is_anonymous():
            return self.show_already_signed_in(request)

        openid_url = request.POST.get("openid_url")
        openids = request.session.get("openids")

        if not openid_url and not openids:
            return account_login(request,
                                 url_required=True,
                                 extra_context={
                                     "openid_login": True,
                                 })

        # perform OpenID login if openid_url is defined. we do this before the
        # check to ACCOUNT_OPEN_SIGNUP to allow users who have existing OpenID
        # association to login even when ACCOUNT_OPEN_SIGNUP is turned off.
        if openid_url:
            return self.start_openid_process(
                request,
                user_url=openid_url,
                on_complete_url=urlparse.urljoin(request.path,
                                                 "../register_complete/"),
                trust_root=urlparse.urljoin(request.path, ".."))

        if not settings.ACCOUNT_OPEN_SIGNUP:
            return render_to_response("django_openid/registration_closed.html",
                                      {},
                                      context_instance=RequestContext(request))

        RegistrationForm = self.get_registration_form_class(request)

        try:
            openid = request.openid and request.openid.openid or None
        except AttributeError:
            return self.show_error(
                request, "Add CookieConsumer or similar to your middleware")

        if request.method == "POST":
            # TODO: The user might have entered an OpenID as a starting point,
            # or they might have decided to sign up normally
            form = RegistrationForm(
                request.POST,
                openid=openid,
                reserved_usernames=self.reserved_usernames,
                no_duplicate_emails=self.no_duplicate_emails)
            if form.is_valid():
                # Pinax modification
                user = form.save(request=request)
                if openid:
                    user.openids.create(openid=openid)
                if settings.ACCOUNT_EMAIL_VERIFICATION:
                    return render_to_response(
                        "account/verification_sent.html", {
                            "email": form.cleaned_data["email"],
                        },
                        context_instance=RequestContext(request))
                else:
                    # form.login is the same implementation used in normal
                    # signup. hopefully this doesn't bite us later.
                    self.log_in_user(request, user)
                    messages.add_message(
                        request, messages.SUCCESS,
                        ugettext("Successfully logged in as %(user)s.") %
                        {"user": user_display(user)})
                    # @@@ honor custom redirect more fully (this is used primarily for
                    # the default fallback)
                    if hasattr(settings, "SIGNUP_REDIRECT_URLNAME"):
                        fallback_url = reverse(
                            settings.SIGNUP_REDIRECT_URLNAME)
                    else:
                        if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
                            fallback_url = reverse(
                                settings.LOGIN_REDIRECT_URLNAME)
                        else:
                            fallback_url = settings.LOGIN_REDIRECT_URL
                    success_url = get_default_redirect(
                        request, fallback_url, self.redirect_field_name)
                    return HttpResponseRedirect(success_url)
        else:
            form = RegistrationForm(
                initial=request.openid
                and self.initial_from_sreg(request.openid.sreg) or {},
                openid=openid,
                reserved_usernames=self.reserved_usernames,
                no_duplicate_emails=self.no_duplicate_emails)

        return self.render(
            request, self.register_template, {
                "form":
                form,
                "message":
                message,
                "openid":
                request.openid,
                "logo":
                self.logo_path or (urlparse.urljoin(request.path, "../logo/")),
                "no_thanks":
                self.sign_next(request.path),
                "action":
                request.path,
            })
Beispiel #32
0
 def label_from_instance(self, obj):
     return user_display(obj)
Beispiel #33
0
 def get_owner_name(self, obj):
     return user_display(obj.owner)
Beispiel #34
0
 def get_display_name(self, obj):
     return user_display(obj)
Beispiel #35
0
def profile(request):
    result = {}
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        result.update({"PROFILE": profile, "USERNAME": user_display(profile)})
    return result
 def do_register(self, request, message=None):
     """
     do_register implementation is copied from django-openid so we can
     ensure Pinax functionality in OpenID registration. django-openid
     didn't quite give enough hooks.
     
     This implementation modifies the POST case and will not run
     create_user, confirm_email_step or on_registration_complete hooks.
     """
     # Show a registration / signup form, provided the user is not
     # already logged in
     if not request.user.is_anonymous():
         return self.show_already_signed_in(request)
     
     openid_url = request.POST.get("openid_url")
     openids = request.session.get("openids")
     
     if not openid_url and not openids:
         return account_login(request, url_required=True, extra_context={
             "openid_login": True,
         })
     
     # perform OpenID login if openid_url is defined. we do this before the
     # check to ACCOUNT_OPEN_SIGNUP to allow users who have existing OpenID
     # association to login even when ACCOUNT_OPEN_SIGNUP is turned off.
     if openid_url:
         return self.start_openid_process(request,
             user_url = openid_url,
             on_complete_url = urlparse.urljoin(
                 request.path, "../register_complete/"
             ),
             trust_root = urlparse.urljoin(request.path, "..")
         )
     
     if not settings.ACCOUNT_OPEN_SIGNUP:
         return render_to_response("django_openid/registration_closed.html", {
         }, context_instance=RequestContext(request))
     
     RegistrationForm = self.get_registration_form_class(request)
     
     try:
         openid = request.openid and request.openid.openid or None
     except AttributeError:
         return self.show_error(
             request, "Add CookieConsumer or similar to your middleware"
         )
     
     if request.method == "POST":
         # TODO: The user might have entered an OpenID as a starting point,
         # or they might have decided to sign up normally
         form = RegistrationForm(
             request.POST,
             openid = openid,
             reserved_usernames = self.reserved_usernames,
             no_duplicate_emails = self.no_duplicate_emails
         )
         if form.is_valid():
             # Pinax modification
             user = form.save(request=request)
             if openid:
                 user.openids.create(openid=openid)
             if settings.ACCOUNT_EMAIL_VERIFICATION:
                 return render_to_response("account/verification_sent.html", {
                     "email": form.cleaned_data["email"],
                 }, context_instance=RequestContext(request))
             else:
                 # form.login is the same implementation used in normal
                 # signup. hopefully this doesn't bite us later.
                 self.log_in_user(request, user)
                 messages.add_message(request, messages.SUCCESS,
                     ugettext("Successfully logged in as %(user)s.") % {
                         "user": user_display(user)
                     }
                 )
                 # @@@ honor custom redirect more fully (this is used primarily for
                 # the default fallback)
                 if hasattr(settings, "SIGNUP_REDIRECT_URLNAME"):
                     fallback_url = reverse(settings.SIGNUP_REDIRECT_URLNAME)
                 else:
                     if hasattr(settings, "LOGIN_REDIRECT_URLNAME"):
                         fallback_url = reverse(settings.LOGIN_REDIRECT_URLNAME)
                     else:
                         fallback_url = settings.LOGIN_REDIRECT_URL
                 success_url = get_default_redirect(request, fallback_url, self.redirect_field_name)
                 return HttpResponseRedirect(success_url)
     else:
         form = RegistrationForm(
             initial = request.openid and self.initial_from_sreg(
                 request.openid.sreg
             ) or {},
             openid = openid,
             reserved_usernames = self.reserved_usernames,
             no_duplicate_emails = self.no_duplicate_emails
         )
     
     return self.render(request, self.register_template, {
         "form": form,
         "message": message,
         "openid": request.openid,
         "logo": self.logo_path or (urlparse.urljoin(
             request.path, "../logo/"
         )),
         "no_thanks": self.sign_next(request.path),
         "action": request.path,
     })