How to restrict users to only access their own media files in wordpress

You can add an author parameter to array in get_children.

Line 2 of your code will look like this:

<?php
    $attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' =>'image', 'author' => get_current_user_id() ) );