Skip to content

Instantly share code, notes, and snippets.

@spscream
Created April 2, 2015 09:39
Show Gist options
  • Select an option

  • Save spscream/404ceb39595b29ba2104 to your computer and use it in GitHub Desktop.

Select an option

Save spscream/404ceb39595b29ba2104 to your computer and use it in GitHub Desktop.
define ['backbone', 'marionette', 'config/backbone/auth'], (Backbone, Marionette, Auth) ->
App = new Marionette.Application
App.auth = new Auth
App.auth.login
email: 'email@example.org'
password: 'password'
App.auth.on 'logged_in', ->
console.log "Authenticated!"
App.on "start", ->
require ["backbone/apps/layout/layout_app"], ->
App.module("LayoutApp").start()
App
define ['backbone', 'cookies'], (Backbone, cookies) ->
class AuthModel extends Backbone.Model
defaults:
cookieName: '_token'
token: undefined
authenticated: false
tokenUrl: '/api/v1/sessions'
initialize: ->
@checkCookie()
@_configureAjax()
checkCookie: ->
token = cookies.get @get('cookieName')
token = undefined if !token?
@set {
authenticated: !!token
token: token
}
@trigger 'logged_in', @get('token') if token?
login: (credentials) ->
cookies.set(@get('cookieName'), '123321123')
@checkCookie()
logout: ->
cookies.expire @get('cookieName')
@set {
token: undefined
authenticated: false
}
@trigger 'logout'
_configureAjax: ->
auth = @
Backbone.$.ajaxSetup
beforeSend: (jqXHR) ->
if auth.get('authenticated')
jqXHR.setRequestHeader 'Authorization', 'Token token=' + auth.get('token')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment