 {coroutine: $coroutine} = require 'bluebird'
 {format} = require 'json-rpc-peer'
 
-{JsonRpcError} = require('../api-errors')
+{
+  JsonRpcError,
+  Unauthorized
+} = require('../api-errors')
 {
   formatXml: $js2xml,
   parseXml,
   pFinally
 } = require '../utils'
 {isVmRunning: $isVMRunning} = require('../xapi')
+
+#=====================================================================
+
+checkPermissionsForSnapshot = (vm) -> (
+  permissions = []
+  $forEach(vm.$VBDs, (vbdId) =>
+    vbd = @getObject(vbdId, 'VBD')
+    vdiId = vbd.VDI
+
+    if vbd.is_cd_drive or not vdiId
+      return
+
+    permissions.push([
+      @getObject(vdiId, 'VDI').$SR,
+      'operate'
+    ])
+  )
+
+  return @hasPermissions(@session.get('user_id'), permissions).then((success) => (
+    throw new Unauthorized() unless success
+  ))
+)
 
 #=====================================================================
 


# TODO: integrate in xapi.js
export_ = $coroutine ({vm, compress, onlyMetadata}) ->
  stream = yield @getXAPI(vm).exportVm(vm.id, {
    compress: compress ? true,
    onlyMetadata: onlyMetadata ? false

#---------------------------------------------------------------------

rollingSnapshot = $coroutine ({vm, tag, depth}) ->
  yield checkPermissionsForSnapshot.call(this, vm)

  snapshot = yield @getXAPI(vm).rollingSnapshotVm(vm.ref, tag, depth)
  return snapshot.$id

