Create a gist now

Instantly share code, notes, and snippets.

Basic Auth manager for Ember
App.authManager = Ember.StateManager.create
# The "stack" contains the currently logged-in user
stack: []
# Callbacks to be ran once the user is authenticated
callbacks: {}
# Grabs the current auth object and returns it
# If callback argument is given, will run the callback function with current auth object as first argument
# If there is no authenticated user:
# callback provided: ask for authentication, then run callback
# callback not provided: return undefined
current: (callback) ->
# if callback is given, use callback, invoking login window if needed
if callback
if(current = @current())
callback current
@force_login callback
# else, find current authenticated user
# if no user, return undefined
# simple case: stack already exists
if @stack.length > 0
# else, stack doesn't have any auths, search in store and rerun function
# SEE IF AUTH EXISTS in sessionStorage
# (WILL NEED to modify this to fit your code)
records = App.sessionStore.findAll(App.Auth)
_.each records.get("content"), (element, index) =>
@stack.push records.objectAtContent index
if @stack.length > 0
return _.last(@stack)
return undefined
force_login: (callback) ->
@add_callback "after_authenticate", callback
@transitionTo "authenticating"
authenticate: (user) ->
# check if the user is valid, probably by sending credentials via AJAX request
add_callback: (type, callback) ->
@callbacks[type] = [] unless typeof @callbacks[type] is "object"
@callbacks[type].push callback
do_callbacks: (type, args) ->
_.each @callbacks[type], (_callback) ->
_callback args
@clear_callbacks type
clear_callbacks: (type) ->
@callbacks[type] = []
authenticating: Em.State.create
enter: (manager) ->
controller: App.get("router").get('authController')
outletName: 'modal'
viewClass: App.NewAuthView
context: App.Auth.createRecord()
exit: (manager) ->
App.get("router").get("applicationController").get("modal").close ->
authenticated: Em.State.create
enter: (manager) ->
App.authManager.do_callbacks "after_authenticate", _.last(App.authManager.stack)
App.authManager.current (auth) =>
# This function is only ran once auth is available (the user logs in)
# So you are safe to do functions that requires a logged in user
# In my implementation, this method is part of my ember-data restful-api adapter, and simply
# overrides the default ajax method, wrapping it inside this calback...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment