コード例 #1
0
    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)
コード例 #2
0
    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)
コード例 #3
0
    def test_is_authenticated(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)
コード例 #4
0
    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)
コード例 #5
0
 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)
コード例 #6
0
    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)
コード例 #7
0
    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')
コード例 #8
0
    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')
コード例 #9
0
    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)
        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))
コード例 #10
0
ファイル: upload.py プロジェクト: wellfire/django-orb
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)
コード例 #11
0
ファイル: views.py プロジェクト: kingctan/django-oppia
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),
    )
コード例 #12
0
ファイル: views.py プロジェクト: kingctan/django-oppia
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)
    )
コード例 #13
0
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)
コード例 #14
0
    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")
コード例 #15
0
    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)
コード例 #16
0
ファイル: profile.py プロジェクト: CruzLeyvaSegundo/Datea
    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
コード例 #17
0
ファイル: views.py プロジェクト: publet/publet-server
def readability(request, pk):
    # Support both API key and session authentication

    if request.method != 'POST':
        return HttpResponseForbidden()

    if not request.user.is_authenticated():

        auth = ApiKeyAuthentication()
        auth._unauthorized = lambda: False

        if not auth.is_authenticated(request):
            return HttpResponseForbidden()

    url = request.POST.get('url')

    if not url:
        return HttpResponseForbidden()

    publication = get_object_or_404(Publication, pk=pk)
    r = Readability.objects.create(url=url, publication=publication)
    tasks.parse_readability.delay(r)

    Meter('chrome.submitted').inc()

    return HttpResponse()
コード例 #18
0
    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')
コード例 #19
0
    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)
コード例 #20
0
    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)
コード例 #21
0
ファイル: api.py プロジェクト: XiaonuoGantan/M1Backend
 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)
コード例 #22
0
    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))
コード例 #23
0
    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)
コード例 #24
0
ファイル: api.py プロジェクト: XiaonuoGantan/M1Backend
 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)
コード例 #25
0
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
コード例 #26
0
    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))
コード例 #27
0
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
コード例 #28
0
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)
コード例 #29
0
    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))
コード例 #30
0
ファイル: tests_api.py プロジェクト: Kami/codespeed
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)
コード例 #31
0
    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')
コード例 #32
0
    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)
コード例 #33
0
    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)
コード例 #34
0
    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)
コード例 #35
0
    def test_whitelisting(self):
        auth = ApiKeyAuthentication(whitelisted_methods=['a_method'])
        request = HttpRequest()

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

        # Calling with a whitelisted method_name without credentials should work
        self.assertEqual(auth.is_authenticated(request, method_name='a_method'), True)
        
        # Calling any other method should require the Api Key
        self.assertEqual(isinstance(auth.is_authenticated(request, method_name='another_method'), 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, method_name="another_method"), True)
        self.assertEqual(auth.get_identifier(request), 'johndoe')
        self.assertEqual(auth.is_authenticated(request, method_name="a_method"), True)
        self.assertEqual(auth.get_identifier(request), 'johndoe')
コード例 #36
0
ファイル: views.py プロジェクト: jooser/archivematica
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
コード例 #37
0
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))
コード例 #38
0
ファイル: views.py プロジェクト: kingctan/django-oppia
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),
    )
コード例 #39
0
ファイル: views.py プロジェクト: jooser/archivematica
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
コード例 #40
0
ファイル: views.py プロジェクト: publet/publet-server
def chrome_extension(request):
    # Support both API key and session authentication

    if not request.user.is_authenticated():
        auth = ApiKeyAuthentication()
        auth._unauthorized = lambda: False

        if not auth.is_authenticated(request):
            return HttpResponseForbidden()

    groups = request.user.get_groups()

    Meter('chrome.clicked').inc()

    return {
        'groups': groups
    }
コード例 #41
0
ファイル: views.py プロジェクト: grharry/archivematica
def authenticate_request(request):
    error = None

    api_auth = ApiKeyAuthentication()
    authorized = api_auth.is_authenticated(request)

    # 'authorized' can be True, False or tastypie.http.HttpUnauthorized
    # Check explicitly for True, not just truthiness
    if authorized is True:
        client_ip = request.META['REMOTE_ADDR']
        whitelist = helpers.get_setting('api_whitelist', '127.0.0.1').split()
        if client_ip not in whitelist:
            error = 'Host/IP ' + client_ip + ' not authorized.'
    else:
        error = 'API key not valid.'

    return error
コード例 #42
0
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)
    cohorts_list = []
    for cohort in cohorts:
        courses = Course.objects.filter(coursecohort__cohort=cohort).order_by('title')
        cohorts_list.append([cohort,courses])
    key = ApiKey.objects.get(user = request.user)
    request.user.key = key.key
    return render_to_response('oppia/mobile/monitor/home.html',{ 'cohorts_list':cohorts_list, 'user': request.user }, context_instance=RequestContext(request))
コード例 #43
0
ファイル: views.py プロジェクト: jhsimpson/archivematica
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
コード例 #44
0
ファイル: views.py プロジェクト: andrewjbtw/archivematica
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
コード例 #45
0
    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')
コード例 #46
0
ファイル: api.py プロジェクト: jasonrig/mytardis
    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
コード例 #47
0
ファイル: api.py プロジェクト: kennethryerson/mytardis
    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
コード例 #48
0
	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')
コード例 #49
0
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))
コード例 #50
0
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))
コード例 #51
0
def file_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', 'title', 'description', 'order_by']

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

    if 'resource_file' not in request.FILES:
        return HttpResponse(status=HTML_BADREQUEST, content='{ "error": "No resource 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)

    rf = ResourceFile()
    rf.title = request.POST['title']
    rf.resource = resource
    rf.create_user = request.user
    rf.update_user = request.user
    rf.file = request.FILES['resource_file']
    rf.description = request.POST['description']
    rf.order_by = request.POST['order_by']
    rf.save()

    return HttpResponse(status=HTML_CREATED)
コード例 #52
0
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))
コード例 #53
0
 def get(self, request):
     authentication = ApiKeyAuthentication()
     if authentication.is_authenticated(request) is not True:
         return Response(Respostas.NAO_AUTORIZADO.value)