Created
November 5, 2014 01:56
-
-
Save georgeOsdDev/9c952944cf54f8a1ad77 to your computer and use it in GitHub Desktop.
Thenable login
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Utils = {}; | |
var deferApply = function() { | |
var args = Array.prototype.slice.apply(arguments), | |
f = args[0], | |
realArgs = args.slice(1) | |
; | |
return new Promise(function(done, reject) { | |
return f.apply(null, [done, reject].concat(realArgs)); | |
}); | |
}; | |
Utils.deferApply = deferApply; | |
function authAllowAll(done, reject, user_id, password){ | |
return done({user_id:user_id, password:password}); | |
} | |
function authDefault(url){ | |
return function(done, reject, user_id, password, option){ | |
if (window.XMLHttpRequest) { | |
httpRequest = new XMLHttpRequest(); | |
if (httpRequest.overrideMimeType) { | |
httpRequest.overrideMimeType('text/plain'); | |
} | |
} else if (window.ActiveXObject) { | |
try { | |
httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); | |
} catch (e) { | |
try { | |
httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); | |
} catch (e) {} | |
} | |
} | |
if (!httpRequest) return reject({}); | |
httpRequest.onreadystatechange = function() { | |
if (httpRequest.readyState == 4) { | |
if (httpRequest.status == 200) { | |
done(httpRequest.responseText) | |
} else { | |
reject(httpRequest.status) | |
} | |
} | |
}; | |
httpRequest.open('POST', url, true); | |
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
httpRequest.send("user_id="+user_id+"&password="+password); | |
} | |
} | |
function authCustom(done, reject, user_id, password, option){ | |
function customAuthentication(user_id,password,option){ | |
return true; // or false; | |
} | |
var result = customAuthentication(user_id, password, option); | |
if (result) return done(result); | |
return reject(result); | |
} | |
function loginSuccess(result){ | |
console.log("success:"+result); | |
} | |
function loginFail(result){ | |
console.log("fail:"+result); | |
} | |
function thenableLogin(login){ | |
return function(user_id, password, option){ | |
return Utils.deferApply(login, user_id, password, option); | |
} | |
} | |
var loginAction = thenableLogin(authAllowAll); | |
loginAction("bob","password").then(loginSuccess, loginFail) | |
var loginAction2 = thenableLogin(authDefault("http://localhost:9000/login")); | |
loginAction2("bob","bob#secret").then(loginSuccess, loginFail); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment