'Return all data libraries that the received user can access'

def get_accessible_libraries(self, trans, user):

    accessible_libraries = []
    current_user_role_ids = [role.id for role in user.all_roles()]
    library_access_action = self.permitted_actions.LIBRARY_ACCESS.action
    restricted_library_ids = [lp.library_id for lp in trans.sa_session.query(trans.model.LibraryPermissions).filter((trans.model.LibraryPermissions.table.c.action == library_access_action)).distinct()]
    accessible_restricted_library_ids = [lp.library_id for lp in trans.sa_session.query(trans.model.LibraryPermissions).filter(and_((trans.model.LibraryPermissions.table.c.action == library_access_action), trans.model.LibraryPermissions.table.c.role_id.in_(current_user_role_ids)))]
    for library in trans.sa_session.query(trans.model.Library).filter(and_((trans.model.Library.table.c.deleted == false()), or_(not_(trans.model.Library.table.c.id.in_(restricted_library_ids)), trans.model.Library.table.c.id.in_(accessible_restricted_library_ids)))).order_by(trans.app.model.Library.name):
        accessible_libraries.append(library)
    return accessible_libraries
