Created
February 9, 2015 12:14
-
-
Save rnewson/4acc3b9cd2d79718653e to your computer and use it in GitHub Desktop.
login from jquery.couch.js
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
/** | |
* Authenticate against CouchDB, the <code>options</code> parameter is | |
*expected to have <code>name</code> and <code>password</code> fields. | |
* @see <a href="http://docs.couchdb.org/en/latest/api/server/authn.html | |
* #post--_session">docs for POST /_session</a> | |
* @param {ajaxSettings} options | |
* <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings"> | |
* jQuery ajax settings</a> | |
*/ | |
login: function(options) { | |
options = options || {}; | |
return $.ajax({ | |
type: "POST", url: this.urlPrefix + "/_session", dataType: "json", | |
data: {name: options.name, password: options.password}, | |
beforeSend: function(xhr) { | |
xhr.setRequestHeader('Accept', 'application/json'); | |
}, | |
complete: function(req) { | |
var resp = $.parseJSON(req.responseText); | |
if (req.status == 200) { | |
if (options.success) options.success(resp); | |
} else if (options.error) { | |
options.error(req.status, resp.error, resp.reason); | |
} else { | |
throw 'An error occurred logging in: ' + resp.reason; | |
} | |
} | |
}); | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment