How to use the djangorestframework.permissions.IsAuthenticated function in djangorestframework

To help you get started, we’ve selected a few djangorestframework examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github devilry / devilry-django / devilry / devilry_student / rest / find_groups.py View on Github external
Uses case-ignore-contains search.


    ## Response
    List of objects with the following attributes:

    - ``id`` (int): Internal Devilry ID of the group. Is never ``null``.
    - ``name`` (string|null): The name of the group.
    - ``assignment`` (object): Information about the assignment.
    - ``period`` (object): Information about the period.
    - ``subject`` (object): Information about the subject.

    The response contains at most most 50 elements, and it is ordered by
    the publishing_time of the assignment (newest first).
    """
    permissions = (IsAuthenticated,)
    resource = FindGroupsResource


    def get_queryset(self):
        querystring = self.request.GET.get('query', '').strip()
        if not querystring:
            return AssignmentGroup.objects.none()

        qry = None
        for word in querystring.split():
            wordqry = Q(Q(name__icontains=word) |
                        # Assignment
                        Q(parentnode__short_name__icontains=word) |
                        Q(parentnode__long_name__icontains=word) |
                        # Period
                        Q(parentnode__parentnode__short_name__icontains=word) |
github devilry / devilry-django / src / devilry_subjectadmin / devilry_subjectadmin / rest / popfromgroup.py View on Github external
## Response
    Responds with status code ``200`` and an object/map with the following attributes on success:

    - ``success`` (bool): Always ``true``.
    - ``group_id`` (int): The ID of the source group.
    - ``candidate_id`` (int): The ID of the candidate.
    - ``new_group_id`` (int): The ID of the newly created group.

    On error, we respond with:

    - Errorcode ``400`` if any of the parameters are missing or wrong.
    - Errorcode ``403`` for permission denied.
    - Errorcode ``404`` if the group is not found within the assignment, or if the candidate is not found within the group.
    """
    permissions = (IsAuthenticated, IsAssignmentAdmin)
    resource = PopFromGroupResource

    def _get_group(self, group_id):
        try:
            return AssignmentGroup.objects.get(parentnode=self.assignment_id,
                                         id=group_id)
        except AssignmentGroup.DoesNotExist:
            raise NotFoundError(('Group with assignment_id={assignment_id} and '
                                 'id={group_id} not found').format(assignment_id=self.assignment_id,
                                                                   group_id=group_id))

    def _get_candidate(self, group_id, candidate_id):
        try:
            return Candidate.objects.get(assignment_group=group_id,
                                         id=candidate_id)
        except Candidate.DoesNotExist:
github devilry / devilry-django / src / devilry_subjectadmin / devilry_subjectadmin / rest / createnewassignment.py View on Github external
def validate_request(self, data, files=None):
        """
        Remove ``id`` from input data to enable us to have it in models.
        """
        if 'id' in data:
            del data['id']
        return super(RestCreateNewAssignmentResource, self).validate_request(data, files)


class RestCreateNewAssignment(SelfdocumentingMixin, View):
    """
    Simplifies creating and setting up new assignments.
    """
    resource = RestCreateNewAssignmentResource
    permissions = (IsAuthenticated,)

    def __init__(self):
        self.dao = CreateNewAssignmentDao()

    def _require_periodadmin(self, user):
        if not 'period_id' in self.CONTENT:
            raise PermissionDeniedError('period_id is a required parameter.')
        period_id = self.CONTENT['period_id']
        periodadmin_required(user, period_id)

    def postprocess_docs(self, docs):
        return docs.format(paramteterstable=self.htmlformat_parameters_from_form())

    def post(self, request):
        """
        Create an assignment, and add related students if requested.
github encode / django-rest-framework / examples / permissionsexample / views.py View on Github external
def get(self, request):
        """
        Handle GET requests.
        """
        return "Successful response to GET request because throttle is not yet active."


class LoggedInExampleView(View):
    """
    You can login with **'test', 'test'.** or use curl:

    `curl -X GET -H 'Accept: application/json' -u test:test http://localhost:8000/permissions-example`
    """

    permissions = (IsAuthenticated, )

    def get(self, request):
        return 'You have permission to view this resource'
github devilry / devilry-django / devilry / devilry_student / rest / open_groups.py View on Github external
## Response
    List of objects with the following attributes:

    - ``id`` (int): Internal Devilry ID of the group. Is never ``null``.
    - ``name`` (string|null): The name of the group.
    - ``assignment`` (object): Information about the assignment.
    - ``period`` (object): Information about the period.
    - ``subject`` (object): Information about the subject.
    - ``active_deadline`` (object): Information about the active deadline.
    - ``deliveries`` (object): Number of deliveries.

    The response is ordered by active deadline, with the groups with oldest
    active deadline first.
    """
    permissions = (IsAuthenticated,)
    resource = OpenGroupsResource

    def get_queryset(self):
        qry = AssignmentGroup.active_where_is_candidate(self.request.user)
        qry = qry.filter(is_open=True)
        qry = qry.filter(parentnode__delivery_types=0) # Only include ELECTRONIC - for now this makes sense, and if we need NON-ELECTRONIC, we make a new API, or add an option to this API.
        qry = qry.annotate(newest_deadline=Max('deadlines__deadline'))
        qry = qry.annotate(deadline_count=Count('deadlines__deadline'))
        qry = qry.filter(deadline_count__gt=0)

        # Only include assignments with one of:
        #   - SOFT deadline handling
        #   - deadline has NOT expired
        qry = qry.filter(Q(parentnode__deadline_handling=0) |
                         Q(newest_deadline__gt=datetime.now()))
github devilry / devilry-django / src / devilry_nodeadmin / devilry_nodeadmin / rest / nodedetails.py View on Github external
def _serialize_node(self, node):
        return {
            'id': node.id,
            'short_name': node.short_name,
            'long_name': node.long_name
        }

    def childnodes(self, instance):
        return [self._serialize_node(node) for node in instance.child_nodes.all()]




class NodeDetails( InstanceModelView ):
    resource = NodeDetailsResource
    permissions = (IsAuthenticated, IsNodeAdmin,)
    allowed_methods = ('get',)

    def get_instance_data(self, instance):
        return instance
github devilry / devilry-django / src / devilry_subjectadmin / devilry_subjectadmin / rest / period.py View on Github external
def authenticate_postrequest(self, user, parentnode_id):
        subjectadmin_required(user, parentnode_id)

    def get_queryset(self):
        qry = super(ListOrCreatePeriodRest, self).get_queryset()
        qry = qry.order_by('-start_time')
        return qry



class InstancePeriodRest(BaseNodeInstanceModelView):
    """
    This API provides read, update and delete on a single subject.
    """
    permissions = (IsAuthenticated, IsPeriodAdmin)
    resource = PeriodInstanceResource

    def get_queryset(self):
        qry = super(InstancePeriodRest, self).get_queryset()
        qry = qry.select_related('parentnode', 'parentnode__parentnode')
        qry = qry.prefetch_related('admins', 'admins__devilryuserprofile',
                                   'parentnode__admins', 'parentnode__admins__devilryuserprofile')
        qry = qry.annotate(number_of_relatedstudents=Count('relatedstudent', distinct=True),
                           number_of_relatedexaminers=Count('relatedexaminer', distinct=True))
        return qry
github devilry / devilry-django / src / devilry_qualifiesforexam / devilry_qualifiesforexam / rest / preview.py View on Github external
## Parameters
    The following parameters are required:

    - ``periodid``: The ID of the period. Supplied as the last part of the URL-path.
      404 is returned unless the user is admin on this period.
    - ``pluginsessionid``: Forwarded from the first page of the wizard. It is an ID
      used to lookup the output from the plugin, included in the listing in the plugins
      REST API.

    ## Returns
    An object/dict with the following attributes:

    - ``pluginoutput``: The serialized output from the plugin.
    - ``perioddata``: All results for all students on the period.
    """
    permissions = (IsAuthenticated, IsPeriodAdmin)

    def get(self, request, id):
        pluginsessionid = self.request.GET.get('pluginsessionid', None)
        if not pluginsessionid:
            raise ErrorResponse(statuscodes.HTTP_400_BAD_REQUEST,
                {'detail': '``pluginsessionid`` is a required parameter'})
        period = get_object_or_404(Period, pk=id)
        previewdata = self.request.session[create_sessionkey(pluginsessionid)]
        grouper = GroupsGroupedByRelatedStudentAndAssignment(period)
        return {
            'perioddata': grouper.serialize(),
            'pluginoutput': previewdata
        }
github devilry / devilry-django / src / devilry_subjectadmin / devilry_subjectadmin / rest / assignment.py View on Github external
def gradingsystemplugin_title(self, instance):
        if isinstance(instance, self.model):
            try:
                pluginapi = instance.get_gradingsystem_plugin_api()
            except GradingSystemPluginNotInRegistryError:
                return None
            else:
                return unicode(pluginapi.title)



class ListOrCreateAssignmentRest(BaseNodeListOrCreateView):
    """
    List the subjects where the authenticated user is admin.
    """
    permissions = (IsAuthenticated,)
    resource = AssignmentResource

    def authenticate_postrequest(self, user, parentnode_id):
        periodadmin_required(user, parentnode_id)

    def get_queryset(self):
        qry = super(ListOrCreateAssignmentRest, self).get_queryset()
        qry = qry.order_by('-publishing_time')
        return qry


class InstanceAssignmentRest(BaseNodeInstanceModelView):
    """
    This API provides read, update and delete on a single subject.
    """
    permissions = (IsAuthenticated, IsAssignmentAdmin)
github devilry / devilry-django / src / devilry_subjectadmin / rest / passedinpreviousperiod.py View on Github external
- ``period``: An object describing the period of the old group. Attributes:
                ``id``: ID of the period.
                ``short_name``: Short name of the period.
                ``long_name``: Long name of the period.
            - ``grade``: The shortformat formatted feedback of the old group.

    # PUT
    Mark groups as passed previously. Takes a list/array of groups to pass, each group is an object
    with the following attributes:

    - ``id`` (int): The ID of a group that should be marked as approved in a previous period.
      Must be a group in the
    - ``newfeedback_points`` (int): The feedback that should be added to the delivery
      that is made to mark this as a previously passed group.
    """
    permissions = (IsAuthenticated, IsAssignmentAdmin)
    resource = PassedInPreviousPeriodResource

    def validate_request(self, datalist, files=None):
        cleaned_datalist = []
        if not isinstance(datalist, list):
            datalist = [datalist]
        for data in datalist:
            cleaned_data = super(PassedInPreviousPeriod, self).validate_request(data)
            cleaned_datalist.append(cleaned_data)
        return cleaned_datalist

    def _get_assignment(self, id):
        try:
            return Assignment.objects.get(id=id)
        except Assignment.DoesNotExist:
            raise NotFoundError('Assignment with id={0} not found'.format(id))