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
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) )
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), )
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)
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')
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)
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="******") 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"] = "******" 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"] = "******" 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")
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)
def test_check_active_true(self): auth = ApiKeyAuthentication() request = HttpRequest() bob_doe = User.objects.get(username="******") 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)
def test_check_active_true(self): auth = ApiKeyAuthentication() request = HttpRequest() bob_doe = User.objects.get(username='******') 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))
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)
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)
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))
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
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
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')
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), )
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
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))
def test_is_authenticated_get_params(self): auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = User.objects.get(username='******') 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'] = '******' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.GET['username'] = '******' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.GET['username'] = '******' request.GET['api_key'] = 'foo' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = User.objects.get(username='******') request.GET['username'] = '******' request.GET['api_key'] = john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) self.assertEqual(auth.get_identifier(request), 'johndoe')
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'] = '******' 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)
def test_is_authenticated_header(self): auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = User.objects.get(username='******') 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='******') request.META['HTTP_AUTHORIZATION'] = 'ApiKey johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) # Capitalization shouldn't matter. john_doe = User.objects.get(username='******') request.META['HTTP_AUTHORIZATION'] = 'aPiKeY johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True)
def authenticate_request(request): error = None 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 except: error = 'Host/IP ' + client_ip + ' not authorized.' else: error = 'API key not valid.' return error
def setUp(self): super(ApiKeyAuthenticationTestCase, self).setUp() ApiKey.objects.all().delete() self.auth = ApiKeyAuthentication() self.request = HttpRequest() # Simulate sending the signal. user = User.objects.get(username='******') create_api_key(User, instance=user, created=True)
def get(self,request): obj=ApiKeyAuthentication() try: username_from_request=request.META['HTTP_USERNAME'] password=request.META['HTTP_PASSWORD'] if username_from_request is not None and password is not None: user=authenticate(username=username_from_request,password=password) if user is not None: is_auth=obj.is_authenticated(request) if is_auth: return HttpResponse(status=200,content_type='application/json') else: return HttpResponse(status=200,content_type='application/json') else: return HttpResponse(status=401,content_type='application/json') else: return HttpResponse(status=401,content_type='application/json') except(KeyError): return HttpResponse(status=400,content_type='application/json')
def is_authenticated(self, request, **kwargs): # noqa # too complex ''' handles backends explicitly so that it can return False when credentials are given but wrong and return Anonymous User when credentials are not given or the session has expired (web use). ''' auth_info = request.META.get('HTTP_AUTHORIZATION') if 'HTTP_AUTHORIZATION' not in request.META: if hasattr(request.user, 'allowed_tokens'): tokens = request.user.allowed_tokens session_auth = SessionAuthentication() check = session_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): session_auth_result = False else: request._authentication_backend = session_auth session_auth_result = check else: request.user = AnonymousUser() session_auth_result = True request.user.allowed_tokens = tokens return session_auth_result else: if auth_info.startswith('Basic'): basic_auth = BasicAuthentication() check = basic_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return False else: request._authentication_backend = basic_auth return check if auth_info.startswith('ApiKey'): apikey_auth = ApiKeyAuthentication() check = apikey_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return False else: request._authentication_backend = apikey_auth return check
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='******') 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'] = '******' 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'] = '******' request3.POST['api_key'] = 'invalid key' #session auth should pass if since john_doe is logged in self.assertTrue(session_auth.is_authenticated(request1)) #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.assertTrue(auth.is_authenticated(request3)) self.assertEqual(request3.user.username, 'johndoe')
def scorecard_view(request): auth = ApiKeyAuthentication() if auth.is_authenticated(request) is not True: return HttpResponse('Unauthorized', status=401) 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))
class ApiKeyAuthenticationTestCase(FixtureTestCase): def setUp(self): super(ApiKeyAuthenticationTestCase, self).setUp() ApiKey.objects.all().delete() self.auth = ApiKeyAuthentication() self.request = HttpRequest() # Simulate sending the signal. user = User.objects.get(username='******') create_api_key(User, instance=user, created=True) def test_is_not_authenticated(self): """Should return HttpUnauthorized when incorrect credentials are given""" # No username/api_key details self.assertEqual(isinstance( self.auth.is_authenticated(self.request), HttpUnauthorized), True) # Wrong username details. self.request.GET['username'] = '******' self.assertEqual(isinstance( self.auth.is_authenticated(self.request), HttpUnauthorized), True) # No api_key. self.request.GET['username'] = '******' self.assertEqual(isinstance( self.auth.is_authenticated(self.request), HttpUnauthorized), True) # Wrong user/api_key. self.request.GET['username'] = '******' self.request.GET['api_key'] = 'foo' self.assertEqual(isinstance( self.auth.is_authenticated(self.request), HttpUnauthorized), True) def test_is_authenticated(self): """Should correctly authenticate when using an existing user and key""" # Correct user/api_key. user = User.objects.get(username='******') self.request.GET['username'] = '******' self.request.GET['api_key'] = user.api_key.key self.assertEqual(self.auth.is_authenticated(self.request), True)
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'] = '******' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.GET['username'] = '******' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.GET['username'] = '******' request.GET['api_key'] = 'foo' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = User.objects.get(username='******') john_doe.save() request.GET['username'] = '******' request.GET['api_key'] = john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True)
def test_is_authenticated_header(self): user_class = get_user_model() auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: '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_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) request.META[ 'HTTP_AUTHORIZATION'] = 'ApiKey johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) # Capitalization shouldn't matter. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) request.META[ 'HTTP_AUTHORIZATION'] = 'aPiKeY johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True)
class Meta: queryset = CookingTime.objects.all() resource_name = "cooking_time" fields = [ 'id', 'hours', 'minutes', ] list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] throttle = CacheDBThrottle() serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization()
class Meta: queryset = Snipt.objects.all().order_by('-created') resource_name = 'snipt' fields = [ 'id', 'title', 'slug', 'lexer', 'code', 'description', 'line_count', 'stylized', 'key', 'public', 'blog_post', 'created', 'modified', 'publish_date', 'meta' ] include_absolute_url = True detail_allowed_methods = ['get', 'patch', 'put', 'delete'] list_allowed_methods = ['get', 'post'] authentication = ApiKeyAuthentication() authorization = PrivateSniptAuthorization() validation = SniptValidation() ordering = ['created', 'modified'] always_return_data = True max_limit = 200 cache = SimpleCache()
class Meta: resource_name = 'event' serializer = MyDateSerializer() queryset = Event.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'delete'] filtering = { #'owner' : ALL_WITH_RELATIONS, 'event_type': ALL_WITH_RELATIONS, 'start': ALL, 'position': ALL, 'canceled': ALL, #'participants': ALL_WITH_RELATIONS, } ordering = ['start'] authorization = DjangoAuthorization() authentication = ApiKeyAuthentication() always_return_data = True
class Meta(object): SetTopBox = apps.get_model('client', 'SetTopBox') queryset = SetTopBox.objects.all() resource_name = 'settopbox' allowed_methods = ['get', 'post', 'delete', 'put', 'patch'] fields = ['serial_number', 'mac'] urlconf_namespace = 'client' authorization = MyAuthorization() validation = SetTopBoxValidation(form_class=forms.SetTopBoxForm) always_return_data = True filtering = { 'mac': ALL, 'serial_number': ALL } authentication = MultiAuthentication( BasicAuthentication(realm='cianet-middleware'), Authentication(), ApiKeyAuthentication())
class Meta: queryset = models.NakopitelnayaVedomost.objects.all() resource_name = 'nakopitelnie_vedomosti' list_allowed_methods = ['get', 'post', 'put', 'delete'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] collection_name = 'nakopitelnie_vedomosti' authorization = Authorization() authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication()) filtering = { 'id': ALL, 'date': ALL, 'created_date': ALL, 'author': ALL_WITH_RELATIONS, 'station': ALL_WITH_RELATIONS, 'event': ALL_WITH_RELATIONS, 'departament': ALL, }
class Meta: queryset = Vote.objects.all() list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] resource_name = 'rating/vote' include_resource_uri = False # TODO: double-check for sensitive information fields = ['id', 'created'] authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication(), Authentication()) authorization = Authorization() always_return_data = True filtering = {}
class Meta: queryset = models.Handout.objects.all() list_allowed_methods = ['get', 'post', 'put', 'delete'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] resource_name = 'handouts' collection_name = 'handouts' always_return_data = True authorization = Authorization() authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication()) filtering = { 'station': ALL_WITH_RELATIONS, 'car': ALL_WITH_RELATIONS, 'worker': ALL_WITH_RELATIONS, 'waybills': ALL_WITH_RELATIONS, 'author': ALL_WITH_RELATIONS, 'date': ALL, }
class Meta: queryset = Visit.objects.all() resource_name = 'visit' #fields = ['id','date_planned','check_in','check_out','coordinates_lat_in','coordinates_lon_in','coordinates_lat_out','coordinates_lon_out','type','observation','requirement','user'] #allowed_methods = ['get','post'] list_allowed_methods = ['get', 'post','put','patch'] detail_allowed_methods = ['get', 'post', 'put','patch'] filtering = { # 'id': ALL, 'date_planned': ALL, 'requirement': ALL_WITH_RELATIONS, 'user': ALL_WITH_RELATIONS, } include_resource_uri = False authentication = ApiKeyAuthentication() authorization = Authorization() serializer = Serializer(formats=['json',]) ordering = ['id']
class Meta: queryset = ProfitCenter.objects.all() authentication = ApiKeyAuthentication() authorization = RalphAuthorization( required_perms=[ Perm.read_dc_structure, ] ) filtering = { 'id': ALL, 'name': ALL, } cache = SimpleCache() throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: queryset = Playlist.objects.order_by('-created').all() list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] resource_name = 'simpleplaylist' #excludes = ['updated',] include_absolute_url = True always_return_data = True authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication()) authorization = Authorization() filtering = {}
class Meta(object): SetTopBoxParameter = apps.get_model('client', 'SetTopBoxParameter') queryset = SetTopBoxParameter.objects.all() resource_name = 'settopboxparameter' allowed_methods = ['get', 'post', 'delete', 'put', 'patch'] urlconf_namespace = 'client' always_return_data = True filtering = { "settopbox": ALL, # ALL_WITH_RELATIONS "key": ALL, "value": ALL } validation = Validation() authorization = MyAuthorization() authentication = MultiAuthentication( BasicAuthentication(realm='cianet-middleware'), Authentication(), ApiKeyAuthentication())
class Meta: queryset = Record.objects.all() authentication = ApiKeyAuthentication() authorization = RalphAuthorization(required_perms=[ Perm.read_dc_structure, ]) filtering = { 'type': ALL, 'name': ALL, 'content': ALL, } cache = SimpleCache() list_allowed_methods = ['get'] throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: queryset = BlogCategory.objects.all() resource_name = "categories" fields = [ 'id', 'title', ] list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] limit = 0 throttle = CacheDBThrottle() serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization()
class Meta: queryset = User.objects.all() excludes = ["email", "password"] authorization = Authorization() authentication = ApiKeyAuthentication() excludes = [ "password", "is_staff", "is_active", "is_superuser", "groups", "user_permissions", ] list_allowed_methods = ['get'] detail_allowed_methods = ['get', 'put'] filtering = { "username": ALL, }
class Meta: queryset = Keyword.objects.all() resource_name = "keywords" fields = ['id', 'title'] list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] limit = 0 throttle = CacheDBThrottle() filtering = { 'title': ('exact', ), } serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization()
class Meta: resource_name = 'receivers' queryset = Receiver.objects.all() filtering = { 'id': ALL, 'name': ALL, 'address1': ALL, 'address2': ALL, 'address3': ALL, 'city': ALL, 'state': ALL, 'zipcode': ALL, 'country': ALL, } authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() allowed_methods = ['get', ] always_return_data = True
class Meta: resource_name = 'purchase_order_line_items' queryset = PurchaseOrderLineItem.objects.all() filtering = { 'id': ALL, 'purchase_order': ALL_WITH_RELATIONS, 'sku': ALL_WITH_RELATIONS, 'quantity_received': ALL, 'unit_cost': ALL, 'discount_percent': ALL, 'discount_dollar': ALL, 'adjusted_unit_cost': ALL, 'total_cost': ALL, } authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() allowed_methods = ['get', ] always_return_data = True
class Meta: queryset = Submission.objects.all() resource_name = 'submission_content' excludes = ['feedback'] allowed_methods = ['get'] include_absolute_url = True # Rules that enable filtering based on exercise, grader, submitter and grade. filtering = { "exercise": ('exact',), "grader": ('exact',), "submitters": ('exact',), "grade": ALL, "id": ALL } authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization()
class Meta: queryset = Extension.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'device' authentication = MultiAuthentication(IPBasicAuthentication(), ApiKeyAuthentication()) authorization = Authorization() serializer = urlencodeSerializer() always_return_data = True fields = [ 'accountcode', 'extension_uuid', 'extension', 'password', 'do_not_disturb', 'is_bell' ] filtering = { 'uuid': ALL, 'sip_username': ALL, 'accountcode': ALL, }
class Meta: queryset = Network.objects.all() authentication = ApiKeyAuthentication() authorization = RalphAuthorization( required_perms=[ Perm.read_network_structure, ] ) filtering = { } excludes = ( ) cache = SimpleCache() throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: queryset = Entity.objects.active() include_resource_uri = False list_allowed_methods = ['get', 'post'] resource_name = 'entities' collection_name = 'entities' excludes = ['user', 'registered', 'num_workers', 'legal_form'] filtering = { 'categories': ALL, 'city': ('exact', ), } authentication = MultiAuthentication( ApiKeyAuthentication(), Authentication(), ) authorization = Authorization()
class Meta: queryset = Asset.objects.all() authentication = ApiKeyAuthentication() filtering = { 'barcode': ALL, 'delivery_date': ALL, 'deprecation_rate': ALL, 'device_environment': ALL_WITH_RELATIONS, 'force_deprecation': ALL, 'hostname': ALL, 'invoice_date': ALL, 'invoice_no': ALL, 'location': ALL, 'model': ALL_WITH_RELATIONS, 'niw': ALL, 'order_no': ALL, 'owner': ALL_WITH_RELATIONS, 'price': ALL, 'production_use_date': ALL, 'production_year': ALL, 'provider': ALL, 'provider_order_date': ALL, 'remarks': ALL, 'request_date': ALL, 'service': ALL_WITH_RELATIONS, 'service_name': ALL_WITH_RELATIONS, 'slots': ALL, 'sn': ALL, 'source': ALL, 'status': ALL, 'support_period': ALL, 'support_price': ALL, 'support_type': ALL, 'support_void_reporting': ALL, 'type': ALL, 'user': ALL_WITH_RELATIONS, 'warehouse': ALL_WITH_RELATIONS, } list_allowed_methods = ['get'] throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: queryset = CIType.objects.all() authentication = ApiKeyAuthentication() authorization = RalphAuthorization(required_perms=[ Perm.read_configuration_item_info_generic, ]) filtering = { 'id': ALL, 'name': ALL, 'resource_uri': ALL, } list_allowed_methods = ['get'] resourse_name = 'citypes' excludes = ['cache_version', 'created', 'modified'] throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: # For authentication, allow both basic and api key so that the key # can be grabbed, if needed. authentication = MultiAuthentication( InlineBasicAuthentication(), BasicAuthentication(), ApiKeyAuthentication(),TokenAuthentication()) authorization = Authorization() serializer = Serializer(formats=['json']) # Because this can be updated nested under the UserProfile, it needed # 'put'. No idea why, since patch is supposed to be able to handle # partial updates. allowed_methods = ['get', 'put' ] always_return_data = True queryset = User.objects.all().select_related("api_key") resource_name = "users" fields = ['last_name','first_name','username','is_active','email','password','is_staff','is_superuser'] filtering = {'username':ALL_WITH_RELATIONS,'email':ALL}
class Meta: queryset = User.objects.all() authentication = ApiKeyAuthentication() authorization = RalphAuthorization(required_perms=[ Perm.read_configuration_item_info_generic, ]) list_allowed_methods = ['get'] filtering = { 'first_name': ALL, 'last_name': ALL, 'username': ALL, } resource_name = 'users' excludes = ['password', 'last_login', 'is_staff', 'is_superuser'] throttle = CacheThrottle( throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION, )
class Meta: queryset = Venture.objects.all() authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() filtering = { 'id': ALL, 'name': ALL, 'symbol': ALL, 'data_center': ALL_WITH_RELATIONS, 'show_in_ralph': ALL, } excludes = ( 'save_priorities', 'max_save_priority', ) cache = SimpleCache() throttle = CacheThrottle(throttle_at=THROTTLE_AT, timeframe=TIMEFRAME, expiration=EXPIRATION)
class Meta: queryset = Resource.objects.all() resource_name = 'resource' excludes = ['source_peer'] allowed_methods = ['get', 'post', 'put'] authentication = MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication()) authorization = ORBResourceAuthorization() serializer = ResourceSerializer() always_return_data = True include_resource_uri = True throttle = CacheDBThrottle(throttle_at=1000, timeframe=3600) ordering = ['update_date'] filtering = { 'update_date': ['lte', 'gte'], # `exact` would imply a timestamp, not date comparison 'status': ['exact'], }
class Meta: queryset = Course.objects.all() resource_name = 'course' allowed_methods = ['get'] fields = ['id', 'title', 'version', 'shortname', 'priority', 'is_draft', 'description', 'author', 'username', 'organisation'] authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization() serializer = CourseJSONSerializer() always_return_data = True include_resource_uri = True
class Meta: queryset = Task.objects.all() resource_name = 'task' list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] always_return_data = True authorization = Authorization() authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication()) collection_name = 'tasks' filtering = { "slug": ('exact', 'startswith'), "title": ALL, 'is_completed': ALL, 'assigner': ALL_WITH_RELATIONS, 'performer': ALL_WITH_RELATIONS, 'to_complete': ALL, 'viewed': ALL }