本文整理汇总了Python中tastypie.authentication.ApiKeyAuthentication类的典型用法代码示例。如果您正苦于以下问题:Python ApiKeyAuthentication类的具体用法?Python ApiKeyAuthentication怎么用?Python ApiKeyAuthentication使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ApiKeyAuthentication类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: monitor_cohort_progress_view
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,代码行数:60,代码来源:views.py
示例2: auto
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,代码行数:31,代码来源:weixin_resource.py
示例3: test_apikey_and_authentication_enforce_user
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,代码行数:34,代码来源:authentication.py
示例4: attachment_upload
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,代码行数:25,代码来源:attachment_resource.py
示例5: image_view
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,代码行数:34,代码来源:upload.py
示例6: scorecard_view
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,代码行数:33,代码来源:views.py
示例7: dehydrate
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,代码行数:32,代码来源:profile.py
示例8: change_password
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,代码行数:25,代码来源:user.py
示例9: logout
def logout(self, request, **kwargs):
auth = ApiKeyAuthentication()
self.method_check(request, allowed=['post'])
if auth.is_authenticated(request):
logout(request)
return self.create_response(request, { 'success': True })
else:
return self.create_response(request, { 'success': False }, HttpUnauthorized)
开发者ID:XiaonuoGantan,项目名称:M1Backend,代码行数:8,代码来源:api.py
示例10: test_check_active_true
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)
request.META["HTTP_AUTHORIZATION"] = "ApiKey bobdoe:%s" % bob_doe.api_key.key
self.assertEqual(auth.is_authenticated(request), False)
开发者ID:mattbriancon,项目名称:django-tastypie,代码行数:8,代码来源:authentication.py
示例11: test_check_active_true
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)
request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
self.assertFalse(auth.is_authenticated(request))
开发者ID:mthornhill,项目名称:django-tastypie,代码行数:8,代码来源:authentication.py
示例12: me
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,代码行数:8,代码来源:user.py
示例13: test_check_active_true
def test_check_active_true(self):
user_class = get_user_model()
auth = ApiKeyAuthentication()
request = HttpRequest()
bob_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'bobdoe'})
create_api_key(User, instance=bob_doe, created=True)
request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
self.assertFalse(auth.is_authenticated(request))
开发者ID:amitu,项目名称:django-tastypie,代码行数:9,代码来源:authentication.py
示例14: monitor_cohort_student_view
def monitor_cohort_student_view(request,cohort_id, student_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)
raise Http404
开发者ID:DigitalCampus,项目名称:django-swaziland-oppia,代码行数:9,代码来源:views.py
示例15: _is_api_key_authentication
def _is_api_key_authentication(request):
authorization_header = request.META.get('HTTP_AUTHORIZATION', '')
api_key_authentication = ApiKeyAuthentication()
try:
username, api_key = api_key_authentication.extract_credentials(request)
except ValueError:
raise Http400("Bad HTTP_AUTHORIZATION header {}"
.format(authorization_header))
else:
return username and api_key
开发者ID:dimagi,项目名称:commcare-hq,代码行数:11,代码来源:auth.py
示例16: disconnect_socialaccount
def disconnect_socialaccount(self, request, provider, **kwargs):
self.method_check(request, allowed=['post'])
apikey_auth = ApiKeyAuthentication()
if apikey_auth.is_authenticated(request) == True:
user_provider_tokens = SocialToken.objects.filter(user=request.user, app__provider=provider)
if user_provider_tokens:
user_provider_tokens.delete()
response_data = {'status': "success"}
return HttpResponse(json.dumps(response_data), mimetype='application/json')
开发者ID:lettoosoft,项目名称:lettoo-weixin-platform-back,代码行数:12,代码来源:user.py
示例17: authenticate_request
def authenticate_request(request):
api_auth = ApiKeyAuthentication()
authorized = api_auth.is_authenticated(request)
if authorized == True:
client_ip = request.META['REMOTE_ADDR']
whitelist = helpers.get_setting('api_whitelist', '127.0.0.1').split("\r\n")
try:
whitelist.index(client_ip)
return True
except:
pass
return False
开发者ID:jooser,项目名称:archivematica,代码行数:14,代码来源:views.py
示例18: monitor_cohort_quizzes_view
def monitor_cohort_quizzes_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": "quizzes"}')
quizzes = Activity.objects.filter(section__course=course, type="quiz").order_by("section__order")
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.quizzes = []
for quiz in quizzes:
completed = False
if Tracker.objects.filter(user=p.user, digest=quiz.digest, completed=True).count() > 0:
completed = True
started = False
if Tracker.objects.filter(user=p.user, digest=quiz.digest, completed=False).count() > 0:
started = True
temp = {"quiz": quiz, "completed": completed, "started": started}
p.quizzes.append(temp)
except (EmptyPage, InvalidPage):
tracks = paginator.page(paginator.num_pages)
return render_to_response(
"oppia/mobile/monitor/quizzes.html",
{"cohort": cohort, "course": course, "participants": students, "user": request.user},
context_instance=RequestContext(request),
)
开发者ID:kingctan,项目名称:django-oppia,代码行数:50,代码来源:views.py
示例19: monitor_home_view
def monitor_home_view(request):
auth = ApiKeyAuthentication()
if auth.is_authenticated(request) is not True:
return HttpResponse('Unauthorized', status=401)
record_mobile_tracker(request,None,'monitor','{"en":"homepage"}')
# find courses this user is a teacher on
now = datetime.datetime.now()
cohorts = Cohort.objects.filter(participant__user=request.user, participant__role=Participant.TEACHER, start_date__lte=now,end_date__gte=now)
key = ApiKey.objects.get(user = request.user)
request.user.key = key.key
return render_to_response('oppia/mobile/monitor/home.html',{ 'cohorts_list':cohorts, 'user': request.user }, context_instance=RequestContext(request))
开发者ID:DigitalCampus,项目名称:django-swaziland-oppia,代码行数:14,代码来源:views.py
示例20: test_is_authenticated_get_params
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,代码行数:30,代码来源:authentication.py
注:本文中的tastypie.authentication.ApiKeyAuthentication类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论