本文整理汇总了Python中tastypie.authentication.ApiKeyAuthentication类的典型用法代码示例。如果您正苦于以下问题:Python ApiKeyAuthentication类的具体用法?Python ApiKeyAuthentication怎么用?Python ApiKeyAuthentication使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ApiKeyAuthentication类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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),
)
示例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)
示例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")
示例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)
示例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)
示例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)
)
示例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
示例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')
示例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)
示例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)
示例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))
示例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)
示例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))
示例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
示例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