var auth = (function(){ var auth = {} auth.appname = is_iphone ? "bucky-web/3.0.0" : "bucky-web/3.0.0" auth.apikey = "influssiblefraubuzzardsunsetideogrammatton" auth.device = "browser" auth.user = {id:-1} auth.next_view = null auth.init = function(fn){ // if we're on an authentication page, ignore the current user if (window.location.pathname === '/login' || window.location.pathname === '/signup') { fn && fn( false ) return } auth.load_user(function(user){ var logged_in = auth.logged_in() if (logged_in) { fn && fn() return } auth.checkin({ success: function(user){ if (user) { auth.set_user(user, fn) } }, error: function(){ window.location.href = "/login" } }) }) } auth.get_user = function(cb){ cb && cb(auth.user) } auth.set_user = function(user, cb){ auth.user = user localStorage.setItem("bucky.user", JSON.stringify(user)) cb && cb() } auth.load_user = function(cb){ var user var user_str = localStorage.getItem("bucky.user") if (user_str && user_str.length) { try { user = JSON.parse(user_str) if (! user.id) user = {id:-1} } catch(e) { user = {id:-1} } } auth.user = user cb && cb(user) } auth.clear_user = function(cb){ auth.user = {id:-1} localStorage.removeItem("bucky.user") cb && cb() } auth.log_out = function(){ auth.clear_user() } auth.logged_in = function(){ return (auth.user && auth.user.id && auth.user.id !== -1 && auth.user.id !== "undefined") } auth.checkin = function(opt){ $.ajax({ method: 'put', url: '/api/checkin', headers: { "csrf-token": $("[name=_csrf]").attr("value") }, success: function(data){ if (data && data.user && data.user.id && data.user.id !== -1) { auth.set_user(data.user) opt.success(data.user) return } opt.error() }, error: function(){ window.location.href = '/login' opt.error() }, }) } return auth })()