Ejemplo n.º 1
0
    def done(self, form_list, **kwargs):
        """
        Login the user and redirect to the desired page.
        """
        redirect_to = self.request.session.get(SESSION_KEY_TWO_FACTOR_REDIRECT_URL, '') \
                      or self.request.GET.get(self.redirect_field_name, '')

        auth_login(self.request, self.user)

        self.reset_two_factor_session()

        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = str(settings.LOGIN_REDIRECT_URL)

        res = HttpResponseRedirect(redirect_to)
        if form_list[0].is_valid():
            remember_me = form_list[0].cleaned_data['remember_me']
            if remember_me:
                s = remember_device(self.user.username)
                res.set_cookie(
                    'S2FA',
                    s.session_key,
                    max_age=settings.TWO_FACTOR_DEVICE_REMEMBER_DAYS * 24 *
                    60 * 60,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                    path=settings.SESSION_COOKIE_PATH,
                    secure=settings.SESSION_COOKIE_SECURE or None,
                    httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return res
Ejemplo n.º 2
0
Archivo: views.py Proyecto: zxhx/seahub
def token_view(request, token):
    """Show form to let user set password.
    """
    i = get_object_or_404(Invitation, token=token)
    if i.is_expired():
        raise Http404

    if request.method == 'POST':
        passwd = request.POST.get('password', '')
        if not passwd:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        try:
            User.objects.get(email=i.accepter)
            messages.error(request,
                           _('A user with this email already exists.'))
        except User.DoesNotExist:
            # Create user, set that user as guest, and log user in.
            u = User.objects.create_user(email=i.accepter,
                                         password=passwd,
                                         is_active=True)
            User.objects.update_role(u.username, GUEST_USER)

            i.accept()  # Update invitaion accept time.

            for backend in get_backends():
                u.backend = "%s.%s" % (backend.__module__,
                                       backend.__class__.__name__)
            auth_login(request, u)
            return HttpResponseRedirect(SITE_ROOT)

    return render_to_response('invitations/token_view.html', {
        'iv': i,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 3
0
def login_simple_check(request):
    """A simple check for login called by thirdpart systems(OA, etc).

    Token generation: MD5(secret_key + [email protected] + 2014-1-1).hexdigest()
    Token length: 32 hexadecimal digits.
    """
    username = request.REQUEST.get('user', '')
    random_key = request.REQUEST.get('token', '')

    if not username or not random_key:
        raise Http404

    today = datetime.now().strftime('%Y-%m-%d')
    expect = hashlib.md5(settings.SECRET_KEY+username+today).hexdigest()
    if expect == random_key:
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            raise Http404
        
        for backend in get_backends():
            user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

        auth_login(request, user)

        return HttpResponseRedirect(settings.SITE_ROOT)
    else:
        raise Http404
Ejemplo n.º 4
0
def client_token_login(request):
    """Login from desktop client with a generated token.
    """
    tokenstr = request.GET.get('token', '')
    user = None
    if len(tokenstr) == 32:
        try:
            username = ClientLoginToken.objects.get_username(tokenstr)
        except ClientLoginToken.DoesNotExist:
            pass
        else:
            try:
                user = User.objects.get(email=username)
                for backend in get_backends():
                    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
            except User.DoesNotExist:
                pass

    if user:
        if request.user.is_authenticated() and request.user.username == user.username:
            pass
        else:
            request.client_token_login = True
            auth_login(request, user)

    return HttpResponseRedirect(request.GET.get("next", reverse('libraries')))
Ejemplo n.º 5
0
def login_simple_check(request):
    """A simple check for login called by thirdpart systems(OA, etc).

    Token generation: MD5(secret_key + [email protected] + 2014-1-1).hexdigest()
    Token length: 32 hexadecimal digits.
    """
    username = request.REQUEST.get('user', '')
    random_key = request.REQUEST.get('token', '')

    if not username or not random_key:
        raise Http404

    today = datetime.now().strftime('%Y-%m-%d')
    expect = hashlib.md5(settings.SECRET_KEY + username + today).hexdigest()
    if expect == random_key:
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            raise Http404

        for backend in get_backends():
            user.backend = "%s.%s" % (backend.__module__,
                                      backend.__class__.__name__)

        auth_login(request, user)

        return HttpResponseRedirect(settings.SITE_ROOT)
    else:
        raise Http404
Ejemplo n.º 6
0
def token_view(request, token):
    """Show form to let user set password.
    """
    i = get_object_or_404(Invitation, token=token)
    if i.is_expired():
        raise Http404

    if request.method == 'POST':
        passwd = request.POST.get('password', '')
        if not passwd:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        try:
            User.objects.get(email=i.accepter)
            messages.error(request, _('A user with this email already exists.'))
        except User.DoesNotExist:
            # Create user, set that user as guest, and log user in.
            u = User.objects.create_user(email=i.accepter, password=passwd,
                                         is_active=True)
            u.role = GUEST_USER
            u.save()

            i.accept()          # Update invitaion accept time.

            for backend in get_backends():
                u.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
            auth_login(request, u)
            return HttpResponseRedirect(SITE_ROOT)

    return render_to_response('invitations/token_view.html', {
        'iv': i,
    }, context_instance=RequestContext(request))
Ejemplo n.º 7
0
def client_token_login(request):
    """Login from desktop client with a generated token.
    """
    tokenstr = request.GET.get('token', '')
    user = None
    if len(tokenstr) == 32:
        try:
            username = ClientLoginToken.objects.get_username(tokenstr)
        except ClientLoginToken.DoesNotExist:
            pass
        else:
            try:
                user = User.objects.get(email=username)
                for backend in get_backends():
                    user.backend = "%s.%s" % (backend.__module__,
                                              backend.__class__.__name__)
            except User.DoesNotExist:
                pass

    if user:
        if request.user.is_authenticated(
        ) and request.user.username == user.username:
            pass
        else:
            request.client_token_login = True
            auth_login(request, user)

    return HttpResponseRedirect(request.GET.get("next", reverse('libraries')))
Ejemplo n.º 8
0
def token_view(request, token):
    """Show form to let user set password.
    """
    i = get_object_or_404(Invitation, token=token)
    if i.is_expired():
        raise Http404

    if request.method == 'GET':
        try:
            user = User.objects.get(email=i.accepter)
            if user.is_active is True:
                # user is active return exist
                messages.error(request, _('A user with this email already exists.'))
        except User.DoesNotExist:
            pass

        return render(request, 'invitations/token_view.html', {'iv': i, })

    if request.method == 'POST':
        passwd = request.POST.get('password', '')
        if not passwd:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        try:
            user = User.objects.get(email=i.accepter)
            if user.is_active is True:
                # user is active return exist
                messages.error(request, _('A user with this email already exists.'))
                return render(request, 'invitations/token_view.html', {'iv': i, })
            else:
                # user is inactive then set active and new password
                user.set_password(passwd)
                user.is_active = True
                user.save()
                user = authenticate(username=user.username, password=passwd)

        except User.DoesNotExist:
            # Create user, set that user as guest.
            user = User.objects.create_user(
                email=i.accepter, password=passwd, is_active=True)
            User.objects.update_role(user.username, GUEST_USER)
            for backend in get_backends():
                user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

        # Update invitation accept time.
        i.accept()

        # login
        auth_login(request, user)

        # send signal to notify inviter
        accept_guest_invitation_successful.send(
            sender=None, invitation_obj=i)

        # send email to notify admin
        if NOTIFY_ADMIN_AFTER_REGISTRATION:
            notify_admins_on_register_complete(user.email)

        return HttpResponseRedirect(SITE_ROOT)
Ejemplo n.º 9
0
def demo(request):
    """
    Login as demo account.
    """
    user = User.objects.get(email=settings.CLOUD_DEMO_USER)
    for backend in get_backends():
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

    auth_login(request, user)

    redirect_to = settings.SITE_ROOT
    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 10
0
def demo(request):
    """
    Login as demo account.
    """
    user = User.objects.get(email=settings.CLOUD_DEMO_USER)
    for backend in get_backends():
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

    auth_login(request, user)

    redirect_to = settings.SITE_ROOT
    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 11
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, '')

    if request.method == "POST":
        form = authentication_form(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:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- redirects to http://example.com should
            # not be allowed, but things like /view/?param=http://example.com
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())

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

            return HttpResponseRedirect(redirect_to)

    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)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 12
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, "")

    if request.method == "POST":
        form = authentication_form(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:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- redirects to http://example.com should
            # not be allowed, but things like /view/?param=http://example.com
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif "//" in redirect_to and re.match(r"[^\?]*//", redirect_to):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())

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

            return HttpResponseRedirect(redirect_to)

    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)

    return render_to_response(
        template_name,
        {"form": form, redirect_field_name: redirect_to, "site": current_site, "site_name": current_site.name},
        context_instance=RequestContext(request),
    )
Ejemplo n.º 13
0
def log_user_in(request, user, redirect_to):
    # Ensure the user-originating redirection url is safe.
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Okay, security checks complete. Log the user in.
    auth_login(request, user)

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

    _clear_login_failed_attempts(request)

    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 14
0
    def done(self, form_list, **kwargs):
        """
        Login the user and redirect to the desired page.
        """
        redirect_to = self.request.session.get(SESSION_KEY_TWO_FACTOR_REDIRECT_URL, '') \
                      or self.request.GET.get(self.redirect_field_name, '')

        auth_login(self.request, self.user)

        self.reset_two_factor_session()

        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = str(settings.LOGIN_REDIRECT_URL)
        return redirect(redirect_to)
Ejemplo n.º 15
0
def log_user_in(request, user, redirect_to):
    # Ensure the user-originating redirection url is safe.
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Okay, security checks complete. Log the user in.
    auth_login(request, user)

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

    _clear_login_failed_attempts(request)

    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 16
0
def log_user_in(request, user, redirect_to):
    # Ensure the user-originating redirection url is safe.
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

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

    clear_login_failed_attempts(request, user.username)

    if two_factor_auth_enabled(user) and \
       not is_device_remembered(request.COOKIES.get('S2FA', ''), user):
        return handle_two_factor_auth(request, user, redirect_to)

    # Okay, security checks complete. Log the user in.
    auth_login(request, user)

    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 17
0
def demo(request):
    """
    Login as demo account.
    """

    try:
        user = User.objects.get(email=settings.CLOUD_DEMO_USER)
    except User.DoesNotExist:
        user = User.objects.create_user(settings.CLOUD_DEMO_USER, is_active=True)
        user.set_unusable_password()
        user.save()

    for backend in get_backends():
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

    auth_login(request, user)

    redirect_to = settings.SITE_ROOT
    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 18
0
def log_user_in(request, user, redirect_to):
    # Light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
            
    # Heavier security check -- redirects to http://example.com should 
    # not be allowed, but things like /view/?param=http://example.com 
    # should be allowed. This regex checks if there is a '//' *before* a
    # question mark.
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Okay, security checks complete. Log the user in.
    auth_login(request, user)

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

    cache.delete(LOGIN_ATTEMPT_PREFIX+user.username)

    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 19
0
def log_user_in(request, user, redirect_to):
    # Light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
            
    # Heavier security check -- redirects to http://example.com should 
    # not be allowed, but things like /view/?param=http://example.com 
    # should be allowed. This regex checks if there is a '//' *before* a
    # question mark.
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Okay, security checks complete. Log the user in.
    auth_login(request, user)

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

    cache.delete(LOGIN_ATTEMPT_PREFIX+user.username)

    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 20
0
def demo(request):
    """
    Login as demo account.
    """
    from django.conf import settings as dj_settings
    if not dj_settings.ENABLE_DEMO_USER:
        raise Http404

    try:
        user = User.objects.get(email=settings.CLOUD_DEMO_USER)
    except User.DoesNotExist:
        logger.warn('CLOUD_DEMO_USER: %s does not exist.' % settings.CLOUD_DEMO_USER)
        raise Http404

    for backend in get_backends():
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

    auth_login(request, user)

    redirect_to = settings.SITE_ROOT
    return HttpResponseRedirect(redirect_to)
Ejemplo n.º 21
0
def token_view(request, token):
    """Show form to let user set password.
    """
    i = get_object_or_404(Invitation, token=token)
    if i.is_expired():
        raise Http404

    if request.method == 'POST':
        passwd = request.POST.get('password', '')
        if not passwd:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        try:
            User.objects.get(email=i.accepter)
            messages.error(request, _('A user with this email already exists.'))
        except User.DoesNotExist:
            # Create user, set that user as guest, and log user in.
            u = User.objects.create_user(email=i.accepter, password=passwd,
                                         is_active=True)
            User.objects.update_role(u.username, GUEST_USER)

            i.accept()          # Update invitaion accept time.

            for backend in get_backends():
                u.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
            auth_login(request, u)

            # send signal to notify inviter
            accept_guest_invitation_successful.send(
                sender=None, invitation_obj=i)

            # send email to notify admin
            if NOTIFY_ADMIN_AFTER_REGISTRATION:
                notify_admins_on_register_complete(u.email)

            return HttpResponseRedirect(SITE_ROOT)

    return render(request, 'invitations/token_view.html', {
        'iv': i,
    })
Ejemplo n.º 22
0
def login_simple_check(request):
    """A simple check for login called by thirdpart systems(OA, etc).

    Token generation: MD5(secret_key + [email protected] + 2014-1-1).hexdigest()
    Token length: 32 hexadecimal digits.
    """
    username = request.GET.get('user', '')
    random_key = request.GET.get('token', '')

    if not username or not random_key:
        raise Http404

    today = datetime.now().strftime('%Y-%m-%d')
    expect = hashlib.md5(
        (settings.SECRET_KEY + username + today).encode('utf-8')).hexdigest()
    if expect == random_key:
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            raise Http404

        for backend in get_backends():
            user.backend = "%s.%s" % (backend.__module__,
                                      backend.__class__.__name__)

        auth_login(request, user)

        # Ensure the user-originating redirection url is safe.
        if REDIRECT_FIELD_NAME in request.GET:
            next_page = request.GET[REDIRECT_FIELD_NAME]
            if not is_safe_url(url=next_page,
                               allowed_hosts=request.get_host()):
                next_page = settings.LOGIN_REDIRECT_URL
        else:
            next_page = settings.SITE_ROOT

        return HttpResponseRedirect(next_page)
    else:
        raise Http404
Ejemplo n.º 23
0
def assertion_consumer_service(request,
                               config_loader_path=None,
                               attribute_mapping=None,
                               create_unknown_user=None):
    """SAML Authorization Response endpoint

    The IdP will send its response to this view, which
    will process it with pysaml2 help and log the user
    in using the custom Authorization backend
    djangosaml2.backends.Saml2Backend that should be
    enabled in the settings.py
    """
    attribute_mapping = attribute_mapping or get_custom_setting(
        'SAML_ATTRIBUTE_MAPPING', {'uid': ('username', )})
    create_unknown_user = create_unknown_user or get_custom_setting(
        'SAML_CREATE_UNKNOWN_USER', True)
    logger.debug('Assertion Consumer Service started')

    conf = get_config(config_loader_path, request)
    if 'SAMLResponse' not in request.POST:
        return HttpResponseBadRequest(
            'Couldn\'t find "SAMLResponse" in POST data.')
    xmlstr = request.POST['SAMLResponse']
    client = Saml2Client(conf, identity_cache=IdentityCache(request.session))

    oq_cache = OutstandingQueriesCache(request.session)
    outstanding_queries = oq_cache.outstanding_queries()

    try:
        response = client.parse_authn_request_response(xmlstr,
                                                       BINDING_HTTP_POST,
                                                       outstanding_queries)
    except MissingKey:
        logger.error('MissingKey error in ACS')
        return HttpResponseForbidden(
            "The Identity Provider is not configured correctly: "
            "the certificate key is missing")
    if response is None:
        logger.error('SAML response is None')
        return HttpResponseBadRequest(
            "SAML response has errors. Please check the logs")

    session_id = response.session_id()
    oq_cache.delete(session_id)

    # authenticate the remote user
    session_info = response.session_info()

    if callable(attribute_mapping):
        attribute_mapping = attribute_mapping()
    if callable(create_unknown_user):
        create_unknown_user = create_unknown_user()

    logger.debug('Trying to authenticate the user')
    user = auth.authenticate(session_info=session_info,
                             attribute_mapping=attribute_mapping,
                             create_unknown_user=create_unknown_user)
    if user is None:
        logger.error('The user is None')
        return HttpResponseForbidden("Permission denied")

    if not user.is_active:
        logger.error('The user is inactive')
        return HttpResponseForbidden("Permission denied")

    auth_login(request, user)
    _set_subject_id(request.session, session_info['name_id'])

    logger.debug('Sending the post_authenticated signal')
    post_authenticated.send_robust(sender=user, session_info=session_info)

    # redirect the user to the view where he came from
    default_relay_state = get_custom_setting('ACS_DEFAULT_REDIRECT_URL',
                                             settings.LOGIN_REDIRECT_URL)
    relay_state = request.POST.get('RelayState', default_relay_state)
    if not relay_state:
        logger.warning('The RelayState parameter exists but is empty')
        relay_state = default_relay_state
    logger.debug('Redirecting to the RelayState: %s', relay_state)
    return HttpResponseRedirect(relay_state)
Ejemplo n.º 24
0
def token_view(request, token):
    """Show form to let user set password.
    """
    i = get_object_or_404(Invitation, token=token)
    if i.is_expired():
        raise Http404

    if request.method == 'GET':
        try:
            user = User.objects.get(email=i.accepter)
            if user.is_active is True:
                # user is active return exist
                messages.error(request,
                               _('A user with this email already exists.'))
        except User.DoesNotExist:
            pass

        return render(request, 'invitations/token_view.html', {
            'iv': i,
        })

    if request.method == 'POST':
        passwd = request.POST.get('password', '')
        if not passwd:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        try:
            user = User.objects.get(email=i.accepter)
            if user.is_active is True:
                # user is active return exist
                messages.error(request,
                               _('A user with this email already exists.'))
                return render(request, 'invitations/token_view.html', {
                    'iv': i,
                })
            else:
                # user is inactive then set active and new password
                user.set_password(passwd)
                user.is_active = True
                user.save()
                user = authenticate(username=user.username, password=passwd)

        except User.DoesNotExist:
            # Create user, set that user as guest.
            user = User.objects.create_user(email=i.accepter,
                                            password=passwd,
                                            is_active=True)
            User.objects.update_role(user.username, GUEST_USER)
            for backend in get_backends():
                user.backend = "%s.%s" % (backend.__module__,
                                          backend.__class__.__name__)

        # Update invitation accept time.
        i.accept()

        # login
        auth_login(request, user)

        # send signal to notify inviter
        accept_guest_invitation_successful.send(sender=None, invitation_obj=i)

        # send email to notify admin
        if NOTIFY_ADMIN_AFTER_REGISTRATION:
            notify_admins_on_register_complete(user.email)

        # repo share invitation
        try:
            shared_queryset = RepoShareInvitation.objects.list_by_invitation(
                invitation=i)
            accepter = i.accepter

            for shared_obj in shared_queryset:
                repo_id = shared_obj.repo_id
                path = shared_obj.path
                permission = shared_obj.permission
                inviter = shared_obj.invitation.inviter

                # recourse check
                repo = seafile_api.get_repo(repo_id)
                if not repo:
                    logger.warning(
                        '[ %s ] repo not found when [ %s ] accepts the invitation to share repo'
                    ) % (repo_id, accepter)
                    continue
                if seafile_api.get_dir_id_by_path(repo.id, path) is None:
                    logger.warning(
                        '[ %s ][ %s ] dir not found when [ %s ] accepts the invitation to share repo'
                    ) % (repo_id, path, accepter)
                    continue

                repo_owner = seafile_api.get_repo_owner(repo_id)
                share_dir_to_user(repo, path, repo_owner, inviter, accepter,
                                  permission, None)

                send_perm_audit_msg('modify-repo-perm', inviter, accepter,
                                    repo_id, path, permission)

            # delete
            shared_queryset.delete()
        except Exception as e:
            logger.error(e)

        return HttpResponseRedirect(SITE_ROOT)
Ejemplo n.º 25
0
def login(request, next_page=None, required=False):
    """Forwards to CAS login URL or verifies CAS ticket"""
    service_url = get_service_url(request, next_page)
    client = get_cas_client(service_url=service_url, request=request)

    if not next_page and settings.CAS_STORE_NEXT and 'CASNEXT' in request.session:
        next_page = request.session['CASNEXT']
        del request.session['CASNEXT']

    if not next_page:
        next_page = get_redirect_url(request)

    if request.method == 'POST' and request.POST.get('logoutRequest'):
        clean_sessions(client, request)
        return HttpResponseRedirect(next_page)

    # backward compability for django < 2.0
    is_user_authenticated = False

    if sys.version_info >= (3, 0):
        bool_type = bool
    else:
        bool_type = types.BooleanType

    if isinstance(request.user.is_authenticated, bool_type):
        is_user_authenticated = request.user.is_authenticated
    else:
        is_user_authenticated = request.user.is_authenticated()

    if is_user_authenticated:
        if settings.CAS_LOGGED_MSG is not None:
            message = settings.CAS_LOGGED_MSG % request.user.get_username()
            messages.success(request, message)
        return HttpResponseRedirect(next_page)

    ticket = request.GET.get('ticket')
    if ticket:
        user = authenticate(ticket=ticket,
                            service=service_url,
                            request=request)
        pgtiou = request.session.get("pgtiou")
        if user is not None:
            if not request.session.exists(request.session.session_key):
                request.session.create()
            auth_login(request, user)
            SessionTicket.objects.create(
                session_key=request.session.session_key, ticket=ticket)

            if pgtiou and settings.CAS_PROXY_CALLBACK:
                # Delete old PGT
                ProxyGrantingTicket.objects.filter(
                    user=user,
                    session_key=request.session.session_key).delete()
                # Set new PGT ticket
                try:
                    pgt = ProxyGrantingTicket.objects.get(pgtiou=pgtiou)
                    pgt.user = user
                    pgt.session_key = request.session.session_key
                    pgt.save()
                except ProxyGrantingTicket.DoesNotExist:
                    pass

            if settings.CAS_LOGIN_MSG is not None:
                name = user.get_username()
                message = settings.CAS_LOGIN_MSG % name
                messages.success(request, message)
            return HttpResponseRedirect(next_page)
        elif settings.CAS_RETRY_LOGIN or required:
            return HttpResponseRedirect(client.get_login_url())
        else:
            raise PermissionDenied(_('Login failed.'))
    else:
        if settings.CAS_STORE_NEXT:
            request.session['CASNEXT'] = next_page
        return HttpResponseRedirect(client.get_login_url())