Skip to content

Instantly share code, notes, and snippets.

@jbarnette
Created October 12, 2011 16:03
Show Gist options
  • Save jbarnette/1281648 to your computer and use it in GitHub Desktop.
Save jbarnette/1281648 to your computer and use it in GitHub Desktop.
# If an AJAX request starts with "/api", transform it into a
# cross-site request to the API server and attach an API token. If
# it's an AJAX request to the local stack, add X-CSRF. If an AJAX
# response status is 403, it means the current API token has expired,
# so ask the local stack for a new token and retry the request.
apiToken = $("meta[name='api.token']").attr "value"
apiURL = $("meta[name='api.url']").attr "value"
csrf = $("meta[name=csrf]").attr "value"
$.ajaxPrefilter (settings, original, xhr) ->
settings.url = settings.url.replace /^\/api/, apiURL
if settings.url.indexOf(apiURL) is 0
xhr.setRequestHeader "X-Audiosocket-Token", apiToken
settings.error = (xhr, status, error) ->
if xhr.status is 403
$.ajax "/token",
type: "POST"
success: (data) ->
apiToken = data.token
$.ajax original
else if original.error
original.error xhr, status, error
else if settings.url.substr(0, 1) is "/"
xhr.setRequestHeader "X-CSRF", csrf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment