예제 #1
0
def file(request):
    form = FilesForm(None, None, request.POST)
    if not form.is_valid():
        return HttpResponse("Something wrong with submitted form.")
    stuff = cache.get(form.cleaned_data['key'])
    cache.delete(form.cleaned_data['key'])
    if not stuff:
        return HttpResponse("You have submitted invalid or expired form.")
    form = FilesForm(
        {
            'filenames': stuff[0]['filenames'],
            'dirnames': stuff[0]['dirnames']
        }, None, request.POST)
    if not form.is_valid():
        return HttpResponse("You have submitted invalid or expired form.")
    lst = [
        int(f.split('_')[1]) for f in form.cleaned_data.iterkeys()
        if form.cleaned_data[f] == True
    ]
    if len(lst) == 0:
        return HttpResponseRedirect('/tq/')
    result = []
    items = stuff[0]['dirnames'] + stuff[0]['filenames']
    con, cur = _connect()
    for n in lst:
        if type(items[n]) in [unicode, str]:
            result += _ls(
                cur,
                request.user.username,
                items[n].split('%s/%s' %
                               (FTP_HOMEDIR, request.user.username))[1],
                walk=True)
        else:
            result.append(items[n])
    con.close()
    if not result:
        return HttpResponseRedirect('/tq/')
    fnames = [f.name for f in result]
    q = Queue.objects.filter(file__in=fnames)
    for i in result[:]:
        if i.name in [j.file for j in q]:
            result.remove(i)
    for f in result:
        e = Queue(status='pending')
        e.user = request.user
        e.file = f.name
        e.attrs['obj'] = f
        e.save()
    return HttpResponseRedirect('/tq/')
def logout(request):
    from django.contrib.auth import logout
    logout(request)
    cache.delete(
        str('ulc-%s' %
            request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)))
    return HttpResponseRedirect(post_redirect(request))
예제 #3
0
def new(request):
    if request.method == 'GET':
        if not request.user.is_staff and request.user.attrs.has_key(
                'posts_today'):
            if request.user.attrs['posts_today'] >= NUMBER_OF_POSTS_PER_DAY:
                return render_to_response(
                    'add.html', {
                        'message':
                        _("You can write only %s posts per day" %
                          NUMBER_OF_POSTS_PER_DAY),
                    },
                    context_instance=RequestContext(request))
        form = TopicForm()
        return render_to_response('add.html', {
            'form': form,
        },
                                  context_instance=RequestContext(request))
    form = TopicForm(request.POST, request.FILES)
    form.instance.author = request.user
    if form.is_valid():
        inst_id = form.save()
        return HttpResponseRedirect('/edit/%s/' % inst_id)
    else:
        return render_to_response('add.html', {
            'form': form,
        },
                                  context_instance=RequestContext(request))
예제 #4
0
def add(request):
    form = TQForm(None, None, request.POST)
    if not form.is_valid():
        return HttpResponse("You've submitted invalid or expired form.")
    stuff = cache.get(form.cleaned_data['key'])
    cache.delete(form.cleaned_data['key'])
    if not stuff:
        return HttpResponse("You've submitted invalid or expired form.")
    form = TQForm(Queue.objects.filter(pk__in=stuff), None, request.POST)
    if form.is_valid():
        s = [
            int(f.split('_')[1]) for f in form.cleaned_data.iterkeys()
            if form.cleaned_data[f] and f != 'key'
        ]
        if s:
            for q in Queue.objects.filter(pk__in=[stuff[i] for i in s]):
                q.order = form.cleaned_data['q_%d' % stuff.index(q.id)][:9]
                try:
                    the_id = int(form.cleaned_data['t_%d' % stuff.index(q.id)])
                except ValueError:
                    the_id = 0
                if the_id:
                    t = Topic.objects.filter(id=the_id)
                    if t:
                        q.topic = t[0]
                q.save()
    return HttpResponseRedirect('/tq/')
def register(request,
             success_url='/signup/complete/',
             profile_callback=None,
             template_name='users/registration_form.html'):
    """
    Allows a new user to register an account.
    Following successful registration, redirects to either
    ``/signup/complete/`` or, if supplied, the URL
    specified in the keyword argument ``success_url``.

    `RegistrationFormUniqueEmail`` must have a method ``save``
    which will create and return the new ``User``, and that
    method must accept the keyword argument ``profile_callback``
    
    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.
    """
    if request.user.is_authenticated():
        logout(request)
    from users.forms import RegistrationFormUniqueEmail
    from users.models import RegistrationProfile
    if request.method == 'POST':
        form = RegistrationFormUniqueEmail(request.POST)
        if form.is_valid():
            new_user = form.save(activate=settings.ACTIVATION_ENABLED,
                                 profile_callback=profile_callback)
            if settings.ACTIVATION_ENABLED:
                return HttpResponseRedirect(success_url)
            else:
                login_without_password(request, new_user)
                return HttpResponseRedirect(success_url)
        return render_to_response(template_name, {
            'form': form,
        },
                                  context_instance=RequestContext(request))
    else:
        form = RegistrationFormUniqueEmail()
    return render_to_response(template_name, {
        'form': form,
    },
                              context_instance=RequestContext(request))
 def save(self):
     try:
         send_mail(self.cleaned_data['subject'],
                   self.cleaned_data['body'],
                   self.cleaned_data['email'],
                   [settings.CONTACT_FORM_EMAIL],
                   fail_silently=False)
     except BadHeaderError:
         return HttpResponse('Invalid header found.')
     return HttpResponseRedirect('/contact/thanks/')
def post_personal(request):
    forms = _profile_forms(request)
    form = PersonalForm(request.POST, request.FILES, instance=request.user)
    if form.is_valid():
        form.save()
    forms['personal'] = form
    if request.POST.has_key('redirect'):
        return HttpResponseRedirect(request.POST['redirect'])
    return render_to_response('users/profile_form.html',
                              forms,
                              context_instance=RequestContext(request))
def change_openid(request):
    forms = _profile_forms(request)
    form = forms['openid'].__class__(request.session, request.POST)
    forms['openid'] = form
    if form.is_valid():
        after_auth_redirect = form.auth_redirect(
            post_redirect(request), 'users.views.change_openid_complete',
            request.user.id)
        return HttpResponseRedirect(after_auth_redirect)
    return render_to_response('users/profile_form.html',
                              forms,
                              context_instance=RequestContext(request))
def chpw(request, key=None, template_name='users/chpw_req.html'):
    from users.forms import PasswordChangeRequestForm, PasswordChangeForm
    if not key:
        form = PasswordChangeRequestForm(request.POST)
    else:
        form = PasswordChangeForm(key, request.POST)
    if request.method == 'POST':
        if form.is_valid():
            if not key:
                user = form.cleaned_data['username'] or \
                    form.cleaned_data['email']
                if not user:
                    return render_to_response(
                        template_name, {
                            'form':
                            form,
                            'error_message':
                            _(u'Please specify valid Username or E-mail.'),
                        },
                        context_instance=RequestContext(request))
                form.save(user)
                return HttpResponseRedirect('/chpw_urlsent/')
            else:
                form.save(form.cleaned_data['user'], form.cleaned_data['pwd'])
                return HttpResponseRedirect('/chpw_done/')
        else:
            return render_to_response(template_name, {
                'form': form,
            },
                                      context_instance=RequestContext(request))
    else:
        if not key:
            form = PasswordChangeRequestForm()
        else:
            form = PasswordChangeForm(key)
        return render_to_response(template_name, {
            'form': form,
        },
                                  context_instance=RequestContext(request))
def authForLoginForm(request):
    from django.contrib.auth import authenticate, login
    form = LoginForm(request.POST)
    if form.is_valid():
        user = authenticate(username=form.cleaned_data['username'],
                            password=form.cleaned_data['password'])
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(post_redirect(request))
    return render_to_response('users/auth.html', {
        'form': form,
        'redirect': post_redirect(request),
    },
                              context_instance=RequestContext(request))
def auth(request):
    from django.contrib.auth import authenticate, login
    user = authenticate(session=request.session, query=request.GET)
    return_to = 'http://%s%s' % (request.get_host(), request.path)
    user = authenticate(session=request.session,
                        query=request.GET,
                        return_to=return_to)
    if not user:
        return HttpResponseForbidden('Authentication error')
    login(request, user)
    cache.delete(
        str('ulc-%s' %
            request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)))
    return HttpResponseRedirect(request.GET.get('redirect', '/'))
예제 #12
0
def get_torrent(request, the_id):
    from users.views import login
    import base64
    from benc import bdecode, bencode
    if not OPEN_TRACKER:
        if not request.user.is_authenticated():
            return HttpResponseRedirect(
                reverse(login) + '?redirect=' + request.path)
    torrent = get_object_or_404(Torrent, pk=the_id)
    content = base64.b64decode(torrent.info)
    content = bdecode(content)
    if not OPEN_TRACKER:
        content['announce'] += "?passkey=%s" % request.user.passkey
    content = bencode(content)
    response = HttpResponse(content, mimetype='application/x-bittorrent')
    response["Content-Length"] = len(content)
    response[
        "Content-Disposition"] = "attachment; filename=\"%s\"" % torrent.fn
    return response
def login(request):
    if request.user.is_authenticated():
        logout(request)
    if request.method == 'POST':
        form = AuthForm(request.session, request.POST)
        if request.POST.has_key('this_is_the_login_form'):
            return authForLoginForm(request)
        if form.is_valid():
            if request.POST.has_key('openid_url'):
                if len(request.POST['openid_url']) > 0:
                    after_auth_redirect = form.auth_redirect(
                        post_redirect(request), 'users.views.auth')
                    return HttpResponseRedirect(after_auth_redirect)
        redirect = post_redirect(request)
    else:
        form = AuthForm(request.session)
        redirect = request.GET.get('redirect', '/')
    return render_to_response('users/auth.html', {
        'form': form,
        'redirect': redirect,
    },
                              context_instance=RequestContext(request))
예제 #14
0
def edit(request, the_id):
    topic = get_object_or_404(Topic, pk=the_id)
    if not request.user == topic.author:
        return HttpResponseForbidden('Permission denied')
    if topic.approved and settings.CENSORSHIP:
        return HttpResponseForbidden(
            'This post approved by moderator and you cannot change it.')
    if request.method == 'POST':
        form = TopicEditForm(request.POST, request.FILES, instance=topic)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/~%s/%s/' %
                                        (topic.author.username, topic.slug))
        return render_to_response('edit.html', {
            'form': form,
            'post': topic,
        },
                                  context_instance=RequestContext(request))
    form = TopicEditForm(instance=topic)
    return render_to_response('edit.html', {
        'form': form,
        'post': topic,
    })
def chpw_done(request, template_name='users/chpw_done.html'):
    return HttpResponseRedirect(post_redirect(request))
def change_openid_complete(request):
    from django.contrib.auth import authenticate
    user = authenticate(session=request.session, query=request.GET)
    if not user:
        return HttpResponseForbidden('Authorization error')
    return HttpResponseRedirect(request.GET.get('redirect', '/'))
def read_hcard(request):
    from users.models import read_hcard
    read_hcard(request.user)
    request.user.save()
    return HttpResponseRedirect('../')
 def wrapper(request, *args, **kwargs):
     if not request.user.is_authenticated():
         return HttpResponseRedirect(
             reverse(login) + '?redirect=' + request.path)
     return func(request, *args, **kwargs)
def leave_message(request, the_id=None):
    if request.method == 'GET':
        if the_id:
            try:
                the_id = int(the_id)
            except ValueError:
                raise Http404
        else:
            raise Http404
        rcpt = User.objects.filter(pk=the_id)
        if not rcpt: raise Http404
        rcpt = rcpt[0]
        form = MessageForm()
        return render_to_response("users/leave_message.html", {
            'user': request.user,
            'rcpt': rcpt,
            'form': form,
        },
                                  context_instance=RequestContext(request))
    elif request.method == 'POST':
        if request.POST.has_key('xhr'):
            r = HttpResponse(mimetype="text/xml")
            r.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")

            def fail():
                r.write("<result><msg>failure</msg></result>")
                return r
        else:

            def fail():
                raise Http404

        if request.POST.has_key('rcpt'):
            try:
                rcpt = int(request.POST['rcpt'])
            except ValueError:
                return fail()

            rcpt = User.objects.filter(pk=rcpt)
            if not rcpt:
                return fail()
            rcpt = rcpt[0]
        else:
            return fail()
        form = MessageForm(request.POST)
        if form.is_valid():
            form.save(request, rcpt)
            if request.user.attrs.has_key('sent_messages'):
                request.user.attrs['sent_messages'] += 1
            else:
                request.user.attrs['sent_messages'] = 1
            request.user.save()
            if rcpt.attrs.has_key('inbox'):
                rcpt.attrs['inbox'] += 1
            else:
                rcpt.attrs['inbox'] = 1
            rcpt.save()
            if request.POST.has_key('xhr'):
                r.write("<result><msg>success</msg></result>")
                return r
            return HttpResponseRedirect('/messages/sent/')
        if request.POST.has_key('xhr'):
            r.write("<result><msg>failure</msg></result>")
            return r
        return render_to_response("users/leave_message.html", {
            'user': request.user,
            'form': form,
        },
                                  context_instance=RequestContext(request))
    raise Http404