Restrict the listed submission for the current user.
963663
def get_queryset(self, request):
        ''' '''
        qs = super(SubmissionAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            return qs.filter(Q(assignment__course__tutors__pk=request.user.pk) | Q(assignment__course__owner=request.user)).distinct()
207149
def revoke_user_access(self, user, db_names, strict=True):
        
        user = utils.get_name(user)
        db_names = self._get_db_names(db_names, strict=strict)
        bad_names = []
        for db_name in db_names:
            uri = "/%s/%s/databases/%s" % (self.uri_base, user, db_name)
            resp, resp_body = self.api.method_delete(uri)
807920
def user_is_submission_owner(self, submission):
        
        if not self._user_manager.session_logged_in():
            raise Exception("A user must be logged in to verify if he owns a jobid")

        return self._user_manager.session_username() in submission["username"]
1021433
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1):
        

        if max_submissions_bound <= 0:
            max_submissions = task.get_stored_submissions()
        elif task.get_stored_submissions() <= 0:
            max_submissions = max_submissions_bound
        else:
            max_submissions = min(max_submissions_bound, task.get_stored_submissions())

        if max_submissions <= 0:
            return []
        tasks = list(self._database.submissions.find(
            {"username": username, "courseid": task.get_course_id(), "taskid": task.get_id()},
            projection=["_id", "status", "result", "grade", "submitted_on"],
            sort=[('submitted_on', pymongo.ASCENDING)]))

        # List the entries to keep
        to_keep = set([])

        if task.get_evaluate() == 'best':
            # Find the best "status"="done" and "result"="success"
            idx_best = -1
            for idx, val in enumerate(tasks):
                if val["status"] == "done":
                    if idx_best == -1 or tasks[idx_best]["grade"] < val["grade"]:
                        idx_best = idx

            # Always keep the best submission
            if idx_best != -1:
                to_keep.add(tasks[idx_best]["_id"])
        elif task.get_evaluate() == 'student':
            user_task = self._database.user_tasks.find_one({
                "courseid": task.get_course_id(),
                "taskid": task.get_id(),
                "username": username
            })

            submissionid = user_task.get('submissionid', None)
            if submissionid:
                to_keep.add(submissionid)

        # Always keep running submissions
        for val in tasks:
            if val["status"] == "waiting":
                to_keep.add(val["_id"])

        while len(to_keep) < max_submissions and len(tasks) > 0:
            to_keep.add(tasks.pop()["_id"])

        to_delete = {val["_id"] for val in tasks}.difference(to_keep)
        self._database.submissions.delete_many({"_id": {"$in": list(to_delete)}})

        return list(map(str, to_delete))
975548
def get_user_last_submissions(self, limit=5, request=None):
        
        if request is None:
            request = {}

        request.update({"username": self._user_manager.session_username()})

        # Before, submissions were first sorted by submission date, then grouped
        # and then resorted by submission date before limiting. Actually, grouping
        # and pushing, keeping the max date, followed by result filtering is much more
        # efficient
        data = self._database.submissions.aggregate([
            {"$match": request},
            {"$group": {"_id": {"courseid": "$courseid", "taskid": "$taskid"},
                        "submitted_on": {"$max": "$submitted_on"},
                        "submissions": {"$push": {
                            "_id": "$_id",
                            "result": "$result",
                            "status" : "$status",
                            "courseid": "$courseid",
                            "taskid": "$taskid",
                            "submitted_on": "$submitted_on"
                        }},
            }},
            {"$project": {
                "submitted_on": 1,
                "submissions": {
                    # This could be replaced by $filter if mongo v3.2 is set as dependency
                    "$setDifference": [
                        {"$map": {
                            "input": "$submissions",
                            "as": "submission",
                            "in": {
                                "$cond": [{"$eq": ["$submitted_on", "$$submission.submitted_on"]}, "$$submission", False]
                            }
                        }},
                        [False]
                    ]
                }
            }},
            {"$sort": {"submitted_on": pymongo.DESCENDING}},
            {"$limit": limit}
        ])

        return [item["submissions"][0] for item in data]
994790
def blockUser(self, user_id):
        
        data = {"fbid": user_id}
        r = self._post(self.req_url.BLOCK_USER, data)
        return r.ok
1340246
public function deny()
    {
        $app = Facade::getFacadeApplication();
        $db = $app->make('database')->connection();
        $cvID = $this->cvID;
        $cID = $this->cID;

        // first we update a collection updated record
        $dh = $app->make('helper/date');
        $db->executeQuery('update Collections set cDateModified = ? where cID = ?', array(
            $dh->getOverridableNow(),
            $cID,
        ));

        // first we remove approval for all versions of this collection
        $v = array(
            $cID,
        );
        $q = "update CollectionVersions set cvIsApproved = 0 where cID = ?";
        $db->executeQuery($q, $v);
        $this->cvIsApproved = 0;

        // now we deny our version
        $v2 = array(
            $cID,
            $cvID,
        );
        $q2 = "update CollectionVersions set cvIsApproved = 0, cvApproverUID = 0 where cID = ? and cvID = ?";
        $db->executeQuery($q2, $v2);
        $this->refreshCache();
    }
472622
def allow(self, comment, content_object, request):
        """"""
        
        POST = urlencode({
                "blog": settings.AKISMET_BLOG.encode("utf-8"),
                "user_ip": comment.ip_address,
                "user_agent": request.META.get('HTTP_USER_AGENT', "").
                                                encode("utf-8"),
                "referrer": request.META.get('HTTP_REFERRER', "").
                                                encode("utf-8"),
                "comment_author": comment.user_name.encode("utf-8"),
                "comment_author_email": comment.user_email.encode("utf-8"),
                "comment_author_url": comment.user_url.encode("utf-8"),
                "comment_content": comment.comment.encode("utf-8")})
        connection = HTTPConnection(AKISMET_URL, AKISMET_PORT)
        connection.request("POST", AKISMET_PATH, POST,
                           {"User-Agent": AKISMET_USERAGENT,
                            "Content-type":"application/x-www-form-urlencoded"
                            })
        response = connection.getresponse()
        status, result = response.status, response.read()
        if result == "false":
            return True
        elif result == "true" and settings.DISCARD_SPAM:
            return False
        elif result == "true":
            comment.is_removed = True
            comment.is_public = False
            return True
        else:
            raise AkismetError(status, result)
135936
public void blockUser(Integer targetUserId) throws IOException {

        String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.BLOCK_URL;

        retrieve().method(POST).to(tailUrl, Void.class);
    }
988351
def _validate_user(self, user):
        """"""
        # All users allowed
        if self._show_all_users:
            return

        # User specifically allowed
        if user.id in self._allowed_user_ids:
            return

        # User allowed by group membership
        user_member_group_ids = set([g['id'] for g in user._raw['groups']])
        if user_member_group_ids & self._allowed_member_ids:
            return

        raise ValidationError(
            self.record,
            'User `{}` is not a valid selection for field `{}`'.format(
                user,
                self.name
            )
        )
1019428
def restrict_to(self, restriction):
        
        if type(restriction) != list:
            restriction = [ restriction ]
        self._restriction = restriction
602591
def set_selected_submission(self, course, task, submissionid):
        

        submission = self.submission_manager.get_submission(submissionid)

        # Do not continue if submission does not exist or is not owned by current user
        if not submission:
            return False

        # Check if the submission if from this task/course!
        if submission["taskid"] != task.get_id() or submission["courseid"] != course.get_id():
            return False

        is_staff = self.user_manager.has_staff_rights_on_course(course, self.user_manager.session_username())

        # Do not enable submission selection after deadline
        if not task.get_accessible_time().is_open() and not is_staff:
            return False

        # Only allow to set submission if the student must choose their best submission themselves
        if task.get_evaluate() != 'student' and not is_staff:
            return False

        # Check if task is done per group/team
        if task.is_group_task() and not is_staff:
            group = self.database.aggregations.find_one(
                {"courseid": task.get_course_id(), "groups.students": self.user_manager.session_username()},
                {"groups": {"$elemMatch": {"students": self.user_manager.session_username()}}})
            students = group["groups"][0]["students"]
        else:
            students = [self.user_manager.session_username()]

        # Check if group/team is the same
        if students == submission["username"]:
            self.database.user_tasks.update_many(
                {"courseid": task.get_course_id(), "taskid": task.get_id(), "username": {"$in": students}},
                {"$set": {"submissionid": submission['_id'],
                          "grade": submission['grade'],
                          "succeeded": submission["result"] == "success"}})
            return True
        else:
            return False
1231711
def revoke(perm, group_list = [])
      validate_usergroup_list(group_list)
      api.post(['revoke', perm].uri_concat, group_list, 'application/json')
    end
407065
def do_denyaccess(self, line):
        """"""
        subject, = self._split_args(line, 1, 0)
        self._command_processor.get_session().get_access_control().remove_allowed_subject(
            subject
        )
        self._print_info_if_verbose(
            'Removed subject "{}" from access policy'.format(subject)
        )
430324
protected void validatePrivilegedUser(HttpServletRequest req) {
        if (!getRemoteUser(req).isPrivileged()) {
            throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
        }
    }
287092
def permitted?(requested_flags = 0)
      current_user_roles.any?{|ug| ug.admin?} ||
      current_model_permissions.any?{|cp| cp.permitted?(requested_flags)}
    end
825596
def deny(cls, action, **kwargs):
        
        return cls.create(action, exclude=True, **kwargs)