           'notebook.lnb':
             content: JSON.stringify notebook, undefined, 2
       @async ->
-        promise = github.save_gist gist
-        promise.done (result) =>
-          @html "<a href='#{result.html_url}'>#{result.html_url}</a>"
-          lead_uri = URI window.location.href
-          lead_uri.fragment "/#{result.html_url}"
-          @html "<a href='#{lead_uri}'>#{lead_uri}</a>"
-        promise.fail =>
-          @error 'Save failed. Make sure your access token is configured correctly.'
+        authorized = ensure_access @
+        authorized.then =>
+          promise = github.save_gist gist
+          promise.done (result) =>
+            @html "<a href='#{result.html_url}'>#{result.html_url}</a>"
+            lead_uri = URI window.location.href
+            lead_uri.fragment "/#{result.html_url}"
+            @html "<a href='#{lead_uri}'>#{lead_uri}</a>"
+          promise.fail =>
+            @error 'Save failed. Make sure your access token is configured correctly.'
 
     github

          @error response.statusText
        promise

    cmd 'gist', 'Loads a script from a gist', (gist, options={}) ->
      if arguments.length is 0
        @github.save_gist()
      else
        url = github.to_gist_url gist
        @async ->
          @text "Loading gist #{gist}"
          promise = http.get url
          promise.done (response) =>
            for name, file of response.files
              notebook.handle_file @, file, options
          promise.fail (response) =>
            @error response.statusText

    cmd 'save_gist', 'Saves a notebook as a gist', ->
      notebook = @export_notebook()


define (require) ->
  URI = require 'URIjs'
  Q = require 'q'
  modules = require 'modules'
  http = require 'http'
  global_settings = require 'settings'

  notebook = null
  require ['notebook'], (nb) ->
