def setUp(self):
        super(UserManagerRoleViewsTest, self).setUp()
        self.user = User.objects.create(username='******',
                                        email='*****@*****.**',
                                        is_staff=True)
        self.user.set_password('test')
        self.user.save()
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
        self.users = list(self._create_users())
        self.managers = list(self._create_managers())
        for user in self.users[:5]:
            UserManagerRole.objects.create(manager_user=self.managers[0],
                                           user=user)
        for user in self.users[5:]:
            UserManagerRole.objects.create(manager_user=self.managers[1],
                                           user=user)

        UserManagerRole.objects.create(manager_user=self.managers[1],
                                       user=self.users[0])

        patcher = patch.object(ManagerViewMixin,
                               'get_authenticators',
                               return_value=[SessionAuthentication()])
        patcher.start()
        self.addCleanup(patcher.__exit__, None, None, None)
Exemple #2
0
    def login(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        if request.user.is_authenticated:
            raise ParseError(_('Log out first.'))

        data = get_api_post_data(request)

        if 'token' in data:
            try:
                token = Token.get_by_token(data['token'])
            except Token.DoesNotExist:
                raise PermissionDenied(_('This token does not exist or is no longer valid.'))
            user = token.user
        elif 'username' in data:
            form = AuthenticationForm(request, data=data)
            if not form.is_valid():
                raise ParseError(form.errors)
            user = form.user_cache
        else:
            raise ParseError(_('You need to send a token or username and password.'))

        login(request, user)

        return Response({
            'detail': _('Login successful.'),
            'csrf_token': csrf.get_token(request),
        })
Exemple #3
0
 def get(self, request):
     rest_request = Request(request)
     try:
         user_token = TokenAuthentication().authenticate(rest_request)
         if user_token is None:
             raise AuthenticationFailed
         user, token = user_token
     except AuthenticationFailed:
         try:
             user_session = SessionAuthentication().authenticate(
                 rest_request)
             if user_session is None:
                 raise AuthenticationFailed
             user, _ = user_session
             if not user.has_perm('base.consume_curriculum'):
                 raise AuthenticationFailed
             token, _ = Token.objects.get_or_create(user=user)
         except AuthenticationFailed:
             return JsonResponse({
                 'authenticated': False,
             })
     socialuser = SocialUser.user_for_django_user(user.id)
     return JsonResponse({
         'authenticated': True,
         'preferencesInitialized': socialuser.has_initialized_preferences,
         'token': token.key,
     })
Exemple #4
0
    def get_direct_queryset(cls, request, **initkwargs):
        """
        TODO: Temporary until a better way is found
        """
        self = cls(**initkwargs)
        request = Request(request, authenticators=(BasicAuthentication(), SessionAuthentication()))
        self.request = request

        return self.get_queryset()
Exemple #5
0
    def deactivate(self, request, *args, **kwargs):
        # django-rest-framework doesn't automatically do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        request.session.pop('changeset', None)
        request.session['direct_editing'] = False

        return Response({
            'success': True,
        })
Exemple #6
0
class AuthFsDavView(RestAuthViewMixIn, DavView):
    """
    Special View providing Authentication for our Webdav Resource
    """
    authentications = (CachedBasicAuthentication(), SessionAuthentication())

    @method_decorator(csrf_exempt)
    @transaction.atomic
    def dispatch(self, request, *args, **kwargs):
        drive = kwargs.get('drive', None)
        if 'path' not in kwargs:
            kwargs['path'] = ""

        if drive:
            drive = Drive.objects.filter(pk=drive).first()

            # check that the drive exists
            if not drive:
                raise Http404

            # temporarily raise a 404 if the drive is a DSS drive
            if drive.is_dss_drive:
                raise Http404

            # ToDo: We need to do a permission check here, but request.user is not set here, as it gets set
            # ToDo: in the dispatch method of the super class
            # ToDo: However, collection_model_qs() should not return any directories, if they are not viewable

            request.drive = drive

            del kwargs['drive']

        project = kwargs.get('project', None)

        if project:
            project = Project.objects.filter(pk=project).first()

            if not project:
                raise Http404

            request.project = project

            del kwargs['project']

        if 'drive_title' in kwargs:
            del kwargs['drive_title']

        if 'project_title' in kwargs:
            del kwargs['project_title']

        # continue
        return super(AuthFsDavView, self).dispatch(request, *args, **kwargs)
Exemple #7
0
    def logout(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        if not request.user.is_authenticated:
            return ParseError(_('Not logged in.'))

        logout(request)

        return Response({
            'detail': _('Logout successful.'),
            'csrf_token': csrf.get_token(request),
        })
    def setUp(self):
        super(CompletionBlockUpdateViewTestCase, self).setUp()
        self.test_user = User.objects.create(username='******')
        self.staff_user = User.objects.create(username='******', is_staff=True)
        self.test_enrollment = self.create_enrollment(
            user=self.test_user,
            course_id=self.course_key,
        )
        self.blocks = [
            self.course_key.make_usage_key('course', 'course'),
            self.course_key.make_usage_key('sequential', 'course-sequence1'),
            self.course_key.make_usage_key('sequential', 'course-sequence2'),
            self.course_key.make_usage_key('html', 'course-sequence1-html1'),
            self.course_key.make_usage_key('html', 'course-sequence1-html2'),
            self.course_key.make_usage_key('html', 'course-sequence1-html3'),
            self.course_key.make_usage_key('html', 'course-sequence1-html4'),
            self.course_key.make_usage_key('html', 'course-sequence1-html5'),
            self.course_key.make_usage_key('html', 'course-sequence2-html6'),
            self.course_key.make_usage_key('html', 'course-sequence2-html7'),
            self.course_key.make_usage_key('html', 'course-sequence2-html8'),
        ]
        compat = StubCompat(self.blocks)
        for compat_import in (
                'completion_aggregator.api.common.compat',
                'completion_aggregator.api.v0.views.compat',
                'completion_aggregator.serializers.compat',
                'completion_aggregator.core.compat',
        ):
            patcher = patch(compat_import, compat)
            patcher.start()
            self.addCleanup(patcher.__exit__, None, None, None)

        self.patch_object(
            CompletionViewMixin,
            'get_authenticators',
            return_value=[OAuth2Authentication(),
                          SessionAuthentication()])
        self.patch_object(CompletionViewMixin,
                          'pagination_class',
                          new_callable=PropertyMock,
                          return_value=PageNumberPagination)
        self.client = APIClient()
        self.client.force_authenticate(user=self.test_user)
        self.update_url = reverse('completion_api_v0:blockcompletion-update',
                                  kwargs={
                                      'course_key':
                                      six.text_type(self.course_key),
                                      'block_key':
                                      six.text_type(self.usage_key)
                                  })
Exemple #9
0
    def get_token(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        data = get_api_post_data(request)

        form = AuthenticationForm(request, data=data)
        if not form.is_valid():
            raise ParseError(form.errors)

        token = form.user_cache.login_tokens.create()

        return Response({
            'token': token.get_token(),
        })
Exemple #10
0
    def direct_editing(self, request, *args, **kwargs):
        # django-rest-framework doesn't automatically do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        if not ChangeSet.can_direct_edit(request):
            raise PermissionDenied(_('You don\'t have the permission to activate direct editing.'))

        changeset = ChangeSet.get_for_request(request)
        if changeset.pk is not None:
            raise PermissionDenied(_('You cannot activate direct editing if you have an active changeset.'))

        request.session['direct_editing'] = True

        return Response({
            'success': True,
        })
Exemple #11
0
 def get_authenticators(self):
     if self.request.method == 'post':
         return []
     else:
         return [SessionAuthentication(), JSONWebTokenAuthentication()]
Exemple #12
0
    def post_or_delete(self, request, *args, **kwargs):
        # django-rest-framework doesn't automatically do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        return self.retrieve(request, *args, **kwargs)
 def enforce_csrf(self, request):
     if request.path.startswith('/api'):
         return
     else:
         return SessionAuthentication.enforce_csrf(
             CsrfExemptSessionAuthentication, request)
    def get_authenticators(self) -> list:
        authenticators: list = super().get_authenticators()
        if getattr(self.request, 'is_internal', False):
            authenticators.append(SessionAuthentication())

        return authenticators
Exemple #15
0
 def enforce_csrf(self, request):
     if getattr(request, '_basic_authenticated', False):
         # This request was not authenticated by the django session security module,
         # so its CSRF check will fail. Avoid.
         return
     _RestSessionAuthentication.enforce_csrf(self, request)
class AuthFsDavView(RestAuthViewMixIn, DavView):
    authentications = (BasicAuthentication(), SessionAuthentication())
Exemple #17
0
 def enforce_csrf(self, request):
     if request.method == 'POST' and request.path == '/api/profile/':
         return
     return SessionAuthentication.enforce_csrf(self, request)