正确使用nano.auth

时间:2014-04-16 04:41:41

标签: node.js authentication cookies couchdb couchdb-nano

所以根据这里的纳米文档:https://github.com/dscape/nano#using-cookie-authentication,您可以通过以下方式验证用户:(在coffeescript中)

nano = require('nano') 'http://localhost:5984'
nano.auth username, password

我对此很好,我可以得到正确的答案,我遇到的麻烦是事后要做什么。我最初的想法是做以下事情(当使用管理员用户名和密码设置通过蒲团时):

nano = require('nano') 'http://localhost:5984'
nano.auth username, password
nano.db.create 'test', (err, body) -> #err here is always [Error: you are not a server admin.]

如果我调试了从nano.auth返回的错误,正文和标题,我得到:

err: null
body: { ok: true, name: null, roles: [ '_admin' ] }
header: { 'set-cookie': [ 'AuthSession=bm9kZV9hZG1pbjo1MzRFMTEwQzoGNe9XUrMu5IKYPK3BP3GQyHeRWQ; Version=1; Path=/; HttpOnly' ],
    date: 'Wed, 16 Apr 2014 05:11:40 GMT',
    'content-type': 'text/plain; charset=utf-8',
    'cache-control': 'must-revalidate',
    'status-code': 200,
    uri: 'http://127.0.0.1:5984/_session' }

在我的测试中,我也尝试了以下似乎无效的

nano = require('nano') "#{prefix}://#{security.couchdb.url}"
cookie = ''
nano.auth security.couchdb.admin_user.username, security.couchdb.admin_user.password, (err, response, headers) ->
    console.log "Nano_admin Setup"
    console.log err
    console.log response
    console.log headers
    cookie = headers['set-cookie']
nano = require('nano')
    url: "#{prefix}://#{security.couchdb.url}"
    cookie: "AuthSession=#{cookie}"
nano.db.create 'test', (err, body) -> #err here is always [Error: you are not a server admin.]

任何人都可以指出我出错了/误解了什么吗?

1 个答案:

答案 0 :(得分:5)

我明白了 - 现在我觉得很傻。永远记住node.js是异步的。

正确的做法:

nano = require('nano') 'http://localhost:5984'
nano.auth username, password, (err, response, headers) ->
    nano = require('nano')
        url: 'http://localhost:5984'
        cookie: headers['set-cookie']
    nano.db.create 'test', (err, body) ->