public final function check_capability() {
        global $USER;

        // The context we are on.
        $currentcontext = $this->context;

        // Ensure that the user can view the repository in the current context.
        $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);

        // Context in which the repository has been created.
        $repocontext = context::instance_by_id($this->instance->contextid);

        // Prevent access to private repositories when logged in as.
        if ($can && \core\session\manager::is_loggedinas()) {
            if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
                $can = false;
            }
        }

        // We are going to ensure that the current context was legit, and reliable to check
        // the capability against. (No need to do that if we already cannot).
        if ($can) {
            if ($repocontext->contextlevel == CONTEXT_USER) {
                // The repository is a user instance, ensure we're the right user to access it!
                if ($repocontext->instanceid != $USER->id) {
                    $can = false;
                }
            } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
                // The repository is a course one. Let's check that we are on the right course.
                if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
                    $coursecontext = $currentcontext->get_course_context();
                    if ($coursecontext->instanceid != $repocontext->instanceid) {
                        $can = false;
                    }
                } else {
                    // We are on a parent context, therefore it's legit to check the permissions
                    // in the current context.
                }
            } else {
                // Nothing to check here, system instances can have different permissions on different
                // levels. We do not want to prevent URL hack here, because it does not make sense to
                // prevent a user to access a repository in a context if it's accessible in another one.
            }
        }

        if ($can) {
            return true;
        }

        throw new repository_exception('nopermissiontoaccess', 'repository');
    }