Skip to content

Instantly share code, notes, and snippets.

@spscream
Created April 2, 2015 10:48
Show Gist options
  • Select an option

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

Select an option

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