Beispiel #1
0
    def allow_request(self, request, view):
        """
        Implement the check to see if the request should be throttled.

        On success calls `throttle_success`.
        On failure calls `throttle_failure`.
        """
        if self.rate is None:
            return True

        if get_remote_ip(request) in settings.REST_FRAMEWORK_THROTTING_WHITELIST:
            return True

        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True

        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
Beispiel #2
0
    def allow_request(self, request, view):
        """
        Implement the check to see if the request should be throttled.

        On success calls `throttle_success`.
        On failure calls `throttle_failure`.
        """
        if self.rate is None:
            return True

        if get_remote_ip(
                request) in settings.REST_FRAMEWORK_THROTTING_WHITELIST:
            return True

        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True

        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
Beispiel #3
0
def _clear_login_failed_attempts(request):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    username = request.user.username
    ip = get_remote_ip(request)
    cache.delete(LOGIN_ATTEMPT_PREFIX + username)
    cache.delete(LOGIN_ATTEMPT_PREFIX + ip)
Beispiel #4
0
def _clear_login_failed_attempts(request):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    username = request.user.username
    ip = get_remote_ip(request)
    cache.delete(LOGIN_ATTEMPT_PREFIX + username)
    cache.delete(LOGIN_ATTEMPT_PREFIX + ip)
Beispiel #5
0
def clear_login_failed_attempts(request, username):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    ip = get_remote_ip(request)

    cache.delete(normalize_cache_key(username, prefix=LOGIN_ATTEMPT_PREFIX))
    cache.delete(normalize_cache_key(ip, prefix=LOGIN_ATTEMPT_PREFIX))
    p = Profile.objects.get_profile_by_user(username)
    if p and p.login_id:
        cache.delete(normalize_cache_key(p.login_id, prefix=LOGIN_ATTEMPT_PREFIX))
Beispiel #6
0
def _clear_login_failed_attempts(request):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    username = request.user.username
    ip = get_remote_ip(request)
    cache.delete(LOGIN_ATTEMPT_PREFIX + urlquote(username))
    cache.delete(LOGIN_ATTEMPT_PREFIX + ip)
    p = Profile.objects.get_profile_by_user(username)
    if p and p.login_id:
        cache.delete(LOGIN_ATTEMPT_PREFIX + urlquote(p.login_id))
Beispiel #7
0
def _clear_login_failed_attempts(request, user):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    username = user.username
    ip = get_remote_ip(request)

    cache.delete(LOGIN_ATTEMPT_PREFIX + urlquote(username))
    cache.delete(LOGIN_ATTEMPT_PREFIX + ip)
    p = Profile.objects.get_profile_by_user(username)
    if p and p.login_id:
        cache.delete(LOGIN_ATTEMPT_PREFIX + urlquote(p.login_id))
Beispiel #8
0
def clear_login_failed_attempts(request, username):
    """Clear login failed attempts records.

    Arguments:
    - `request`:
    """
    ip = get_remote_ip(request)

    cache.delete(normalize_cache_key(username, prefix=LOGIN_ATTEMPT_PREFIX))
    cache.delete(normalize_cache_key(ip, prefix=LOGIN_ATTEMPT_PREFIX))
    p = Profile.objects.get_profile_by_user(username)
    if p and p.login_id:
        cache.delete(
            normalize_cache_key(p.login_id, prefix=LOGIN_ATTEMPT_PREFIX))
Beispiel #9
0
    def process_request(self, request):
        if not ENABLE_LIMIT_IPADDRESS:
            return None

        ip = get_remote_ip(request)
        if not TrustedIP.objects.match_ip(ip) and ip not in TRUSTED_IP_LIST:
            if "api2/" in request.path or "api/v2.1/" in request.path:
                return HttpResponse(
                    json.dumps({"err_msg": "you can't login, because IP \
                    address was not in range"}),
                    status=403,
                    content_type='application/json; charset=utf-8'
                )
            else:
                return render_to_response('trusted_ip/403_trusted_ip.html',
                                          status=403)
Beispiel #10
0
def _get_cache_key(request, prefix):
    """Return cache key of certain ``prefix``. If user is logged in, use
    username, otherwise use combination of request ip and user agent.

    Arguments:
    - `prefix`:
    """
    if request.user.is_authenticated():
        key = normalize_cache_key(request.user.username, 'SharedLink_')
    else:
        ip = get_remote_ip(request)
        # Memcached key length limit is 250 chars, and user agent somethings may
        # be long which will cause error.
        agent = request.META.get('HTTP_USER_AGENT', '')[:150]
        key = normalize_cache_key(ip + agent, 'SharedLink_')

    return key
Beispiel #11
0
def _get_cache_key(request, prefix):
    """Return cache key of certain ``prefix``. If user is logged in, use
    username, otherwise use combination of request ip and user agent.

    Arguments:
    - `prefix`:
    """
    if request.user.is_authenticated():
        key = normalize_cache_key(request.user.username, 'SharedLink_')
    else:
        ip = get_remote_ip(request)
        # Memcached key length limit is 250 chars, and user agent somethings may
        # be long which will cause error.
        agent = request.META.get('HTTP_USER_AGENT', '')[:150]
        key = normalize_cache_key(ip + agent, 'SharedLink_')

    return key
Beispiel #12
0
def sys_sudo_mode(request):
    if request.method not in ('GET', 'POST'):
        return HttpResponseNotAllowed

    # here we can't use @sys_staff_required
    if not request.user.is_staff:
        raise Http404

    next_page = request.GET.get('next', reverse('sys_info'))
    password_error = False
    if request.method == 'POST':
        password = request.POST.get('password')
        username = request.user.username
        ip = get_remote_ip(request)
        if password:
            user = authenticate(username=username, password=password)
            if user:
                update_sudo_mode_ts(request)

                from seahub.auth.utils import clear_login_failed_attempts
                clear_login_failed_attempts(request, username)

                return HttpResponseRedirect(next_page)
        password_error = True

        from seahub.auth.utils import get_login_failed_attempts, incr_login_failed_attempts
        failed_attempt = get_login_failed_attempts(username=username, ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            # logout user
            from seahub.auth import logout
            logout(request)
            return HttpResponseRedirect(reverse('auth_login'))
        else:
            incr_login_failed_attempts(username=username, ip=ip)

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_adfs_login = getattr(settings, 'ENABLE_ADFS_LOGIN', False)
    return render(
        request, 'sysadmin/sudo_mode.html', {
            'password_error': password_error,
            'enable_sso': enable_shib_login or enable_adfs_login,
            'next': next_page,
        })
Beispiel #13
0
def send_file_download_msg(request, repo, path, dl_type):
    """Send file downlaod msg.
    
    Arguments:
    - `request`:
    - `repo`:
    - `obj_id`:
    - `dl_type`: web or api
    """
    username = request.user.username
    ip = get_remote_ip(request)
    user_agent = request.META.get("HTTP_USER_AGENT")

    msg = "file-download-%s\t%s\t%s\t%s\t%s\t%s\t%s" % (dl_type, username, ip, user_agent, repo.id, repo.name, path)
    msg_utf8 = msg.encode("utf-8")

    try:
        send_message("seahub.stats", msg_utf8)
    except Exception as e:
        logger.error("Error when sending file-download-%s message: %s" % (dl_type, str(e)))
Beispiel #14
0
def send_file_download_msg(request, repo, path, dl_type):
    """Send file downlaod msg.
    
    Arguments:
    - `request`:
    - `repo`:
    - `obj_id`:
    - `dl_type`: web or api
    """
    username = request.user.username
    ip = get_remote_ip(request)
    user_agent = request.META.get("HTTP_USER_AGENT")

    msg = 'file-download-%s\t%s\t%s\t%s\t%s\t%s\t%s' % \
        (dl_type, username, ip, user_agent, repo.id, repo.name, path)
    msg_utf8 = msg.encode('utf-8')

    try:
        send_message('seahub.stats', msg_utf8)
    except Exception as e:
        logger.error("Error when sending file-download-%s message: %s" %
                     (dl_type, str(e)))
Beispiel #15
0
def login(request, template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)
    failed_attempt = _get_login_failed_attempts(ip=ip)

    if request.method == "POST":
        username = urlquote(request.REQUEST.get('username', '').strip())
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                form = authentication_form(data=request.POST)
                if form.is_valid():
                    return _handle_login_form_valid(request, form.get_user(),
                                                    redirect_to, remember_me)
                else:
                    # freeze user account anyway
                    login = request.REQUEST.get('login', '')
                    email = Profile.objects.get_username_by_login_id(login)
                    if email is None:
                        email = login

                    try:
                        user = User.objects.get(email)
                        if user.is_active:
                            user.freeze_user(notify_admins=True)
                    except User.DoesNotExist:
                        pass
                    form.errors['freeze_account'] = _('This account has been frozen due to too many failed login attempts.')
            else:
                # log user in if password is valid otherwise show captcha
                form = CaptchaAuthenticationForm(data=request.POST)
                if form.is_valid():
                    return _handle_login_form_valid(request, form.get_user(),
                                                    redirect_to, remember_me)
                else:
                    # show page with captcha and increase failed login attempts
                    _incr_login_faied_attempts(username=username, ip=ip)
        else:
            # login failed attempts < limit
            form = authentication_form(data=request.POST)
            if form.is_valid():
                return _handle_login_form_valid(request, form.get_user(),
                                                redirect_to, remember_me)
            else:
                # increase failed attempts
                login = urlquote(request.REQUEST.get('login', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=login,
                                                            ip=ip)

                if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                    logger.warn('Login attempt limit reached, email/username: %s, ip: %s, attemps: %d' %
                                (login, ip, failed_attempt))

                    if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                        form = authentication_form(data=request.POST)
                    else:
                        form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form(data=request.POST)
            else:
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form(request)

    request.session.set_test_cookie()

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

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
    }, context_instance=RequestContext(request))
Beispiel #16
0
def login(
    request,
    template_name="registration/login.html",
    redirect_if_logged_in=None,
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=AuthenticationForm,
):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, "")
    ip = get_remote_ip(request)

    if request.method == "POST":
        login = urlquote(request.REQUEST.get("login", "").strip())
        failed_attempt = _get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.REQUEST.get("remember_me", "") == "on" else False

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(), redirect_to, remember_me)

        # form is invalid
        failed_attempt = _incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    "Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d"
                    % (login, ip, failed_attempt)
                )
                login = request.REQUEST.get("login", "")
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            "Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d"
                            % (login, ip, failed_attempt)
                        )
                except User.DoesNotExist:
                    logger.warn(
                        "Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d"
                        % (login, ip, failed_attempt)
                    )
                    pass
                form.errors["freeze_account"] = _("This account has been frozen due to too many failed login attempts.")
            else:
                # use a new form with Captcha
                logger.warn(
                    "Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d"
                    % (login, ip, failed_attempt)
                )
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()
    else:
        ### GET
        failed_attempt = _get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn("Login attempt limit reached, show Captcha, ip: %s, attempts: %d" % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()

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

    multi_tenancy = getattr(settings, "MULTI_TENANCY", False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, "FORCE_ORG_REGISTER", False)
            if org_account_only:
                signup_url = reverse("org_register")
            else:
                signup_url = reverse("choose_register")
        else:
            signup_url = reverse("registration_register")
    else:
        signup_url = ""

    enable_shib_login = getattr(settings, "ENABLE_SHIB_LOGIN", False)
    enable_krb5_login = getattr(settings, "ENABLE_KRB5_LOGIN", False)

    return render_to_response(
        template_name,
        {
            "form": form,
            redirect_field_name: redirect_to,
            "site": current_site,
            "site_name": current_site.name,
            "remember_days": config.LOGIN_REMEMBER_DAYS,
            "signup_url": signup_url,
            "enable_shib_login": enable_shib_login,
            "enable_krb5_login": enable_krb5_login,
        },
        context_instance=RequestContext(request),
    )
Beispiel #17
0
def create_login_log(sender, request, user, **kwargs):
    username = user.username
    login_ip = get_remote_ip(request)
    UserLoginLog.objects.create_login_log(username, login_ip)
Beispiel #18
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)
    failed_attempt = _get_login_failed_attempts(ip=ip)

    if request.method == "POST":
        username = urlquote(request.REQUEST.get('username', '').strip())
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            # have captcha
            form = CaptchaAuthenticationForm(data=request.POST)
            if form.is_valid():
                if UserOptions.objects.passwd_change_required(
                        form.get_user().username):
                    redirect_to = reverse('auth_password_change')
                    request.session['force_passwd_change'] = True

                # captcha & passwod is valid, log user in
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                # show page with captcha and increase failed login attempts
                _incr_login_faied_attempts(username=username, ip=ip)
        else:
            form = authentication_form(data=request.POST)
            if form.is_valid():
                if UserOptions.objects.passwd_change_required(
                        form.get_user().username):
                    redirect_to = reverse('auth_password_change')
                    request.session['force_passwd_change'] = True

                # password is valid, log user in
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                login = urlquote(request.REQUEST.get('login', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=login,
                                                            ip=ip)

                if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
                    logger.warn(
                        'Login attempt limit reached, email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            form = CaptchaAuthenticationForm(request)
        else:
            form = authentication_form(request)

    request.session.set_test_cookie()

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

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
    },
                              context_instance=RequestContext(request))
Beispiel #19
0
def create_login_failed_log(sender, request, **kwargs):
    username = request.POST.get('login', '')
    login_ip = get_remote_ip(request)
    UserLoginLog.objects.create_login_log(username,
                                          login_ip,
                                          login_success=False)
Beispiel #20
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)
    failed_attempt = _get_login_failed_attempts(ip=ip)

    if request.method == "POST":
        username = urlquote(request.REQUEST.get('username', '').strip())
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                form = authentication_form(data=request.POST)
                if form.is_valid():
                    return _handle_login_form_valid(request, form.get_user(),
                                                    redirect_to, remember_me)
                else:
                    # freeze user account anyway
                    login = request.REQUEST.get('login', '')
                    email = Profile.objects.get_username_by_login_id(login)
                    if email is None:
                        email = login

                    try:
                        user = User.objects.get(email)
                        if user.is_active:
                            user.freeze_user(notify_admins=True)
                    except User.DoesNotExist:
                        pass
                    form.errors['freeze_account'] = _(
                        'This account has been frozen due to too many failed login attempts.'
                    )
            else:
                # log user in if password is valid otherwise show captcha
                form = CaptchaAuthenticationForm(data=request.POST)
                if form.is_valid():
                    return _handle_login_form_valid(request, form.get_user(),
                                                    redirect_to, remember_me)
                else:
                    # show page with captcha and increase failed login attempts
                    _incr_login_faied_attempts(username=username, ip=ip)
        else:
            # login failed attempts < limit
            form = authentication_form(data=request.POST)
            if form.is_valid():
                return _handle_login_form_valid(request, form.get_user(),
                                                redirect_to, remember_me)
            else:
                # increase failed attempts
                login = urlquote(request.REQUEST.get('login', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=login,
                                                            ip=ip)

                if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                    logger.warn(
                        'Login attempt limit reached, email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))

                    if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                        form = authentication_form(data=request.POST)
                    else:
                        form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form(data=request.POST)
            else:
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form(request)

    request.session.set_test_cookie()

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

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
    },
                              context_instance=RequestContext(request))
Beispiel #21
0
def login(request, template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        if request.REQUEST.get('captcha_0', '') != '':
            # have captcha
            form = CaptchaAuthenticationForm(data=request.POST)
            if form.is_valid():
                # captcha & passwod is valid, log user in
                remember_me = True if request.REQUEST.get(
                    'remember_me', '') == 'on' else False
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                # show page with captcha and increase failed login attempts
                _incr_login_faied_attempts(ip=ip)
        else:
            form = authentication_form(data=request.POST)
            if form.is_valid():
                # password is valid, log user in
                remember_me = True if request.REQUEST.get(
                    'remember_me', '') == 'on' else False
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                username = urlquote(request.REQUEST.get('username', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=username,
                                                            ip=ip)

                if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
                    logger.warn('Login attempt limit reached, username: %s, ip: %s, attemps: %d' %
                                (username, ip, failed_attempt))
                    form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        failed_attempt = _get_login_failed_attempts(ip=ip)
        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            form = CaptchaAuthenticationForm(request)
        else:
            form = authentication_form(request)
    
    request.session.set_test_cookie()
    
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    enable_signup = getattr(settings, 'ENABLE_SIGNUP', False)
    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)
    if enable_signup:
        if multi_tenancy:
            signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    return render_to_response(template_name, {
            'form': form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': current_site.name,
            'remember_days': settings.LOGIN_REMEMBER_DAYS,
            'signup_url': signup_url,
            }, context_instance=RequestContext(request))
Beispiel #22
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        login = urlquote(request.REQUEST.get('login', '').strip())
        failed_attempt = _get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        user_logged_in_failed.send(sender=None, request=request)
        failed_attempt = _incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    'Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                login = request.REQUEST.get('login', '')
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            'Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d'
                            % (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn(
                        'Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _(
                    'This account has been frozen due to too many failed login attempts.'
                )
            else:
                # use a new form with Captcha
                logger.warn(
                    'Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()

    else:
        ### GET
        failed_attempt = _get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn(
                    'Login attempt limit reached, show Captcha, ip: %s, attempts: %d'
                    % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()

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

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)
    enable_adfs_login = getattr(settings, 'ENABLE_ADFS_LOGIN', False)

    login_bg_image_path = LOGIN_BG_IMAGE_PATH
    # get path that background image of login page
    custom_login_bg_image_file = os.path.join(MEDIA_ROOT,
                                              CUSTOM_LOGIN_BG_IMAGE_PATH)
    if os.path.exists(custom_login_bg_image_file):
        login_bg_image_path = CUSTOM_LOGIN_BG_IMAGE_PATH

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
        'enable_adfs_login': enable_adfs_login,
        'login_bg_image_path': login_bg_image_path,
    },
                              context_instance=RequestContext(request))
Beispiel #23
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in='libraries',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    redirect_to = request.GET.get(redirect_field_name, '')
    if request.user.is_authenticated():
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        else:
            return HttpResponseRedirect(reverse(redirect_if_logged_in))

    ip = get_remote_ip(request)

    if request.method == "POST":
        login = request.POST.get('login', '').strip()
        failed_attempt = get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.POST.get('remember_me',
                                               '') == 'on' else False
        redirect_to = request.POST.get(redirect_field_name, '') or redirect_to

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        user_logged_in_failed.send(sender=None, request=request)
        failed_attempt = incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    'Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            'Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d'
                            % (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn(
                        'Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _(
                    'This account has been frozen due to too many failed login attempts.'
                )
            else:
                # use a new form with Captcha
                logger.warn(
                    'Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()

    else:
        ### GET
        failed_attempt = get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn(
                    'Login attempt limit reached, show Captcha, ip: %s, attempts: %d'
                    % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()
    current_site = get_current_site(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_sso = getattr(settings, 'ENABLE_SHIB_LOGIN', False) or \
                 getattr(settings, 'ENABLE_KRB5_LOGIN', False) or \
                 getattr(settings, 'ENABLE_ADFS_LOGIN', False) or \
                 getattr(settings, 'ENABLE_OAUTH', False) or \
                 getattr(settings, 'ENABLE_CAS', False) or \
                 getattr(settings, 'ENABLE_REMOTE_USER_AUTHENTICATION', False) or \
                 getattr(settings, 'ENABLE_WORK_WEIXIN', False)

    login_bg_image_path = get_login_bg_image_path()

    return render(
        request, template_name, {
            'form': form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': get_site_name(),
            'remember_days': config.LOGIN_REMEMBER_DAYS,
            'signup_url': signup_url,
            'enable_sso': enable_sso,
            'login_bg_image_path': login_bg_image_path,
        })