当前位置: 首页>>代码示例>>Python>>正文


Python ApiKeyAuthentication.is_authenticated方法代码示例

本文整理汇总了Python中tastypie.authentication.ApiKeyAuthentication.is_authenticated方法的典型用法代码示例。如果您正苦于以下问题:Python ApiKeyAuthentication.is_authenticated方法的具体用法?Python ApiKeyAuthentication.is_authenticated怎么用?Python ApiKeyAuthentication.is_authenticated使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tastypie.authentication.ApiKeyAuthentication的用法示例。


在下文中一共展示了ApiKeyAuthentication.is_authenticated方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_is_authenticated

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_is_authenticated(self):
        auth = ApiKeyAuthentication()
        request = HttpRequest()

        # Simulate sending the signal.
        john_doe = User.objects.get(username="johndoe")
        create_api_key(User, instance=john_doe, created=True)

        # No username/api_key details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong username details.
        request.GET["username"] = "foo"
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No api_key.
        request.GET["username"] = "daniel"
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/api_key.
        request.GET["username"] = "daniel"
        request.GET["api_key"] = "foo"
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/api_key.
        john_doe = User.objects.get(username="johndoe")
        request.GET["username"] = "johndoe"
        request.GET["api_key"] = john_doe.api_key.key
        self.assertEqual(auth.is_authenticated(request), True)
开发者ID:thepeopleseason,项目名称:django-tastypie,代码行数:31,代码来源:authentication.py

示例2: test_is_authenticated_get_params

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_is_authenticated_get_params(self):
        auth = ApiKeyAuthentication()
        request = HttpRequest()

        # Simulate sending the signal.
        john_doe = CustomUser.objects.get(pk=1)
        create_api_key(CustomUser, instance=john_doe, created=True)

        # No username/api_key details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong username (email) details.
        request.GET['username'] = '[email protected]'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No api_key.
        request.GET['username'] = john_doe.email
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/api_key.
        request.GET['username'] = john_doe.email
        request.GET['api_key'] = 'foo'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/api_key.
        ApiKey.objects.all().delete()
        create_api_key(CustomUser, instance=john_doe, created=True)
        request.GET['username'] = john_doe.email
        request.GET['api_key'] = john_doe.api_key.key
        self.assertEqual(auth.is_authenticated(request), True)
        self.assertEqual(auth.get_identifier(request), john_doe.email)
开发者ID:Alexander-Attar,项目名称:django-tastypie,代码行数:33,代码来源:custom_user.py

示例3: test_is_authenticated

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
 def test_is_authenticated(self):
     auth = ApiKeyAuthentication()
     request = HttpRequest()
     
     # No username/api_key details should fail.
     self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)
     
     # Wrong username details.
     request.GET['username'] = 'foo'
     self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)
     
     # No api_key.
     request.GET['username'] = 'daniel'
     self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)
     
     # Wrong user/api_key.
     request.GET['username'] = 'daniel'
     request.GET['api_key'] = 'foo'
     self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)
     
     # Correct user/api_key.
     john_doe = User.objects.get(username='johndoe')
     john_doe.save()
     request.GET['username'] = 'johndoe'
     request.GET['api_key'] = john_doe.api_key.key
     self.assertEqual(auth.is_authenticated(request), True)
开发者ID:Concert,项目名称:django-tastypie,代码行数:28,代码来源:authentication.py

示例4: test_is_authenticated_header

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_is_authenticated_header(self):
        auth = ApiKeyAuthentication()
        request = HttpRequest()

        # Simulate sending the signal.
        john_doe = User.objects.get(username='johndoe')
        create_api_key(User, instance=john_doe, created=True)

        # No username/api_key details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong username details.
        request.META['HTTP_AUTHORIZATION'] = 'foo'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No api_key.
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/api_key.
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel:pass'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/api_key.
        john_doe = User.objects.get(username='johndoe')
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey johndoe:%s' % john_doe.api_key.key
        self.assertEqual(auth.is_authenticated(request), True)
开发者ID:Unholster,项目名称:django-tastypie,代码行数:29,代码来源:authentication.py

示例5: test_is_authenticated_get_params

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_is_authenticated_get_params(self):
        auth = ApiKeyAuthentication()
        request = HttpRequest()

        # Simulate sending the signal.
        john_doe = User.objects.get(username='johndoe')
        create_api_key(User, instance=john_doe, created=True)

        # No username/api_key details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong username details.
        request.GET['username'] = 'foo'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No api_key.
        request.GET['username'] = 'daniel'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/api_key.
        request.GET['username'] = 'daniel'
        request.GET['api_key'] = 'foo'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/api_key.
        john_doe = User.objects.get(username='johndoe')
        request.GET['username'] = 'johndoe'
        request.GET['api_key'] = john_doe.api_key.key
        self.assertEqual(auth.is_authenticated(request), True)
        self.assertEqual(auth.get_identifier(request), 'johndoe')
开发者ID:mthornhill,项目名称:django-tastypie,代码行数:32,代码来源:authentication.py

示例6: test_check_active_true

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_check_active_true(self):
        auth = ApiKeyAuthentication()
        request = HttpRequest()

        bob_doe = User.objects.get(username='bobdoe')
        create_api_key(User, instance=bob_doe, created=True)
        create_api_key(User, instance=bob_doe, created=True)

        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_keys.all()[0].key
        self.assertFalse(auth.is_authenticated(request))

        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_keys.all()[1].key
        self.assertFalse(auth.is_authenticated(request))
开发者ID:dekoza,项目名称:django-biscuit,代码行数:15,代码来源:authentication.py

示例7: image_view

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
def image_view(request):

    if request.method != 'POST':
        return HttpResponse(status=HTML_METHOD_NOT_ALLOWED)

    auth = ApiKeyAuthentication()
    auth_result = auth.is_authenticated(request)
    if auth_result == False:
        return HttpResponse(status=HTML_UNAUTHORIZED)
    elif auth_result != True:
        return auth_result

    required_params = ['resource_id']

    for r in required_params:
        if r not in request.POST:
            return HttpResponse(status=HTML_BADREQUEST, content='{ "error": "No ' + r + ' provided"}')

    if 'image_file' not in request.FILES:
        return HttpResponse(status=HTML_BADREQUEST, content='{ "error": "No image file provided"}')

    # check owner of resource
    resource_id = request.POST['resource_id']
    try:
        resource = Resource.objects.get(
            create_user=request.user, pk=resource_id)
    except Resource.DoesNotExist:
        return HttpResponse(status=HTML_UNAUTHORIZED)

    # handle file upload
    resource.image = request.FILES['image_file']
    resource.save()

    return HttpResponse(status=HTML_CREATED)
开发者ID:wellfire,项目名称:django-orb,代码行数:36,代码来源:upload.py

示例8: monitor_cohort_progress_view

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
def monitor_cohort_progress_view(request, cohort_id, course_id):
    auth = ApiKeyAuthentication()
    if auth.is_authenticated(request) is not True:
        return HttpResponse("Unauthorized", status=401)
    now = datetime.datetime.now()
    key = ApiKey.objects.get(user=request.user)
    request.user.key = key.key
    cohort = get_object_or_404(
        Cohort,
        pk=cohort_id,
        participant__user=request.user,
        participant__role=Participant.TEACHER,
        start_date__lte=now,
        end_date__gte=now,
    )
    course = get_object_or_404(Course, coursecohort__cohort=cohort, pk=course_id)
    record_mobile_tracker(request, course, "monitor", '{"en": "progress"}')

    sections = Section.objects.filter(course=course, order__gt=0).order_by("order")
    section_list = {}
    for s in sections:
        section_list[s.id] = Activity.objects.filter(section=s).values("digest").distinct()
    participants = Participant.objects.filter(cohort=cohort, role=Participant.STUDENT).order_by("user__first_name")

    paginator = Paginator(participants, 25)
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

    try:
        students = paginator.page(page)
        for p in students:
            p.sections = []
            for s in sections:
                user_completed = (
                    Tracker.objects.filter(user=p.user, completed=True, digest__in=section_list[s.id])
                    .values("digest")
                    .distinct()
                )
                user_started = (
                    Tracker.objects.filter(user=p.user, completed=False, digest__in=section_list[s.id])
                    .values("digest")
                    .distinct()
                )
                temp = {
                    "completed": user_completed.count() * 100 / section_list[s.id].count(),
                    "started": user_started.count() * 100 / section_list[s.id].count(),
                    "section": s,
                }
                p.sections.append(temp)
    except (EmptyPage, InvalidPage):
        tracks = paginator.page(paginator.num_pages)

    return render_to_response(
        "oppia/mobile/monitor/progress.html",
        {"cohort": cohort, "course": course, "participants": students, "user": request.user},
        context_instance=RequestContext(request),
    )
开发者ID:kingctan,项目名称:django-oppia,代码行数:62,代码来源:views.py

示例9: scorecard_view

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
def scorecard_view(request):
    auth = ApiKeyAuthentication()
    if auth.is_authenticated(request) is not True:
        return HttpResponse("Unauthorized", status=401)

    record_mobile_tracker(request, None, "scorecard", '{"en":"homepage"}')

    start_date = datetime.datetime.now() - datetime.timedelta(days=14)
    end_date = datetime.datetime.now()
    media = {
        "views": Tracker.activity_views(user=request.user, type="media", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="media", start_date=start_date, end_date=end_date),
        "points": Points.media_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    quiz = {
        "views": Tracker.activity_views(user=request.user, type="quiz", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="quiz", start_date=start_date, end_date=end_date),
        "points": Points.quiz_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    acts = {
        "views": Tracker.activity_views(user=request.user, type="page", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="page", start_date=start_date, end_date=end_date),
        "points": Points.page_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    total = {
        "views": acts["views"] + quiz["views"] + media["views"],
        "secs": acts["secs"] + quiz["secs"] + media["secs"],
        "points": acts["points"] + quiz["points"] + media["points"],
    }
    scorecard = {"media": media, "quiz": quiz, "acts": acts, "total": total}
    return render_to_response(
        "oppia/mobile/scorecard.html", {"scorecard": scorecard}, context_instance=RequestContext(request)
    )
开发者ID:kingctan,项目名称:django-oppia,代码行数:35,代码来源:views.py

示例10: change_password

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def change_password(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        apikey_auth = ApiKeyAuthentication()
        if apikey_auth.is_authenticated(request) == True:
            data = self.deserialize(request, request.body,
                                    format=request.META.get('CONTENT_TYPE', 'application/json'))
            if request.user.has_usable_password():
                password_change_form = ChangePasswordForm(request.user, data)
            else:
                password_change_form = SetPasswordForm(request.user, data)

            if password_change_form.is_valid():
                password_change_form.save()
                response_data = {'status': "success"}
                if request.user.is_authenticated():
                    logout(request)
            else:
                if request.user.is_authenticated():
                    logout(request)
                return self.create_response(request, {
                    'error': password_change_form.errors,
                }, HttpBadRequest)

            return HttpResponse(json.dumps(response_data), mimetype='application/json')
开发者ID:lettoosoft,项目名称:lettoo-weixin-platform-back,代码行数:27,代码来源:user.py

示例11: dehydrate

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def dehydrate(self, bundle):
        bundle.data['url'] = bundle.obj.profile.get_absolute_url()
        
        # return full user data with follows and casted votes
        
        if hasattr(bundle.request, 'REQUEST') and 'user_full' in bundle.request.REQUEST:
            follows = []
            follow_rsc = FollowResource()
            for f in DateaFollow.objects.filter(user=bundle.obj, published=True):
                f_bundle = follow_rsc.build_bundle(obj=f)
                f_bundle = follow_rsc.full_dehydrate(f_bundle)
                follows.append(f_bundle.data)
            bundle.data['follows'] = follows
            
            votes = []
            vote_rsc = VoteResource()
            for v in DateaVote.objects.filter(user=bundle.obj):
                v_bundle = vote_rsc.build_bundle(obj=v)
                v_bundle = vote_rsc.full_dehydrate(v_bundle)
                votes.append(v_bundle.data)
            bundle.data['votes'] = votes
            
            if 'with_action_ids' in bundle.request.REQUEST:
                bundle.data['actions'] = [a.id for a in DateaAction.objects.filter(user=bundle.obj)]

            if 'api_key' in bundle.request.REQUEST:
                keyauth = ApiKeyAuthentication()
                if keyauth.is_authenticated(bundle.request):
                    if bundle.request.user and bundle.request.user == bundle.obj:
                        bundle.data['email'] = bundle.obj.email
                
        return bundle
开发者ID:CruzLeyvaSegundo,项目名称:Datea,代码行数:34,代码来源:profile.py

示例12: attachment_upload

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def attachment_upload(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        apikey_auth = ApiKeyAuthentication()
        if apikey_auth.is_authenticated(request) == True:
            if request.user.is_staff:
                if 'multipart/form-data' not in str(request.META['CONTENT_TYPE']):
                    return self.create_response(request, {
                        'error': 'Unsupported media type',
                    }, HttpBadRequest)
                else:
                    if ('file' in request.FILES):
                        file = request.FILES['file']
                        name = request.POST.get('name', file.name)
                        attachment = Attachment(user=request.user, name=name, file=file)
                        attachment.save()

                        return self.create_response(
                            request,
                            {'id': attachment.id, 'url': request.build_absolute_uri(attachment.file.url)})
                    else:
                        return self.create_response(request, {
                            'error': 'No file found',
                        }, HttpBadRequest)
        else:
            return self.create_response(request, {}, HttpUnauthorized)
开发者ID:lettoosoft,项目名称:lettoo-weixin-platform-back,代码行数:27,代码来源:attachment_resource.py

示例13: auto

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def auto(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        apikey_auth = ApiKeyAuthentication()
        if apikey_auth.is_authenticated(request) == True:
            data = self.deserialize(request, request.body,
                                    format=request.META.get('CONTENT_TYPE', 'application/json'))
            username = data.get('username', None)
            password = data.get('password', None)
            try:
                w = Weixin(username, password)
                w.login()
                user_dict = w.get_user_info()
                public_account = PublicAccount.objects.get_or_create(
                    user=request.user,
                    type=user_dict['type'],
                    title=user_dict['title'],
                    weixin_id=user_dict['weixin_id'],
                    thumbnail_url=request.build_absolute_uri(user_dict['thumbnail_url'])
                )[0]
                public_account.save()
                public_account.callback_url = request.build_absolute_uri(public_account.callback_url)
                public_account.save()
                bundle = self.build_bundle(obj=public_account, request=request)
                bundle = self.full_dehydrate(bundle)
                return self.create_response(request, bundle)
            except Exception as e:
                return self.obj_create(request, {}, HttpBadRequest)

        else:
            return self.create_response(request, {}, HttpUnauthorized)
开发者ID:lettoosoft,项目名称:lettoo-weixin-platform-back,代码行数:33,代码来源:weixin_resource.py

示例14: test_apikey_and_authentication_enforce_user

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def test_apikey_and_authentication_enforce_user(self):
        session_auth = SessionAuthentication()
        api_key_auth = ApiKeyAuthentication()
        auth = MultiAuthentication(api_key_auth, session_auth)
        john_doe = User.objects.get(username="johndoe")
        request1 = HttpRequest()
        request2 = HttpRequest()
        request3 = HttpRequest()

        request1.method = "POST"
        request1.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"}
        request1.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"}
        request1.user = john_doe

        request2.POST["username"] = "janedoe"
        request2.POST["api_key"] = "invalid key"

        request3.method = "POST"
        request3.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"}
        request3.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"}
        request3.user = john_doe
        request3.POST["username"] = "janedoe"
        request3.POST["api_key"] = "invalid key"

        # session auth should pass if since john_doe is logged in
        self.assertEqual(session_auth.is_authenticated(request1), True)
        # api key auth should fail because of invalid api key
        self.assertEqual(isinstance(api_key_auth.is_authenticated(request2), HttpUnauthorized), True)

        # multi auth shouldn't change users if api key auth fails
        # multi auth passes since session auth is valid
        self.assertEqual(request3.user.username, "johndoe")
        self.assertEqual(auth.is_authenticated(request3), True)
        self.assertEqual(request3.user.username, "johndoe")
开发者ID:mattbriancon,项目名称:django-tastypie,代码行数:36,代码来源:authentication.py

示例15: me

# 需要导入模块: from tastypie.authentication import ApiKeyAuthentication [as 别名]
# 或者: from tastypie.authentication.ApiKeyAuthentication import is_authenticated [as 别名]
    def me(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        apikey_auth = ApiKeyAuthentication()
        if apikey_auth.is_authenticated(request) == True:
            return self.generate_response(request, request.user)
        else:
            return self.create_response(request, {}, HttpUnauthorized)
开发者ID:lettoosoft,项目名称:lettoo-weixin-platform-back,代码行数:10,代码来源:user.py


注:本文中的tastypie.authentication.ApiKeyAuthentication.is_authenticated方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。