コード例 #1
0
 def log_auth(cls, request, confirm_method=''):
     ip = get_ip(request)
     user_agent = request.META.get('HTTP_USER_AGENT')
     if user_agent is not None:
         parser = detect(user_agent)
         browser = parser.get('browser', {})
         user_agent = "%s, %s %s" % (
             parser.get('platform', {}).get('name', ""),
             browser.get('name', ""), browser.get('version', ""))
     cls.objects.create(
         user=request.user, ip=get_ip(request), geo=get_geo(ip),
         agent=user_agent, confirm_method=confirm_method
     )
コード例 #2
0
ファイル: base.py プロジェクト: Tapo4ek/django-secure-auth
 def _check_step(self, step):
     if self.request.session.get('step') != step:
         raise Http404
     elif self.request.session.get('ip') != get_ip(self.request):
         return Http404
     elif (now() - self.request.session.get('step_time')).seconds > SMS_AGE:
         return Http404
コード例 #3
0
 def check_access(cls, request):
     if request.GET.get('data'):
         data = Sign().unsign(request.GET.get('data'), SMS_AGE * 2)
         if data.get('ip') == get_ip(request):
             user_agent = md5(request.META['HTTP_USER_AGENT'])
             if data.get('user_agent') == user_agent:
                 return True
コード例 #4
0
def login_confirmation(request, template_name='secureauth/confirmation.html',
                       authentication_form=ConfirmAuthenticationForm,
                       extra_context=None, current_app=None
                       ):  # pylint: disable=R0913
    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    data = get_data(request)
    if extra_context is None and data.get('extra_context'):
        extra_context = data.get('extra_context')

    if hasattr(request, 'user') and request.user.is_authenticated():
        return HttpResponseRedirect(data.get('redirect_to', '/'))
    elif request.method == "POST":
        form = authentication_form(data, request.POST)
        if form.is_valid():
            user = form.get_user()

            if user and data.get('user_pk') == user.pk:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(
                        request, form.cleaned_data.get('auth_type'))

                UserAuthNotification.notify(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)

                return HttpResponseRedirect(data.get('redirect_to'))
            else:
                return HttpResponseBadRequest()
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(data)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        'site': current_site,
        'site_name': current_site.name,
        'data': request.GET.get('data'),
    }
    if extra_context is not None:
        context.update(extra_context)
    if django.VERSION < (1, 8):
        return TemplateResponse(
            request, template_name, context, current_app=current_app)
    else:
        return TemplateResponse(
            request, template_name, context)
コード例 #5
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
 def check_access(cls, request):
     if request.GET.get('data'):
         data = Sign().unsign(request.GET.get('data'), SMS_AGE * 2)
         if data.get('ip') == get_ip(request):
             user_agent = md5(request.META['HTTP_USER_AGENT'])
             if data.get('user_agent') == user_agent:
                 return True
コード例 #6
0
def login_confirmation(request,
                       template_name='secureauth/confirmation.html',
                       authentication_form=ConfirmAuthenticationForm,
                       extra_context=None,
                       current_app=None):  # pylint: disable=R0913
    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    data = get_data(request)
    if extra_context is None and data.get('extra_context'):
        extra_context = data.get('extra_context')

    if hasattr(request, 'user') and request.user.is_authenticated():
        return HttpResponseRedirect(data.get('redirect_to', '/'))
    elif request.method == "POST":
        form = authentication_form(data, request.POST)
        if form.is_valid():
            user = form.get_user()

            if user and data.get('user_pk') == user.pk:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(
                        request, form.cleaned_data.get('auth_type'))

                UserAuthNotification.notify(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)

                return HttpResponseRedirect(data.get('redirect_to'))
            else:
                return HttpResponseBadRequest()
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(data)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        'site': current_site,
        'site_name': current_site.name,
        'data': request.GET.get('data'),
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request,
                            template_name,
                            context,
                            current_app=current_app)
コード例 #7
0
 def _check_step(self, step):
     step_time = self.request.session.get('step_time', SMS_AGE+10)
     if self.request.session.get('step') != step:
         raise Http404
     elif self.request.session.get('ip') != get_ip(self.request):
         return Http404
     elif (now() - datetime.fromtimestamp(step_time)).seconds > SMS_AGE:
         return Http404
コード例 #8
0
 def _check_step(self, step):
     step_time = self.request.session.get('step_time', SMS_AGE + 10)
     if self.request.session.get('step') != step:
         raise Http404
     elif self.request.session.get('ip') != get_ip(self.request):
         return Http404
     elif (now() - datetime.fromtimestamp(step_time)).seconds > SMS_AGE:
         return Http404
コード例 #9
0
def _get_data(request):
    data = Sign().unsign(request.GET.get("data"), age=SMS_AGE * 2)
    if data is not None and "credentials" in data:
        if "captcha" in data["credentials"]:
            data["credentials"].pop("captcha")
        user = authenticate(**data["credentials"])
        if user is not None and user.is_active:
            if get_ip(request) == data.get("ip"):
                return data
    raise Http404("Data is not valid!")
コード例 #10
0
    def is_allowed(cls, request, user):
        ip_address = get_ip(request)
        if cls.objects.filter(ip__user=user, ip_data=ip_address).exists():
            return True

        range_list = cls.objects.values_list('ip_data', flat=True).filter(
            ip__user=user, is_ip=False)
        user_ip = IPv4Address(unicode(ip_address))

        if any([user_ip in IPv4Network(ip_range) for ip_range in range_list]):
            return True
コード例 #11
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
    def is_allowed(cls, request, user):
        ip_address = get_ip(request)
        if cls.objects.filter(ip__user=user, ip_data=ip_address).exists():
            return True

        range_list = cls.objects.values_list('ip_data', flat=True).filter(
            ip__user=user, is_ip=False)
        user_ip = IPv4Address(unicode(ip_address))

        if any([user_ip in IPv4Network(ip_range) for ip_range in range_list]):
            return True
コード例 #12
0
 def check_location(cls, request):
     obj = cls.objects.filter(user_id=request.user.pk).order_by('-id')[:1]
     if obj.exists():
         geo = get_geo(get_ip(request))
         obj = obj[0]
         if not obj.notified and geo != obj.geo:
             messages.warning(request, render_template(
                 'secureauth/location_message.html', {'obj': obj}))
             UserAuthNotification.notify(
                 request, _('Your location has changed to %s' % geo))
             obj.notified = True
             obj.save()
コード例 #13
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
 def check_location(cls, request):
     obj = cls.objects.filter(user_id=request.user.pk).order_by('-id')[:1]
     if obj.exists():
         geo = get_geo(get_ip(request))
         obj = obj[0]
         if not obj.notified and geo != obj.geo:
             messages.warning(request, render_template(
                 'secureauth/location_message.html', {'obj': obj}))
             UserAuthNotification.notify(
                 request, _('Your location has changed to %s' % geo))
             obj.notified = True
             obj.save()
コード例 #14
0
def login_confirmation(
    request,
    template_name="secureauth/confirmation.html",
    authentication_form=ConfirmAuthenticationForm,
    extra_context=None,
    current_app=None,
):
    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    data = _get_data(request)
    if extra_context is None and data.get("extra_context"):
        extra_context = data.get("extra_context")

    if hasattr(request, "user") and request.user.is_authenticated():
        return HttpResponseRedirect(data.get("redirect_to", "/"))
    elif request.method == "POST":
        form = authentication_form(data, request.POST)
        if form.is_valid():
            user = form.get_user()

            if user and data.get("user_pk") == user.pk:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(request, form.cleaned_data.get("auth_type"))

                UserAuthNotification.notify(request)
                UserAuthAttempt.remove(request)
                request.session["ip"] = get_ip(request)

                return HttpResponseRedirect(data.get("redirect_to"))
            else:
                return HttpResponseBadRequest()
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(data)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {"form": form, "site": current_site, "site_name": current_site.name, "data": request.GET.get("data")}
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context, current_app=current_app)
コード例 #15
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
 def log_auth(cls, request, confirm_method=''):
     ip_address = get_ip(request)
     user_agent = request.META.get('HTTP_USER_AGENT')
     if user_agent is not None:
         parser = detect(user_agent)
         browser = parser.get('browser', {})
         user_agent = "%s, %s %s" % (
             parser.get('platform', {}).get('name', ""),
             browser.get('name', ""), browser.get('version', ""))
     cls.objects.create(
         user=request.user, ip=ip_address, geo=get_geo(ip_address),
         agent=user_agent, confirm_method=confirm_method
     )
コード例 #16
0
 def send_link(cls, request, user):
     data = {
         'ip': get_ip(request),
         'user_agent': md5(request.META.get('HTTP_USER_AGENT')),
     }
     link = 'http://%s%s?data=%s' % (
         Site.objects.get_current(),
         reverse('auth_login'),
         Sign().sign(data)
     )
     send_mail(
         [user.email], _('Link for unlock access'), link
     )
コード例 #17
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
 def send_link(cls, request, user):
     data = {
         'ip': get_ip(request),
         'user_agent': md5(request.META.get('HTTP_USER_AGENT')),
     }
     link = 'http://%s%s?data=%s' % (
         Site.objects.get_current(),
         reverse('auth_login'),
         Sign().sign(data)
     )
     send_mail(
         [user.email], _('Link for unlock access'), link
     )
コード例 #18
0
 def _set_next_step(self, step):
     self.request.session['step'] = step
     self.request.session['step_time'] = time.mktime(now().timetuple())
     if not self.request.session.get('ip'):
         self.request.session['ip'] = get_ip(self.request)
コード例 #19
0
def login(request,
          template_name='secureauth/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=BaseAuthForm,
          current_app=None,
          extra_context=None,
          redirect_to=''):  # pylint: disable=R0913
    args = [redirect_field_name, redirect_to]
    redirect_to = request.GET.get(*args) or request.POST.get(*args)

    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    if request.method == "POST":
        form = authentication_form(request,
                                   data=request.POST,
                                   test_cookie_enabled=False)
        if form.is_valid():
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL
                if '/' not in redirect_to and '.' not in redirect_to:
                    redirect_to = reverse(settings.LOGIN_REDIRECT_URL)

            user = form.get_user()

            if UserAuthIPRange.is_blocked(request, user):
                return render(request, 'secureauth/blocked_ip.html')

            if SMS_FORCE or len(get_available_auth_methods(user)) > 1:
                data = {
                    'credentials': form.cleaned_data,
                    'user_pk': user.pk,
                    'ip': get_ip(request),
                    'redirect_to': redirect_to,
                    'extra_context': extra_context,
                }
                data = Sign().sign(data)
                return HttpResponseRedirect(
                    '%s?data=%s' % (reverse('auth_confirmation'), data))
            else:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)
                return HttpResponseRedirect(redirect_to)
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    if django.VERSION < (1, 8):
        return TemplateResponse(request,
                                template_name,
                                context,
                                current_app=current_app)
    else:
        return TemplateResponse(request, template_name, context)
コード例 #20
0
 def process_request(self, request):
     if request.session.get('ip'):
         if request.session.get('ip') != get_ip(request):
             del request.session['ip']
             logout(request)
コード例 #21
0
 def process_request(self, request):
     if request.session.get('ip'):
         if request.session.get('ip') != get_ip(request):
             del request.session['ip']
             logout(request)
コード例 #22
0
 def _set_next_step(self, step):
     self.request.session['step'] = step
     self.request.session['step_time'] = now()
     if not self.request.session.get('ip'):
         self.request.session['ip'] = get_ip(self.request)
コード例 #23
0
ファイル: models.py プロジェクト: Br0wserz/django-secure-auth
 def get_obj(cls, request):
     return cls.objects.get_or_create(ip=inet_aton(get_ip(request)))[0]
コード例 #24
0
def login(
    request,
    template_name="secureauth/login.html",
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=BaseAuthForm,
    current_app=None,
    extra_context=None,
    redirect_to="",
):
    redirect_to = request.REQUEST.get(redirect_field_name, redirect_to)

    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    if request.method == "POST":
        form = authentication_form(request, data=request.POST, test_cookie_enabled=False)
        if form.is_valid():
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL
                if "/" not in redirect_to and "." not in redirect_to:
                    redirect_to = reverse(settings.LOGIN_REDIRECT_URL)

            user = form.get_user()

            if UserAuthIPRange.is_blocked(request, user):
                return render(request, "secureauth/blocked_ip.html")

            if SMS_FORCE or len(get_available_auth_methods(user)) > 1:
                data = {
                    "credentials": form.cleaned_data,
                    "user_pk": user.pk,
                    "ip": get_ip(request),
                    "redirect_to": redirect_to,
                    "extra_context": extra_context,
                }
                data = Sign().sign(data)
                return HttpResponseRedirect("%s?data=%s" % (reverse("auth_confirmation"), data))
            else:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(request)
                UserAuthAttempt.remove(request)
                request.session["ip"] = get_ip(request)
                return HttpResponseRedirect(redirect_to)
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {"form": form, redirect_field_name: redirect_to, "site": current_site, "site_name": current_site.name}
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context, current_app=current_app)
コード例 #25
0
 def _set_next_step(self, step):
     self.request.session["step"] = step
     self.request.session["step_time"] = now()
     if not self.request.session.get("ip"):
         self.request.session["ip"] = get_ip(self.request)
コード例 #26
0
 def get_obj(cls, request):
     return cls.objects.get_or_create(ip=inet_aton(get_ip(request)))[0]
コード例 #27
0
def login(request, template_name='secureauth/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=BaseAuthForm,
          current_app=None, extra_context=None, redirect_to=''
          ):  # pylint: disable=R0913
    args = [redirect_field_name, redirect_to]
    redirect_to = request.GET.get(*args) or request.POST.get(*args)

    if CHECK_ATTEMPT and UserAuthAttempt.is_banned(request):
        return HttpResponseBadRequest()

    if request.method == "POST":
        form = authentication_form(
            request, data=request.POST, test_cookie_enabled=False)
        if form.is_valid():
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL
                if '/' not in redirect_to and '.' not in redirect_to:
                    redirect_to = reverse(settings.LOGIN_REDIRECT_URL)

            user = form.get_user()

            if UserAuthIPRange.is_blocked(request, user):
                return render(request, 'secureauth/blocked_ip.html')

            if SMS_FORCE or len(get_available_auth_methods(user)) > 1:
                data = {
                    'credentials': form.cleaned_data,
                    'user_pk': user.pk,
                    'ip': get_ip(request),
                    'redirect_to': redirect_to,
                    'extra_context': extra_context,
                }
                data = Sign().sign(data)
                return HttpResponseRedirect(
                    '%s?data=%s' % (reverse('auth_confirmation'), data))
            else:
                auth_login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                if UserAuthLogging.is_enabled(request):
                    UserAuthActivity.check_location(request)
                    UserAuthActivity.log_auth(request)
                UserAuthAttempt.remove(request)
                request.session['ip'] = get_ip(request)
                return HttpResponseRedirect(redirect_to)
        elif CHECK_ATTEMPT is True:
            UserAuthAttempt.clean()
            UserAuthAttempt.store(request)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    if django.VERSION < (1, 8):
        return TemplateResponse(
            request, template_name, context, current_app=current_app)
    else:
        return TemplateResponse(
            request, template_name, context)
コード例 #28
0
 def _set_next_step(self, step):
     now = datetime.datetime.now()
     self.request.session['step'] = step
     self.request.session['step_time'] = time.mktime(now.timetuple())
     if not self.request.session.get('ip'):
         self.request.session['ip'] = get_ip(self.request)