示例#1
0
文件: views.py 项目: aarsom/signbank
def mylogin(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    "Displays the login form and handles the login action."
    
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if request.method == "POST":
        form = EmailAuthenticationForm(data=request.POST)
        if form.is_valid(): 
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            from django.contrib.auth import login
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)
    else:
        form = EmailAuthenticationForm(request)
    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'allow_registration': settings.ALLOW_REGISTRATION,
    }, context_instance=RequestContext(request))
示例#2
0
文件: views.py 项目: hnejadi/xerobis
def _login(request, redirect_to):
    """"Altered version of the default login, intended to be called by `combined_login`.

    Returns tuple:
    - success
    - redirect (success) or form (on failure)
    """
    form = EmailAuthenticationForm(data=request.POST)
    if request.method == 'POST':
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return (True, HttpResponseRedirect(redirect_to))
        else:
            log.error(form.errors)

    return (False, form)
示例#3
0
def mylogin(request, template_name="registration/login.html", redirect_field_name=REDIRECT_FIELD_NAME):
    """Displays the login form and handles the login action."""

    # Replaced request.REQUEST with request.GET.get
    # Get the url to forward to after login
    # If GET has the value, use it, else use POST to get the url
    if request.GET.get(redirect_field_name):
        redirect_to = request.GET.get(redirect_field_name, "")
    else:
        redirect_to = request.POST.get(redirect_field_name, "")
    if request.method == "POST":
        form = EmailAuthenticationForm(data=request.POST)
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or "//" in redirect_to or " " in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            from django.contrib.auth import login

            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)
    else:
        form = EmailAuthenticationForm(request)
    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    return render(
        request,
        template_name,
        {
            "form": form,
            redirect_field_name: redirect_to,
            "site": current_site,
            "site_name": current_site.name,
            "allow_registration": settings.ALLOW_REGISTRATION,
        },
    )
示例#4
0
def login(request, next=None, *args, **kwargs):
    """
    Main login view.
    """
    next = request.REQUEST.get('next', next)
    user = None
    user_id = request.session.get("user_id")
    if user_id:
        del request.session[
            "user_id"]  # We probably don't need it for more than one pageload
        if User.objects.filter(pk=user_id).exists():
            user = User.objects.get(pk=user_id)

    if next is None:
        if request.path != reverse('auth_login'):
            next = request.path
        else:
            next = '/account/profile/info'

    if request.method == "POST":
        ip = request.META["REMOTE_ADDR"]

        cache_key = 'login_%s' % ip
        login_try = cache.get(cache_key)

        # Anti-Bruteforce
        if login_try > 19:
            request.method = 'GET'
            messages.error(
                request,
                _(u'Your IP address has been blocked due to 20 unsuccessfull logon '
                  u'attempts. Please wait at least 20 minutes before trying again'
                  ))
            cache.set(cache_key, login_try + 1, 20 * 60)
            subject = u'Возможная попытка взлома системы'
            message = u'IP %s пытается войти в систему. Данный IP был заблокирован на ближайшие ' \
                      u'20 минут, вследствие 20 неудачных попыток войти в систему.' % ip
            mail_admins(subject=subject, message=message)

    form = EmailAuthenticationForm(
        data=request.POST or None,
        request=request,
        prefix="auth",
        label_suffix='',
        initial={
            'login_from': get_private_office_from_next(next),
            'email_phone': user.profile.phone_mobile if user else None
        })

    if request.method == "POST":
        if form.is_valid():
            user = form.get_user()

            if user.last_login == datetime.fromtimestamp(
                    0) and not user.profile.has_otp_devices:
                SMSDevice.objects.create(
                    user=user, phone_number=user.profile.phone_mobile)
                user.profile.make_valid("phone_mobile")
                user.profile.lost_otp = False
                user.profile.save()

            # if user.profile.ask_on_login:
            #     result = security_check(request, user)
            #     if result:
            #         return result

            django_login(request, user)

            Logger(content_object=request.user,
                   ip=request.META["REMOTE_ADDR"],
                   user=request.user,
                   event=Events.LOGIN_OK).save()

            profile = request.user.profile

            language = request.session.get('django_language',
                                           settings.LANGUAGE_CODE)

            if profile.language != language:
                profile.language = language
                profile.save()

            if not form.cleaned_data["remember"]:
                days = 0  # Log the user out after a day.
            else:
                days = settings.LOGIN_FOR

            request.session.set_expiry(60 * 60 * 24 * days)

            if request.user.profile.lost_otp:
                if request.is_ajax():
                    return {
                        "ok": True,
                        "redirect": reverse("otp_security") + "?next=" + next
                    }

            next_url = '{}://{}{}'.format(request.META['wsgi.url_scheme'],
                                          request.get_host(),
                                          request.GET.get("next", "/"))

            request.session['login_ts'] = time.time()
            request.session['xnext'] = '{}://{}{}'.format(
                request.META['wsgi.url_scheme'], request.get_host(),
                request.GET.get("next", "/"))

            if settings.XDOMAINS and not request.user.profile.registered_from:
                request.session['redirect_ts'] = time.time()
                request.session['xnext'] = next_url
                session_hashed = hashlib.md5(
                    request.session.session_key).hexdigest()
                cache.set('sess_' + session_hashed,
                          request.session.session_key, 30)

                redirect_to = '{}://{}{}?token={}'.format(
                    request.META['wsgi.url_scheme'], settings.XDOMAINS[0],
                    reverse('xdomain_auth'), session_hashed)
            else:
                redirect_to = next_url

            if request.is_ajax():
                return {"ok": True, "simple_redirect": redirect_to}

            print redirect_to
            return redirect(redirect_to)

        else:
            # сделано из-за странной ошибки с именованием поля.
            # видимо, где-то есть форма со старым названием поля;
            # можно удалить лет через 10, когда все устаканится
            email = request.POST.get("auth-email_phone") or request.POST.get(
                "email")
            users = User.objects.filter(email=email)
            kwargs = {"content_object": users[0]} if users else {}

            Logger(ip=request.META["REMOTE_ADDR"],
                   event=Events.LOGIN_FAIL,
                   params={
                       "email": email
                   },
                   **kwargs).save()

            if login_try:
                cache.set(cache_key, login_try + 1, 20 * 60)
            else:
                cache.set(cache_key, 1, 20 * 60)

            if request.is_ajax():
                return {
                    "nok": True,
                    "errors":
                    {k: map(unicode, v)
                     for k, v in form.errors.items()}
                }

    if request.is_ajax():
        return render_to_response(
            "reveal_forms/login.html",
            RequestContext(request, {
                "form": form,
                "next": next
            }))

    return {"form": form, "next": next, "first_login": True if user else False}
示例#5
0
def mylogin(request,
            template_name='registration/login.html',
            redirect_field_name='/signs/recently_added/'):
    "Displays the login form and handles the login action."

    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
    error_message = ''

    if request.method == "POST":
        if REDIRECT_FIELD_NAME in request.POST:
            redirect_to = request.POST[REDIRECT_FIELD_NAME]

        form = EmailAuthenticationForm(data=request.POST)
        if form.is_valid():

            #Count the number of logins
            profile = form.get_user().get_profile()
            profile.number_of_logins += 1
            profile.save()

            #Expiry date cannot be in the past
            if profile.expiry_date != None and date.today(
            ) > profile.expiry_date:
                form = EmailAuthenticationForm(request)
                error_message = _(
                    'This account has expired. Please contact [email protected].'
                )

            else:
                # Light security check -- make sure redirect_to isn't garbage.
                if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                    redirect_to = settings.LOGIN_REDIRECT_URL
                from django.contrib.auth import login
                login(request, form.get_user())
                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                # For logging in API clients
                if "api" in request.GET and request.GET['api'] == 'yes':
                    return HttpResponse(json.dumps({'success': 'true'}),
                                        content_type='application/json')

                return HttpResponseRedirect(redirect_to)
        else:
            if "api" in request.GET and request.GET['api'] == 'yes':
                return HttpResponse(json.dumps({'success': 'false'}),
                                    content_type='application/json')
            error_message = _('The username or password is incorrect.')

    else:
        form = EmailAuthenticationForm(request)

    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    # For logging in API clients
    if request.method == "GET" and "api" in request.GET and request.GET[
            'api'] == 'yes':
        token = get_token(request)
        return HttpResponse(json.dumps({'csrfmiddlewaretoken': token}),
                            content_type='application/json')

    return render_to_response(template_name, {
        'form': form,
        REDIRECT_FIELD_NAME: settings.URL + redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'allow_registration': settings.ALLOW_REGISTRATION,
        'error_message': error_message
    },
                              context_instance=RequestContext(request))