예제 #1
0
    def create_form(self):
        """Create provider form method

        :return form
        """
        if self.create_form_mod is not None:
            return load_module(self.create_form_mod)
        try:
            return load_module(self.form_mod)
        except AttributeError:
            raise ImproperlyConfigured(
                _("Setup form_mod attributes at first."))
예제 #2
0
파일: api.py 프로젝트: spicycms/spicy.core
    def create_form(self):
        """Create provider form method

        :return form
        """
        if self.create_form_mod is not None:
            return load_module(self.create_form_mod)
        try:
            return load_module(self.form_mod)
        except AttributeError:
            raise ImproperlyConfigured(
                _("Setup form_mod attributes at first."))
예제 #3
0
    def register(self, request):
        status = 'error'
        message = ''
        real_ip = request.META.get('REMOTE_ADDR')
        is_blacklisted = real_ip and models.BlacklistedIP.objects.filter(
            ip=real_ip).exists()

        if request.user.is_authenticated():
            redirect = request.REQUEST.get(
                REDIRECT_FIELD_NAME, request.session.get(REDIRECT_FIELD_NAME))
            try:
                del request.session[REDIRECT_FIELD_NAME]
            except KeyError:
                pass

            if callable(defaults.DEFAULT_PROFILE_URL):
                user_redirect_uri = defaults.DEFAULT_PROFILE_URL(request.user)
            else:
                user_redirect_uri = defaults.DEFAULT_PROFILE_URL
            redirect = redirect or user_redirect_uri

            return dict(status='ok',
                        message=unicode(message),
                        redirect=redirect,
                        REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED)

        elif request.method == "POST":
            form = load_module(CUSTOM_USER_SIGNUP_FORM)(request.POST)
            redirect = reverse('profile:public:success-signup')
            if not is_blacklisted and form.is_valid():
                status = 'ok'
                new_profile = form.save(request=request,
                                        realhost=request.get_host(),
                                        next_url=request.session.get(
                                            REDIRECT_FIELD_NAME, '/'))
                request.session['profile_id'] = new_profile.pk
                request.session['profile_email'] = new_profile.email

        else:
            form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            request.session.set_test_cookie()

            # Display the login form and handle the login action.
            redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, '/')
            request.session[REDIRECT_FIELD_NAME] = redirect

        return dict(status=status,
                    message=unicode(message),
                    redirect=redirect,
                    form=form,
                    REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED,
                    errors=str(form.errors))
예제 #4
0
    def register(self, request):
        status = 'error'
        message = ''
        real_ip = request.META.get('REMOTE_ADDR')
        is_blacklisted = real_ip and models.BlacklistedIP.objects.filter(
            ip=real_ip).exists()

        if request.user.is_authenticated():
            redirect = request.REQUEST.get(
                REDIRECT_FIELD_NAME, request.session.get(REDIRECT_FIELD_NAME))
            try:
                del request.session[REDIRECT_FIELD_NAME]
            except KeyError:
                pass

            if callable(defaults.DEFAULT_PROFILE_URL):
                user_redirect_uri = defaults.DEFAULT_PROFILE_URL(request.user)
            else:
                user_redirect_uri = defaults.DEFAULT_PROFILE_URL
            redirect = redirect or user_redirect_uri

            return dict(status='ok',
                        message=unicode(message),
                        redirect=redirect,
                        REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED)

        elif request.method == "POST":
            form = load_module(CUSTOM_USER_SIGNUP_FORM)(request.POST)
            redirect = reverse('profile:public:success-signup')
            if not is_blacklisted and form.is_valid():
                status = 'ok'
                new_profile = form.save(
                    request=request, realhost=request.get_host(),
                    next_url=request.session.get(REDIRECT_FIELD_NAME, '/'))
                request.session['profile_id'] = new_profile.pk
                request.session['profile_email'] = new_profile.email

        else:
            form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            request.session.set_test_cookie()

            # Display the login form and handle the login action.
            redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, '/')
            request.session[REDIRECT_FIELD_NAME] = redirect

        return dict(
        status=status, message=unicode(message), redirect=redirect,
        form=form, REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED, errors=str(form.errors))
예제 #5
0
def edit(request, profile_id):
    """Handles edit requests, renders template according `action`
    get parameter

    """
    message = None
    action = request.GET.get('action')
    profile = get_object_or_404(Profile, id=profile_id)
    ProfileForm = utils.load_module(defaults.ADMIN_EDIT_PROFILE_FORM)

    if action == 'new':
        message = _('New account created, welcome to editing.')

    if (request.method == 'POST' and request.user.has_perm(
            'profile.change_profile')):
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            message = settings.MESSAGES['success']
        else:
            message = settings.MESSAGES['error']
    else:
        form = ProfileForm(instance=profile)

    passwd_form = forms.AdminPasswdForm(profile)

    return {
        'action': action, 'instance': profile, 'form': form,
        'passwd_form': passwd_form, 'message': message,
        'services': api.register.get_list(consumer=profile), 'tab': 'edit'}
예제 #6
0
def edit(request, profile_id):
    """Handles edit requests, renders template according `action`
    get parameter

    """
    message = None
    action = request.GET.get('action')
    profile = get_object_or_404(Profile, id=profile_id)
    ProfileForm = utils.load_module(defaults.ADMIN_EDIT_PROFILE_FORM)

    if action == 'new':
        message = _('New account created, welcome to editing.')

    if (request.method == 'POST'
            and request.user.has_perm('profile.change_profile')):
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            message = settings.MESSAGES['success']
        else:
            message = settings.MESSAGES['error']
    else:
        form = ProfileForm(instance=profile)

    passwd_form = forms.AdminPasswdForm(profile)

    return {
        'action': action,
        'instance': profile,
        'form': form,
        'passwd_form': passwd_form,
        'message': message,
        'services': api.register.get_list(consumer=profile),
        'tab': 'edit'
    }
예제 #7
0
def backend_factory(setting, class_name, delegate_methods=()):
    bases = ()
    backends = []
    from spicy.utils import load_module
    for backend in setting:
        backend_class = load_module(backend + '.' + class_name)
        if backend_class:
            bases += (backend_class, )
            backends.append(backend_class)

    def delegate_method(name):
        def _inner(self, *args, **kwargs):
            for backend in self.backends:
                try:
                    getattr(backend, name)(self, *args, **kwargs)
                except AttributeError:
                    pass

        return _inner

    attrs = dict(backends=backends, __module__=__name__)
    for method in delegate_methods:
        attrs[method] = delegate_method(method)

    class Meta:
        abstract = True
    attrs['Meta'] = Meta

    return type('DynamicBackend' + class_name, bases, attrs)
예제 #8
0
def backend_factory(setting, class_name, delegate_methods=()):
    bases = ()
    backends = []
    from spicy.utils import load_module
    for backend in setting:
        backend_class = load_module(backend + '.' + class_name)
        if backend_class:
            bases += (backend_class, )
            backends.append(backend_class)

    def delegate_method(name):
        def _inner(self, *args, **kwargs):
            for backend in self.backends:
                try:
                    getattr(backend, name)(self, *args, **kwargs)
                except AttributeError:
                    pass

        return _inner

    attrs = dict(backends=backends, __module__=__name__)
    for method in delegate_methods:
        attrs[method] = delegate_method(method)

    class Meta:
        abstract = True

    attrs['Meta'] = Meta

    return type('DynamicBackend' + class_name, bases, attrs)
예제 #9
0
파일: api.py 프로젝트: spicycms/spicy.core
    def add(self, path_to_srv_interface):
        service = load_module(path_to_srv_interface)

        if not issubclass(service, Interface):
            raise WrongServiceAPI(
                'You must inherit services.Interface at first.')

        # Tested - works.
        if service.name in self:
            return

        try:
            service_instance = service()
            service_instance[
                'GENERIC_CONSUMER'].model.service = service_instance
            self[service.name] = service_instance
            if settings.DEBUG:
                print_success(
                    'Initialize [%s] service %s compatible with '
                    'consumer_types: %s' % (
                        service.name, service_instance,
                        service_instance.print_schema()))
        except Exception:
            print_error('Error while initialize service %s\n' % service.name)
            print_text(traceback.format_exc())
예제 #10
0
def edit(request, doc_id):
    messages = ''

    doc = get_object_or_404(DocumentModel, pk=doc_id)
    if not request.user.is_staff:  # and can edit documents
        if doc.owner != request.user:
            raise PermissionDenied()

    Form = load_module(defaults.EDIT_DOCUMENT_FORM)
    if request.method == 'POST':
        form = Form(request.POST, request.FILES, instance=doc)
        if form.is_valid():
            doc = form.save()
            doc.set_preview_quality()
            doc.set_preview2_quality()
            form = Form(instance=doc)
    else:
        form = Form(instance=doc)

    user = doc.owner
    if not doc.owner_id:
        user = request.user

    return dict(messages=messages,
                user=user,
                form=form,
                instance=doc,
                tab='doc')
예제 #11
0
    def collect(self):
        """
        Perform the bulk of the work of collectstatic.

        Split off from handle_noargs() to facilitate testing.
        """
        if self.symlink:
            if sys.platform == 'win32':
                raise CommandError("Symlinking is not supported by this "
                                   "platform (%s)." % sys.platform)
            if not self.local:
                raise CommandError("Can't symlink to a remote destination.")

        if self.clear:
            self.clear_dir('')

        if self.symlink:
            handler = self.link_file
        else:
            handler = self.copy_file

        found_files = SortedDict()
        for theme_path, theme in utils.get_siteskin_themes():
            for finder_path in settings.STATICFILES_FINDERS:
                finder = load_module(finder_path)(theme=theme)
                for path, storage in finder.list(self.ignore_patterns):
                    # Prefix the relative path if the source storage contains it
                    if getattr(storage, 'prefix', None):
                        prefixed_path = os.path.join(storage.prefix, path)
                    else:
                        prefixed_path = path

                    prefixed_path = os.path.join(theme, prefixed_path)

                    if prefixed_path not in found_files:
                        found_files[prefixed_path] = (storage, path)
                        handler(path, prefixed_path, storage)

        # Here we check if the storage backend has a post_process
        # method and pass it the list of modified files.
        if self.post_process and hasattr(self.storage, 'post_process'):
            processor = self.storage.post_process(found_files,
                                                  dry_run=self.dry_run)
            for original_path, processed_path, processed in processor:
                if processed:
                    self.log(u"Post-processed '%s' as '%s" %
                             (original_path, processed_path),
                             level=1)
                    self.post_processed_files.append(original_path)
                else:
                    self.log(u"Skipped post-processing '%s'" % original_path)

        return {
            'modified': self.copied_files + self.symlinked_files,
            'unmodified': self.unmodified_files,
            'post_processed': self.post_processed_files,
        }
예제 #12
0
    def collect(self):
        """
        Perform the bulk of the work of collectstatic.

        Split off from handle_noargs() to facilitate testing.
        """
        if self.symlink:
            if sys.platform == 'win32':
                raise CommandError("Symlinking is not supported by this "
                                   "platform (%s)." % sys.platform)
            if not self.local:
                raise CommandError("Can't symlink to a remote destination.")

        if self.clear:
            self.clear_dir('')

        if self.symlink:
            handler = self.link_file
        else:
            handler = self.copy_file

        found_files = SortedDict()
        for theme_path, theme in utils.get_siteskin_themes():
            for finder_path in settings.STATICFILES_FINDERS:
                finder = load_module(finder_path)(theme=theme)
                for path, storage in finder.list(self.ignore_patterns):
                    # Prefix the relative path if the source storage contains it
                    if getattr(storage, 'prefix', None):
                        prefixed_path = os.path.join(storage.prefix, path)
                    else:
                        prefixed_path = path

                    prefixed_path = os.path.join(theme, prefixed_path)

                    if prefixed_path not in found_files:
                        found_files[prefixed_path] = (storage, path)
                        handler(path, prefixed_path, storage)

        # Here we check if the storage backend has a post_process
        # method and pass it the list of modified files.
        if self.post_process and hasattr(self.storage, 'post_process'):
            processor = self.storage.post_process(found_files,
                                                  dry_run=self.dry_run)
            for original_path, processed_path, processed in processor:
                if processed:
                    self.log(u"Post-processed '%s' as '%s" %
                             (original_path, processed_path), level=1)
                    self.post_processed_files.append(original_path)
                else:
                    self.log(u"Skipped post-processing '%s'" % original_path)

        return {
            'modified': self.copied_files + self.symlinked_files,
            'unmodified': self.unmodified_files,
            'post_processed': self.post_processed_files,
        }
예제 #13
0
def new_feedback(request):
    """
    Render form for adding feedback to consumer with type and id.
    After adding feedback redirects to consumer absolute url
    """
    FeedbackForm = load_module(defaults.CUSTOM_FEEDBACK_FORM)

    if request.method == 'GET':
        from django.shortcuts import render
        return render(
            request,
            'spicy.core.simplepages/simplepages/feedback_create_lead.html')

    if request.method == 'POST':
        pattern = get_object_or_404(models.FeedbackPattern,
                                    slug=request.POST.get('pattern'))
        feedback = Feedback(pattern=pattern)
        form = FeedbackForm(request.POST, instance=feedback)

        if form.is_valid():
            if 'import requests' in request.session:
                del request.session['feedback_form']
            feedback = form.save(commit=False)

            feedback.ip_address = request.META['REMOTE_ADDR']
            if not (feedback.name.strip() or feedback.email.strip()
                    or feedback.phone.strip() or feedback.var1.strip()
                    or feedback.var2.strip() or feedback.var3.strip()
                    or feedback.message.strip()
                    or feedback.company_name.strip() or feedback.url.strip()):
                feedback.processing_status = defaults.SPAM
            feedback.save()

            signals.create_feedback.send(sender=feedback.__class__,
                                         request=request,
                                         feedback=feedback)

            if feedback.processing_status != defaults.SPAM:
                feedback.send_report()

            try:
                if defaults.SEND_AUTO_RESPONSE_WITHOUT_TIMEOUT:
                    feedback.send_to_customers(realhost=request.get_host())
            except Exception as e:
                return {'status': 'success', 'errors': e.message}

            return {'status': 'success'}
        else:
            request.session['feedback_form'] = request.POST
            return {'status': 'fail', 'errors': str(form.errors)}
    else:
        return http.HttpResponseNotAllowed(['POST'])
예제 #14
0
    def restore(self, request):
        message = ''
        RestorePasswordForm = load_module(defaults.RESTORE_PASSWORD_FORM)
        if request.method == 'POST':
            form = RestorePasswordForm(request.POST)
            if form.is_valid():
                profile = Profile.objects.get(
                    email__iexact=form.cleaned_data['email'])
                if 'send_pass' in request.POST:
                    newpass = generate_random_password()
                    profile.set_password(newpass)
                    profile.save()
                    profile.email_forgotten_passwd(newpass)

                    return dict(
                        form=form,
                        message=_(
                            'New password has been sent to you email address'))

                elif 'resend_activation' in request.POST:
                    if profile.check_activation():
                        return dict(
                            form=form,
                            message=_('Profile has been already activated'))
                    else:
                        try:
                            profile.generate_activation_key(
                                realhost=request.get_host(),
                                next_url=request.path)

                            message = _(
                                'New activation key has been sent to your '
                                'email address.')
                            return dict(form=form, message=message)

                        except Exception:
                            return dict(
                                form=form,
                                message=_(
                                    'Unable to send activation key, please '
                                    'try again later'))
            else:
                message = form.errors.as_text()
        else:
            if request.user.is_authenticated():
                form = RestorePasswordForm(
                    initial={'email': request.user.email})
            else:
                form = RestorePasswordForm()
        return dict(form=form, message=message)
예제 #15
0
def create(request):
    message = None
    CreateProfileForm = utils.load_module(defaults.ADMIN_CREATE_PROFILE_FORM)
    if request.method == 'POST':
        form = CreateProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(realhost=request.get_host())
            return HttpResponseRedirect('/admin/profile/%s/?action=new' %
                                        profile.id)
        else:
            message = settings.MESSAGES['error']
    else:
        form = CreateProfileForm(initial={'email_activation_key': True})
    return {'form': form, 'message': message}
예제 #16
0
    def restore(self, request):
        message = ''
        RestorePasswordForm = load_module(defaults.RESTORE_PASSWORD_FORM)
        if request.method == 'POST':
            form = RestorePasswordForm(request.POST)
            if form.is_valid():
                profile = Profile.objects.get(
                    email__iexact=form.cleaned_data['email'])
                if 'send_pass' in request.POST:
                    newpass = generate_random_password()
                    profile.set_password(newpass)
                    profile.save()
                    profile.email_forgotten_passwd(newpass)

                    return dict(
                        form=form,
                        message=_(
                            'New password has been sent to you email address'))

                elif 'resend_activation' in request.POST:
                    if profile.check_activation():
                        return dict(
                            form=form,
                            message=_('Profile has been already activated'))
                    else:
                        try:
                            profile.generate_activation_key(
                                realhost=request.get_host(),
                                next_url=request.path)

                            message = _(
                                'New activation key has been sent to your '
                                'email address.')
                            return dict(form=form, message=message)

                        except Exception:
                            return dict(
                                form=form,
                                message=_(
                                    'Unable to send activation key, please '
                                    'try again later'))
            else:
                message = form.errors.as_text()
        else:
            if request.user.is_authenticated():
                form = RestorePasswordForm(
                    initial={'email': request.user.email})
            else:
                form = RestorePasswordForm()
        return dict(form=form, message=message)
예제 #17
0
def create(request):
    message = None
    CreateProfileForm = utils.load_module(defaults.ADMIN_CREATE_PROFILE_FORM)
    if request.method == 'POST':
        form = CreateProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(realhost=request.get_host())
            return HttpResponseRedirect(
                '/admin/profile/%s/?action=new' % profile.id)
        else:
            message = settings.MESSAGES['error']
    else:
        form = CreateProfileForm(
            initial={'email_activation_key': True})
    return {
        'form': form,
        'message': message}
예제 #18
0
    def _get_redirect(self, request):
        redirect = request.GET.get(
            REDIRECT_FIELD_NAME,
            request.session.get(REDIRECT_FIELD_NAME,
                                request.session.get('newuser-next', '')))
        try:
            del request.session[REDIRECT_FIELD_NAME]
        except KeyError:
            pass

        if callable(defaults.DEFAULT_PROFILE_URL):
            user_redirect_uri = defaults.DEFAULT_PROFILE_URL(request.user)
        elif isinstance(defaults.DEFAULT_PROFILE_URL, basestring):
            user_redirect_uri = load_module(defaults.DEFAULT_PROFILE_URL)(
                request.user)
        else:
            user_redirect_uri = defaults.DEFAULT_PROFILE_URL
        redirect = redirect or user_redirect_uri
        return redirect
예제 #19
0
def backend_data(pattern, backends_list, backend_name=None):
    backend_modules = [load_module(backend) for backend in backends_list]
    backends = [(backend.get_admin_form()[0], backend.__name__.rsplit('.',
                                                                      1)[-1])
                for backend in backend_modules
                if hasattr(backend, 'get_admin_form')]
    if backend_name:
        for backend in backend_modules:
            if backend.__name__.rsplit('.', 1)[-1] == backend_name:
                tab = backend_name

                title, Form = backend.get_admin_form()
                break
        else:
            backend = None
    else:
        Form = forms.PatternForm
        tab = 'edit'
        title = _('Edit pattern: %s') % pattern
    return locals()
예제 #20
0
    def _get_redirect(self, request):
        redirect = request.GET.get(
            REDIRECT_FIELD_NAME,
            request.session.get(
                REDIRECT_FIELD_NAME,
                request.session.get('newuser-next', '')))
        try:
            del request.session[REDIRECT_FIELD_NAME]
        except KeyError:
            pass

        if callable(defaults.DEFAULT_PROFILE_URL):
            user_redirect_uri = defaults.DEFAULT_PROFILE_URL(request.user)
        elif isinstance(defaults.DEFAULT_PROFILE_URL, basestring):
            user_redirect_uri = load_module(defaults.DEFAULT_PROFILE_URL)(
                request.user)
        else:
            user_redirect_uri = defaults.DEFAULT_PROFILE_URL
        redirect = redirect or user_redirect_uri
        return redirect
예제 #21
0
def create(request):
    message = ''

    Form = load_module(defaults.CREATE_DOCUMENT_FORM)

    if request.method == 'POST':
        form = Form(request.POST, request.FILES)
        if form.is_valid():
            doc = form.save()
            doc.site.add(Site.objects.get_current())
            return http.HttpResponseRedirect(
                reverse('document:admin:edit', args=[doc.pk]))
        else:
            message = u'Form validation Error: {}'.format(
                form.errors.as_text())

    else:
        form = Form(initial={
            'pub_date': dt.datetime.now(),
            'owner': request.user
        })

    return dict(user=request.user, form=form, message=message)
예제 #22
0
    def add(self, path_to_srv_interface):
        service = load_module(path_to_srv_interface)

        if not issubclass(service, Interface):
            raise WrongServiceAPI(
                'You must inherit services.Interface at first.')

        # Tested - works.
        if service.name in self:
            return

        try:
            service_instance = service()
            service_instance[
                'GENERIC_CONSUMER'].model.service = service_instance
            self[service.name] = service_instance
            if settings.DEBUG:
                print_success('Initialize [%s] service %s compatible with '
                              'consumer_types: %s' %
                              (service.name, service_instance,
                               service_instance.print_schema()))
        except Exception:
            print_error('Error while initialize service %s\n' % service.name)
            print_text(traceback.format_exc())
예제 #23
0
from django import http
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from spicy.core.admin.conf import AdminAppBase, AdminLink, Perms
from spicy.core.profile.decorators import is_staff
from spicy.core.siteskin.decorators import ajax_request, render_to
from spicy.utils import get_custom_model_class, NavigationFilter, load_module
from spicy.utils.permissions import *
from . import defaults


Category = get_custom_model_class(defaults.CUSTOM_CATEGORY_MODEL)
CategoryEditForm = load_module(defaults.CREATE_CATEGORY_FORM)
CategoryCreateForm = load_module(defaults.CREATE_CATEGORY_FORM)

class AdminApp(AdminAppBase):
    name = 'categories'
    label = _('Categories')
    order_number = 3

    menu_items = (
        AdminLink('categories:admin:create', _('Create category')),
        AdminLink('categories:admin:index', _('All categories')),
    )

    create = AdminLink('categories:admin:create', _('Create category'),)

    perms = Perms(view=[],  write=[], manage=[])
예제 #24
0
 def form(self):
     return load_module(self.form_mod)
예제 #25
0
파일: api.py 프로젝트: spicycms/spicy.core
 def form(self):
     return load_module(self.form_mod)
예제 #26
0
    def login_or_register(self, request):

        status = 'error'
        message = ''
        redirect = None
        can_login = True
        action = None
        real_ip = request.META.get('REMOTE_ADDR')
        is_blacklisted = real_ip and models.BlacklistedIP.objects.filter(
            ip=real_ip).exists()

        if request.user.is_authenticated():
            redirect = self._get_redirect(request)
            return dict(
                status='ok',
                action='authenticated',
                message=unicode(_('User is signed in already')),
                redirect=redirect)

        elif 'register' in request.POST:

            action = 'register'
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)(request.POST)
            login_form = LoginForm(request)
            if not is_blacklisted and register_form.is_valid():
                status = 'ok'
                new_profile = register_form.save(
                    request=request, realhost=request.get_host(),
                    next_url=request.session.get(REDIRECT_FIELD_NAME, '/'))
                request.session['profile_id'] = new_profile.pk
                request.session['profile_email'] = new_profile.email

        elif 'login' in request.POST:
            action = 'login'
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            login_form = LoginForm(data=request.POST)

            # Brute force check.
            username = request.POST.get('username')

            login_check = self.check_login(
                username, real_ip)
            if login_check == defaults.AUTH_DISALLOW:
                can_login = False
            elif login_check == defaults.AUTH_WARN:
                login_form.make_captcha_visible()
                #captcha_required = True

            if can_login and not is_blacklisted and login_form.is_valid():

                if not redirect or ' ' in redirect or (
                        '//' in redirect and re.match(r'[^\?]*//', redirect)):
                    redirect = settings.LOGIN_REDIRECT_URL

                if login_form.cleaned_data['is_remember']:
                    request.session.set_expiry(1209600)

                session_copy = dict(
                    item for item in request.session.iteritems()
                    if not item[0].startswith('_'))
                auth_login(request, login_form.get_user())
                redirect = self._get_redirect(request)

                for key, value in session_copy.iteritems():
                    request.session[key] = value
                request.session[
                    defaults.PASSWORD_HASH_KEY] = request.user.password

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()
                status = 'ok'

            else:
                if not login_form.is_valid():
                    message = login_form.errors.as_text()
                elif not can_login or is_blacklisted:
                    message = _('Login is disabled or your account is banned.')

        else:
            login_form = LoginForm(request)
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            request.session.set_test_cookie()
            action = None
            if not redirect:
                redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, '/')

            request.session[REDIRECT_FIELD_NAME] = redirect

        return dict(
            status=status, message=unicode(message), redirect=redirect,
            login_form=login_form, register_form=register_form,
            REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED, action=action)
예제 #27
0
    def login_or_register(self, request):

        status = 'error'
        message = ''
        redirect = None
        can_login = True
        action = None
        real_ip = request.META.get('REMOTE_ADDR')
        is_blacklisted = real_ip and models.BlacklistedIP.objects.filter(
            ip=real_ip).exists()

        if request.user.is_authenticated():
            redirect = self._get_redirect(request)
            return dict(status='ok',
                        action='authenticated',
                        message=unicode(_('User is signed in already')),
                        redirect=redirect)

        elif 'register' in request.POST:

            action = 'register'
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)(request.POST)
            login_form = LoginForm(request)
            if not is_blacklisted and register_form.is_valid():
                status = 'ok'
                new_profile = register_form.save(request=request,
                                                 realhost=request.get_host(),
                                                 next_url=request.session.get(
                                                     REDIRECT_FIELD_NAME, '/'))
                request.session['profile_id'] = new_profile.pk
                request.session['profile_email'] = new_profile.email

        elif 'login' in request.POST:
            action = 'login'
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            login_form = LoginForm(data=request.POST)

            # Brute force check.
            username = request.POST.get('username')

            login_check = self.check_login(username, real_ip)
            if login_check == defaults.AUTH_DISALLOW:
                can_login = False
            elif login_check == defaults.AUTH_WARN:
                login_form.make_captcha_visible()
                #captcha_required = True

            if can_login and not is_blacklisted and login_form.is_valid():

                if not redirect or ' ' in redirect or (
                        '//' in redirect and re.match(r'[^\?]*//', redirect)):
                    redirect = settings.LOGIN_REDIRECT_URL

                if login_form.cleaned_data['is_remember']:
                    request.session.set_expiry(1209600)

                session_copy = dict(item
                                    for item in request.session.iteritems()
                                    if not item[0].startswith('_'))
                auth_login(request, login_form.get_user())
                redirect = self._get_redirect(request)

                for key, value in session_copy.iteritems():
                    request.session[key] = value
                request.session[
                    defaults.PASSWORD_HASH_KEY] = request.user.password

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()
                status = 'ok'

            else:
                if not login_form.is_valid():
                    message = login_form.errors.as_text()
                elif not can_login or is_blacklisted:
                    message = _('Login is disabled or your account is banned.')

        else:
            login_form = LoginForm(request)
            register_form = load_module(CUSTOM_USER_SIGNUP_FORM)()
            request.session.set_test_cookie()
            action = None
            if not redirect:
                redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, '/')

            request.session[REDIRECT_FIELD_NAME] = redirect

        return dict(status=status,
                    message=unicode(message),
                    redirect=redirect,
                    login_form=login_form,
                    register_form=register_form,
                    REGISTRATION_ENABLED=defaults.REGISTRATION_ENABLED,
                    action=action)