diff options
author | isaacs <i@izs.me> | 2012-09-25 19:23:55 +0400 |
---|---|---|
committer | isaacs <i@izs.me> | 2012-09-25 19:23:55 +0400 |
commit | edd98f43f000c4ffe5693d141858191114e7b013 (patch) | |
tree | 8b5b3986d0339d8d46e4305cc0b7f1be87607066 | |
parent | 643979090221ce18ea72c462379a7a442450d261 (diff) |
couch-login@0.1.12
-rw-r--r-- | node_modules/couch-login/couch-login.js | 76 | ||||
-rw-r--r-- | node_modules/couch-login/package.json | 4 | ||||
-rw-r--r-- | node_modules/couch-login/test/basic.js | 13 |
3 files changed, 76 insertions, 17 deletions
diff --git a/node_modules/couch-login/couch-login.js b/node_modules/couch-login/couch-login.js index be037f0f2..a2b323439 100644 --- a/node_modules/couch-login/couch-login.js +++ b/node_modules/couch-login/couch-login.js @@ -2,6 +2,7 @@ var request = require('request') , url = require('url') , crypto = require('crypto') , YEAR = (1000 * 60 * 60 * 24 * 365) +, BASIC = {} module.exports = CouchLogin @@ -13,11 +14,28 @@ function CouchLogin (couch, tok) { if (!couch) throw new Error( "Need to pass a couch url to CouchLogin constructor") - // having auth completely defeats the purpose + if (couch instanceof CouchLogin) + couch = couch.couch + couch = url.parse(couch) + if (couch.auth) { + var a = couch.auth.split(':') + var name = a.shift() + var password = a.join(':') + this.name = name + if (password) + this.auth = new Buffer(name + ':' + password).toString('base64') + } else { + this.auth = null + this.name = null + } delete couch.auth - if (tok === 'anonymous') tok = NaN + if (tok === 'anonymous') + tok = NaN + else if (tok === 'basic') + tok = BASIC + this.token = tok this.couch = url.format(couch) this.proxy = null @@ -97,9 +115,16 @@ function makeReq (meth, body, f) { return function madeReq (p, d, cb) { , u = url.resolve(this.couch, p) , req = { uri: u, headers: h, json: true, body: d, method: meth } - if (this.token) { + if (this.token === BASIC) { + if (!this.auth) + return process.nextTick(cb.bind(this, new Error( + 'Using basic auth and no auth provided'))) + else + h.authorization = 'Basic ' + this.auth + } else if (this.token) { h.cookie = 'AuthSession=' + this.token.AuthSession } + if (this.proxy) { req.proxy = this.proxy } @@ -113,8 +138,19 @@ function makeReq (meth, body, f) { return function madeReq (p, d, cb) { }} function login (auth, cb) { + if (this.token === BASIC) { + this.auth = new Buffer(auth.name + ':' + auth.password).toString('base64') + this.name = auth.name + return process.nextTick(cb, null, { statusCode: 200 }, { ok: true }) + } var a = { name: auth.name, password: auth.password } - makeReq('post', true, true).call(this, '/_session', a, cb) + var req = makeReq('post', true, true) + req.call(this, '/_session', a, function (er, cr, data) { + if (er || (cr && cr.statusCode >= 400)) + return cb(er, cr, data) + this.name = auth.name + cb(er, cr, data) + }) } function changePass (auth, cb) { @@ -145,8 +181,12 @@ function changePass (auth, cb) { data.date = new Date().toISOString() this.put(u + '?rev=' + data._rev, data, function (er, res, data) { - if (er || res.statusCode >= 400) return cb(er, res, data) - this.login(auth, cb) + console.error('back from changepass', er, data, this.name) + if (er || res.statusCode >= 400) + return cb(er, res, data) + if (this.name && this.name !== auth.name) + return cb(er, res, data) + return this.login(auth, cb) }.bind(this)) }.bind(this)) } @@ -176,17 +216,18 @@ function deleteAccount (name, cb) { function signup (auth, cb) { - if (this.token) return this.logout(function (er, res, data) { - if (er || res.statusCode !== 200) { - return cb(er, res, data) - } + if (this.token && this.token !== BASIC) + return this.logout(function (er, res, data) { + if (er || res.statusCode !== 200) { + return cb(er, res, data) + } - if (this.token) { - return cb(new Error('failed to delete token'), res, data) - } + if (this.token) { + return cb(new Error('failed to delete token'), res, data) + } - this.signup(auth, cb) - }.bind(this)) + this.signup(auth, cb) + }.bind(this)) // make a new user record. var newSalt = crypto.randomBytes(30).toString('hex') @@ -221,6 +262,10 @@ function signup (auth, cb) { } function addToken (res) { + // not doing the whole login session cookie thing. + if (this.token === BASIC) + return + // attach the token, if a new one was provided. var sc = res.headers['set-cookie'] if (!sc) return @@ -294,6 +339,7 @@ function logout (cb) { } function valid (token) { + if (token === BASIC) return true if (!token) return false if (!token.hasOwnProperty('expires')) return true return token.expires > Date.now() diff --git a/node_modules/couch-login/package.json b/node_modules/couch-login/package.json index 7d62b739f..9ccd561b5 100644 --- a/node_modules/couch-login/package.json +++ b/node_modules/couch-login/package.json @@ -6,7 +6,7 @@ }, "name": "couch-login", "description": "A module for doing logged-in requests to a couchdb server", - "version": "0.1.10", + "version": "0.1.12", "repository": { "type": "git", "url": "git://github.com/isaacs/couch-login.git" @@ -22,6 +22,6 @@ "tap": "~0.2.4" }, "readme": "# couch-login\n\nThis module lets you log into couchdb to get a session token, then make\nrequests using that session. It is basically just a thin wrapper around\n[@mikeal's request module](https://github.com/mikeal/request).\n\nThis is handy if you want a user to take actions in a couchdb database\non behalf of a user, without having to store their couchdb username and\npassword anywhere. (You do need to store the AuthSession token\nsomewhere, though.)\n\n## Usage\n\n```javascript\nvar CouchLogin = require('couch-login')\n\n// Nothing about this module is http-server specific of course.\n// You could also use it to do authenticated requests against\n// a couchdb using sessions and storing the token somewhere else.\n\nhttp.createServer(function (req, res) {\n var couch = new CouchLogin('http://my-couch.iriscouch.com:5984/')\n\n // .. look up the token in the user's session or whatever ..\n // Look at couch.decorate(req, res) for more on doing that\n // automatically, below.\n\n if (sessionToken) {\n // this user already logged in.\n couch.token = sessionToken\n\n // now we can do things on their behalf, like:\n // 1. View their session info.\n // like doing request.get({ uri: couch + '/_session', ... })\n // but with the cookie and whatnot\n\n couch.get('/_session', function (er, resp, data) {\n // er = some kind of communication error.\n // resp = response object from the couchdb request.\n // data = parsed JSON response body.\n if (er || resp.statusCode !== 200) {\n res.statusCode = resp.statusCode || 403\n return res.end('Invalid login or something')\n }\n\n // now we have the session info, we know who this user is.\n // hitting couchdb for this on every request is kinda costly,\n // so maybe you should store the username wherever you're storing\n // the sessionToken. RedSess is a good util for this, if you're\n // into redis. And if you're not into redis, you're crazy,\n // because it is awesome.\n\n // now let's get the user record.\n // note that this will 404 for anyone other than the user,\n // unless they're a server admin.\n couch.get('/_users/org.couchdb.user:' + data.userCtx.name, etc)\n\n // PUTs and DELETEs will also use their session, of course, so\n // your validate_doc_update's will see their info in userCtx\n })\n\n } else {\n // don't have a sessionToken.\n // get a username and password from the post body or something.\n // maybe redirect to a /login page or something to ask for that.\n var login = { name: name, password: password }\n couch.login(login, function (er, resp, data) {\n // again, er is an error, resp is the response obj, data is the json\n if (er || resp.statusCode !== 200) {\n res.statusCode = resp.statusCode || 403\n return res.end('Invalid login or something')\n }\n\n // the data is something like\n // {\"ok\":true,\"name\":\"testuser\",\"roles\":[]}\n // and couch.token is the token you'll need to save somewhere.\n\n // at this point, you can start making authenticated requests to\n // couchdb, or save data in their session, or do whatever it is\n // that you need to do.\n\n res.statusCode = 200\n res.write(\"Who's got two thumbs and just logged you into couch?\\n\")\n setTimeout(function () {\n res.end(\"THIS GUY!\")\n }, 500)\n })\n }\n})\n```\n\n## Class: CouchLogin\n### new CouchLogin(couchdbUrl, token)\n\nCreate a new CouchLogin object bound to the couchdb url.\n\nIn addition to these, the `get`, `post`, `put`, and `del` methods all\nproxy to the associated method on [request](https://github.com/mikeal/request).\n\nHowever, as you'll note in the example above, only the pathname portion\nof the url is required. Urls will be appended to the couchdb url passed\ninto the constructor.\n\nIf you have to talk to more than one couchdb, then you'll need more than\none CouchLogin object, for somewhat obvious reasons.\n\nAll callbacks get called with the following arguments, which are exactly\nidentical to the arguments passed to a `request` callback.\n\n* `er` {Error | null} Set if a communication error happens.\n* `resp` {HTTP Response} The response from the request to couchdb\n* `data` {Object} The parsed JSON data from couch\n\nIf the token is the string \"anonymous\", then it will not attempt to log\nin before making requests. If the token is not \"anonymous\", then it\nmust be an object with the appropriate fields.\n\n### couch.token\n\n* {Object}\n\nAn object representing the couchdb session token. (Basically just a\ncookie and a timeout.)\n\nIf the token has already timed out, then setting it will have no effect.\n\n### couch.tokenSet\n\nIf set, this method is called whenever the token is saved.\n\nFor example, you could assign a function to this method to save the\ntoken into a redis session, a cookie, or in some other database.\n\nTakes a callback which should be called when the token is saved.\n\n### couch.tokenGet\n\nIf set, this method is called to look up the token on demand.\n\nThe inverse of couch.tokenSet. Takes a callback which is called with\nthe `cb(er || null, token)`.\n\n### couch.tokenDel\n\nIf set, this method is called to delete the token when it should be\ndiscarded.\n\nRelated to tokenGet and tokenSet. Takes a callback which should be\ncalled when the token is deleted.\n\n### couch.anonymous()\n\nReturn a new CouchLogin object that points at the same couchdb server,\nbut doesn't try to log in before making requests.\n\nThis is handy for situations where the user is not logged in at the\nmoment, but a request needs to be made anyway, and does not require\nauthorization.\n\n### couch.login(auth, callback)\n\n* `auth` {Object} The login details\n * `name` {String}\n * `password` {String}\n* `callback` {Function}\n\nWhen the callback is called, the `couch.token` will already have been\nset (assuming it worked!), so subsequent requests will be done as that\nuser.\n\n### couch.get(path, callback)\n\nGET the supplied path from the couchdb using the credentials on the\ntoken.\n\nFails if the token is invalid or expired.\n\n### couch.del(path, callback)\n\nDELETE the supplied path from the couchdb using the credentials on the\ntoken.\n\nFails if the token is invalid or expired.\n\n### couch.post(path, data, callback)\n\nPOST the data to the supplied path in the couchdb, using the credentials\non the token.\n\nFails if the token is invalid or expired.\n\n### couch.put(path, data, callback)\n\nPUT the data to the supplied path in the couchdb, using the credentials\non the token.\n\nFails if the token is invalid or expired.\n\n### couch.changePass(newAuth, callback)\n\nMust already be logged in. Updates the `_users` document with new salt\nand hash, and re-logs in with the new credentials. Callback is called\nwith the same arguments as login, or the first step of the process that\nfailed.\n\n### couch.signup(userData, callback)\n\nCreate a new user account. The userData must contain at least a `name`\nand `password` field. Any additional data will be copied to the user\nrecord. The `_id`, `name`, `roles`, `type`, `password_sha`, `salt`, and\n`date` fields are generated.\n\nAlso signs in as the newly created user, on successful account creation.\n\n### couch.deleteAccount(name, callback)\n\nDeletes a user account. If not logged in as the user, or a server\nadmin, then the request will fail.\n\nNote that this immediately invalidates any session tokens for the\ndeleted user account. If you are deleting the user's record, then you\nought to follow this with `couch.logout(callback)` so that it won't try\nto re-use the invalid session.\n\n### couch.logout(callback)\n\nDelete the session out of couchdb. This makes the token permanently\ninvalid, and deletes it.\n\n### couch.decorate(req, res)\n\nSet up `req.couch` and `res.couch` as references to this couch login\ninstance.\n\nAdditionall, if `req.session` or `res.session` is set, then it'll call\n`session.get('couch_token', cb)` as the tokenGet method,\n`session.set('couch_token', token, cb)` as the tokenSet method, and\n`session.del('couch_token', cb)` as the tokenDel method.\n\nThis works really nice with\n[RedSess](https://github.com/isaacs/redsess).\n", - "_id": "couch-login@0.1.10", + "_id": "couch-login@0.1.12", "_from": "couch-login@~0.1.9" } diff --git a/node_modules/couch-login/test/basic.js b/node_modules/couch-login/test/basic.js index fb280624a..660a24a0f 100644 --- a/node_modules/couch-login/test/basic.js +++ b/node_modules/couch-login/test/basic.js @@ -284,3 +284,16 @@ tap.test('sign up as new user', function (t) { }) }) }) + +tap.test('using basic auth', function (t) { + var c = new CouchLogin(couch.couch, 'basic') + c.login(auth, function () { + c.get('/_users/org.couchdb.user:testuser', function (er, res, data) { + if (er) + throw er + okStatus(t, res) + t.ok(data, 'data') + t.end() + }) + }) +}) |