Exemplo n.º 1
0
def test_login_authenticate_do_not_create_user(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a user, but does not
    create a user based on the CAS_CREATE_USER setting.
    """
    # No need to test the message framework
    settings.CAS_CREATE_USER = False
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    with pytest.raises(PermissionDenied):
        login(request)
    assert django_user_model.objects.filter(username='******').exists() is False
Exemplo n.º 2
0
def test_login_authenticate_do_not_create_user(monkeypatch, django_user_model,
                                               settings):
    """
    Test the case where the login view authenticates a user, but does not
    create a user based on the CAS_CREATE_USER setting.
    """
    # No need to test the message framework
    settings.CAS_CREATE_USER = False
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {
        'ticket': 'fake-ticket',
        'service': 'fake-service'
    })

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    with pytest.raises(PermissionDenied):
        login(request)
    assert django_user_model.objects.filter(
        username='******').exists() is False
Exemplo n.º 3
0
def test_login_post_logout(django_user_model, settings):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = True`
    """
    settings.CAS_VERSION = 'CAS_2_SAML_1_0'

    data = {
        'logoutRequest':
        '<samlp:LogoutRequest '
        'xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">'
        '<samlp:SessionIndex>fake-ticket'
        '</samlp:SessionIndex></samlp:LogoutRequest>'
    }
    session = SessionStore()
    session['fake_session'] = 'fake-session'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    factory = RequestFactory()
    request = factory.post('/login/', data)
    request.session = session

    # Create a fake session ticket and make sure it exists in the db
    session_ticket = SessionTicket.objects.create(
        session_key=session.session_key, ticket='fake-ticket')
    assert session_ticket is not None
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is True
    user = django_user_model.objects.create(username='******',
                                            email='*****@*****.**')
    assert user is not None
    assert django_user_model.objects.filter(
        username='******').exists() is True
    request.user = user

    # Create a fake pgt
    pgt = ProxyGrantingTicket.objects.create(session_key=session.session_key,
                                             user=user,
                                             pgtiou='fake-ticket-iou',
                                             pgt='fake-ticket')
    assert pgt is not None
    assert ProxyGrantingTicket.objects.filter(
        session_key=session.session_key,
        user=user,
        pgtiou='fake-ticket-iou',
        pgt='fake-ticket').exists() is True

    login(request)
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is False
    assert ProxyGrantingTicket.objects.filter(
        session_key=session.session_key,
        user=user,
        pgtiou='fake-ticket-iou',
        pgt='fake-ticket').exists() is False
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is False
Exemplo n.º 4
0
def test_login_post_logout(django_user_model, settings):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = True`
    """
    settings.CAS_VERSION = 'CAS_2_SAML_1_0'

    data = {'logoutRequest': '<samlp:LogoutRequest '
                             'xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">'
                             '<samlp:SessionIndex>fake-ticket'
                             '</samlp:SessionIndex></samlp:LogoutRequest>'
            }
    session = SessionStore()
    session['fake_session'] = 'fake-session'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    factory = RequestFactory()
    request = factory.post('/login/', data)
    request.session = session

    # Create a fake session ticket and make sure it exists in the db
    session_ticket = SessionTicket.objects.create(
        session_key=session.session_key,
        ticket='fake-ticket'
    )
    assert session_ticket is not None
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is True
    user = django_user_model.objects.create(username='******', email='*****@*****.**')
    assert user is not None
    assert django_user_model.objects.filter(username='******').exists() is True
    request.user = user

    # Create a fake pgt
    pgt = ProxyGrantingTicket.objects.create(session_key=session.session_key,
                                       user=user, pgtiou='fake-ticket-iou',
                                       pgt='fake-ticket')
    assert pgt is not None
    assert ProxyGrantingTicket.objects.filter(session_key=session.session_key,
                                       user=user, pgtiou='fake-ticket-iou',
                                       pgt='fake-ticket').exists() is True

    login(request)
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is False
    assert ProxyGrantingTicket.objects.filter(session_key=session.session_key,
                                       user=user, pgtiou='fake-ticket-iou',
                                       pgt='fake-ticket').exists() is False
    assert SessionTicket.objects.filter(session_key=session.session_key,
                                        ticket='fake-ticket').exists() is False
Exemplo n.º 5
0
def test_login_authenticate_and_create_user(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a new user.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302
    assert django_user_model.objects.get(username='******').is_authenticated() is True
Exemplo n.º 6
0
    def wrapper(request, *args, **kwargs):
        try:
            if isinstance(request.user, AnonymousUser):
                ticket = request.GET.get("ticket", "")
                if ticket:
                    logger.info('caslogin--ticket=%s', ticket)
                    return cas_views.login(request, next_page=request.get_full_path())

                # 未登陆用户,先获取用户的code,为获取openid做准备
                if check_weixin_agent(request):
                    state = convert_from_url_path('http://' + request.META.get('HTTP_HOST', "") + request.get_full_path())

                    if not state:
                        return HttpResponseForbidden()
                    else:
                        return HttpResponseRedirect("/wx/authorize_fhlogin?state=%s" % state)
                else:
                    return HttpResponseForbidden('<h1>Forbidden<br/> 请从微信上登陆使用本系统</h1>')

            else:
                # 已登陆用户,获取用户当前所在学校,然后跳转到该学校的首页
                if check_weixin_agent(request):
                    return HttpResponseRedirect("/m?sid=%s" % request.user.school.id)
                else:
                    return HttpResponseForbidden('<h1>Forbidden<br/> 请从微信登陆使用本系统</h1>')

        except Exception as ex:
            sErrInfo = traceback.format_exc()
            logger.error(sErrInfo)
            return HttpResponseForbidden('<h1>Forbidden</h1>')
Exemplo n.º 7
0
def page_login(request, next_page=None):
    if not isinstance(request.user, AnonymousUser):
        page_logout(request)
    if settings.CAS_AUTH:
        return cas_views.login(request, next_page=next_page)
    else:
        return render_to_response('page/base/login/login.html')
Exemplo n.º 8
0
def test_login_authenticate_and_create_user(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a new user.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302
    assert django_user_model.objects.get(username='******').is_authenticated() is True
Exemplo n.º 9
0
def cas_login(request, **kwargs):
    r = baseviews.login(request, **kwargs)
    if not request.user.is_anonymous():
        token = get_token(request)
        if token:
            r.set_cookie('token', token)
        else:
            print 'Get token error'
    else:
        print('User is anonymous')
    return r
Exemplo n.º 10
0
def test_login_proxy_callback(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view has a pgtiou.
    """
    # No need to test the message framework
    settings.CAS_PROXY_CALLBACK = True
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {
        'ticket': 'fake-ticket',
        'service': 'fake-service'
    })

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    request.session['pgtiou'] = 'fake-pgtiou'
    request.session.save()

    user = django_user_model.objects.create_user('*****@*****.**', '')
    assert user is not None
    pgt = ProxyGrantingTicket.objects.create(
        session_key=request.session.session_key,
        user=user,
        pgtiou='fake-pgtiou',
        pgt='fake-pgt')
    assert pgt is not None

    response = login(request)
    assert response.status_code == 302
    if django.VERSION[0] < 2:
        assert django_user_model.objects.get(
            username='******').is_authenticated() is True
    else:
        assert django_user_model.objects.get(
            username='******').is_authenticated is True
    assert ProxyGrantingTicket.objects.filter(
        pgtiou='fake-pgtiou').exists() is True
    assert ProxyGrantingTicket.objects.filter(
        pgtiou='fake-pgtiou').count() == 1
Exemplo n.º 11
0
def test_login_no_ticket():
    """
    Test the case where we try to login with no ticket
    """
    factory = RequestFactory()
    request = factory.get('/login/')

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302
Exemplo n.º 12
0
def test_login_no_ticket():
    """
    Test the case where we try to login with no ticket
    """
    factory = RequestFactory()
    request = factory.get('/login/')

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302
Exemplo n.º 13
0
def test_login_no_ticket_stores_explicit_next(settings):
    """
    When there is an explicit next pointer, it gets stored in the cookie
    """
    settings.CAS_STORE_NEXT = True

    factory = RequestFactory()
    request = factory.get('/login/', {'next': '/admin/'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302

    assert 'CASNEXT' in request.session
    assert request.session['CASNEXT'] == '/admin/'
Exemplo n.º 14
0
def test_signal_when_user_logout_slo(monkeypatch, django_user_model, settings):
    data = {'logoutRequest': '<samlp:LogoutRequest '
                             'xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">'
                             '<samlp:SessionIndex>fake-ticket'
                             '</samlp:SessionIndex></samlp:LogoutRequest>'
           }

    settings.CAS_VERSION = 'CAS_2_SAML_1_0'

    factory = RequestFactory()
    request = factory.post('/login', data)
    # user session and current requests.session are different
    request.session = {}

    user = django_user_model.objects.create_user('*****@*****.**', '')
    assert user is not None


    session = SessionStore()
    session['fake_session_key'] = 'fake-session_value'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    # Create a fake session ticket and make sure it exists in the db
    session_ticket = SessionTicket.objects.create(
        session_key=session.session_key,
        ticket='fake-ticket'
    )

    callback_values = {}

    @receiver(cas_user_logout)
    def callback(sender, session, **kwargs):
        callback_values.update(kwargs)
        callback_values['session'] = dict(session)


    response = login(request)
    assert 'user' in callback_values
    assert 'session' in callback_values
    assert callback_values['session'].get('fake_session_key') == 'fake-session_value'
    assert 'ticket' in callback_values
    assert callback_values['ticket'] == 'fake-ticket'
Exemplo n.º 15
0
def test_login_redirect_based_on_cookie(monkeypatch, django_user_model,
                                        settings):
    """
    Test the case where the login view authenticates a new user and redirects them based on cookie.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
    # Store next as cookie
    settings.CAS_STORE_NEXT = True

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {
        'ticket': 'fake-ticket',
        'service': 'fake-service'
    })

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    # Add the next pointer
    request.session['CASNEXT'] = '/admin/'

    response = login(request)
    assert response.status_code == 302
    assert response['Location'] == '/admin/'

    assert 'CASNEXT' not in request.session
    if django.VERSION[0] < 2:
        assert django_user_model.objects.get(
            username='******').is_authenticated() is True
    else:
        assert django_user_model.objects.get(
            username='******').is_authenticated is True
Exemplo n.º 16
0
def test_login_proxy_callback(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view has a pgtiou.
    """
    # No need to test the message framework
    settings.CAS_PROXY_CALLBACK = True
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    request.session['pgtiou'] = 'fake-pgtiou'
    request.session.save()

    user = django_user_model.objects.create_user('*****@*****.**', '')
    assert user is not None
    pgt = ProxyGrantingTicket.objects.create(session_key=request.session.session_key,
                                             user=user, pgtiou='fake-pgtiou',
                                             pgt='fake-pgt')
    assert pgt is not None

    response = login(request)
    assert response.status_code == 302
    if django.VERSION[0] < 2:
        assert django_user_model.objects.get(username='******').is_authenticated() is True
    else:
        assert django_user_model.objects.get(username='******').is_authenticated is True
    assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').exists() is True
    assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').count() == 1
Exemplo n.º 17
0
def test_login_no_ticket_stores_explicit_next(settings):
    """
    When there is an explicit next pointer, it gets stored in the cookie
    """
    settings.CAS_STORE_NEXT = True

    factory = RequestFactory()
    request = factory.get('/login/', {'next': '/admin/'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = login(request)
    assert response.status_code == 302

    assert 'CASNEXT' in request.session
    assert request.session['CASNEXT'] == '/admin/'
Exemplo n.º 18
0
def test_signal_when_user_logout_slo(monkeypatch, django_user_model, settings):
    data = {
        'logoutRequest':
        '<samlp:LogoutRequest '
        'xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">'
        '<samlp:SessionIndex>fake-ticket'
        '</samlp:SessionIndex></samlp:LogoutRequest>'
    }

    settings.CAS_VERSION = 'CAS_2_SAML_1_0'

    factory = RequestFactory()
    request = factory.post('/login', data)
    # user session and current requests.session are different
    request.session = {}

    user = django_user_model.objects.create_user('*****@*****.**', '')
    assert user is not None

    session = SessionStore()
    session['fake_session_key'] = 'fake-session_value'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    # Create a fake session ticket and make sure it exists in the db
    session_ticket = SessionTicket.objects.create(
        session_key=session.session_key, ticket='fake-ticket')

    callback_values = {}

    @receiver(cas_user_logout)
    def callback(sender, session, **kwargs):
        callback_values.update(kwargs)
        callback_values['session'] = dict(session)

    response = login(request)
    assert 'user' in callback_values
    assert 'session' in callback_values
    assert callback_values['session'].get(
        'fake_session_key') == 'fake-session_value'
    assert 'ticket' in callback_values
    assert callback_values['ticket'] == 'fake-ticket'
Exemplo n.º 19
0
    def wrapper(request, *args, **kwargs):
        try:
            if isinstance(request.user, AnonymousUser):
                ticket = request.GET.get("ticket", "")
                if ticket:
                    logger.info('caslogin--ticket=%s', ticket)
                    return cas_views.login(request, next_page=request.get_full_path())

                if check_weixin_agent(request):

                    school_id = request.GET.get("sid", "")
                    state = convert_from_url_path('http://' + request.META.get('HTTP_HOST', "") + request.get_full_path())
                    # print state
                    if not state:
                        return HttpResponseForbidden()
                    else:
                        return HttpResponseRedirect("/wx/authorize?state=" + state + "&sid=" + school_id)
                else:

                    token = request.GET.get("t", "")
                    now = datetime.datetime.now()
                    due_date = now + datetime.timedelta(hours=1)
                    # login_code = LoginCode.objects.filter(value=token, create_time__lt=due_date, del_flag=FLAG_NO).first()
                    login_code = None  # 暂时不允许直接通过token登陆。后面有需要再改,可能会通过openid登陆。
                    if not login_code:
                        return HttpResponseForbidden('<h1>Forbidden<br/> 请从手机微信公众号上登陆使用本系统</h1>')
                    else:
                        login_code.del_flag = FLAG_YES
                        auth.login(request, login_code.account)
                        login_code.save()
                        return view_func(request, *args, **kwargs)
            else:
                return view_func(request, *args, **kwargs)
        except Exception as ex:
            sErrInfo = traceback.format_exc()
            logger.error(sErrInfo)
            return HttpResponseForbidden('<h1>Forbidden</h1>')
Exemplo n.º 20
0
def test_login_redirect_based_on_cookie(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a new user and redirects them based on cookie.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
    # Store next as cookie
    settings.CAS_STORE_NEXT = True

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    # Add the next pointer
    request.session['CASNEXT'] = '/admin/'

    response = login(request)
    assert response.status_code == 302
    assert response['Location'] == '/admin/'

    assert 'CASNEXT' not in request.session
    if django.VERSION[0] < 2:
        assert django_user_model.objects.get(username='******').is_authenticated() is True
    else:
        assert django_user_model.objects.get(username='******').is_authenticated is True
Exemplo n.º 21
0
def test_login_delete_not_allowed():
    factory = RequestFactory()
    request = factory.delete('/login/')
    response = login(request)
    assert response.status_code == 405
Exemplo n.º 22
0
def test_login_delete_not_allowed():
    factory = RequestFactory()
    request = factory.delete('/login/')
    response = login(request)
    assert response.status_code == 405
Exemplo n.º 23
0
def cas_login(request):
    return cas_views.login(request)
Exemplo n.º 24
0
def login(request, **kwargs):
    return casviews.login(request, **kwargs)
Exemplo n.º 25
0
def page_login(request):
    return cas_views.login(request)