node.js - Sails JS Passport session 持久性问题 : Mocha Test Failing

标签 node.js testing express sails.js mocha.js

我正在尝试使用 Mocha、Chai 和 Superagent 以及 SailsJS 和 Passport 作为身份验证框架来编写一些基本的身份验证测试。以下是我的测试场景,由于某种原因我无法保持持久 session ,这似乎是我最后一次查看用户是否有权访问 /userplansetting/edit 的测试失败。注意:我已经确认这在我通过网络界面登录时有效。

更新:这是一个包含类似代码和结果的存储库 https://github.com/robksawyer/sailsjs-starter-template

request = require("superagent")
crypto = require("crypto")
async = require("async")
chai = require("chai")
expect = chai.expect
should = chai.should()
assert = chai.assert

userStub = ->
  randString = crypto.randomBytes(20).toString("hex")
  username: randString.slice(0, 15)
  biography: randString + " is a auto generated user!"
  email: randString + "@gmail.com"
  password: "123123123123"
  displayName: "John Doe"
  language: "en-us"

describe "Auth", ->
  appURL = "http://localhost:1335"
  user = undefined
  agent1 = request.agent() # sails.hooks.http.app

  loginUser = (agent, userObj) ->
    (done) ->
      onResponse = (err, res) ->
        should.not.exist(err)
        res.status.should.eql 200
        res.text.should.include "Your Campaigns"
        done()
      agent.post(appURL + "/login")
        .send(userObj)
        .end onResponse

  registerUser = (agent, userObj) ->
    (done) ->
      onResponse = (err, res) ->
        should.not.exist(err)
        res.status.should.eql 200
        res.text.should.include "Your Campaigns"
        done()
      agent.post(appURL + "/auth/local/register")
        .send(userObj)
        .end onResponse

  describe "Register User", ->
    describe "JSON Requests", ->
      describe "POST", ->
        it "/auth/local/register should register a user", (done) ->
          uStub = userStub()
          password = uStub.password
          userObj =
            email: uStub.email
            username: uStub.username
            biography: uStub.biography
            displayName: uStub.displayName
            language: uStub.language
            password: password
          registerUser(agent1, userObj)
          done()

  describe "Sign Out Registered User", ->
    describe "JSON Requests", ->
      describe "GET", ->
        agent = request.agent()
        it "should start with signin", (done) ->
          userObj =
            email: global.fixtures.user[0].email
            password: global.fixtures.passport[0].password
          loginUser(agent, userObj)
          done()
        it "should sign the user out", (done) ->
          agent.get(appURL + "/auth/local/logout")
            .end (err, res) ->
              if err then done(err)
              res.status.should.eql 200
              res.redirects.should.eql [ appURL + "/login" ]
              done()
        it "should destroy the user session", (done) ->
          agent.get(appURL + "/plan")
            .end (err, res) ->
              should.exist(err)
              expect(res).to.have.property('error')
              res.status.should.eql 403
              res.text.should.include 'You are not permitted to perform this action.'
              done()

  describe "UnAuthenticated", ->
    describe "JSON Requests", ->
      describe "POST", ->
        agent2 = request.agent()
        it "/auth/local should login user", (done) ->
          userObj =
            email: global.fixtures.user[1].email
            password: global.fixtures.passport[1].password
          loginUser(agent2, userObj)
          done()
        it "/userplansetting/edit should allow access", (done) ->
            # do a seccond request to ensures how user is logged in
            agent2.get(appURL + "/userplansetting/edit")
              .end (err, res) ->
                should.not.exist(err)
                sails.log res
                res.status.should.eql 200
                done()

测试结果

+------------------------------------+
| Running mocha tests                |
+------------------------------------+
Debugger listening on port 5858
warn: Lifting sails...
debug: Loading models from /Users/robsawyer/Sites/specs/test/fixtures/models
  i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/en.json +0ms
  i18n:debug read /Users/robsawyer/Sites/specs/config/locales/en.json for locale: en +1ms
  i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/es.json +1ms
  i18n:debug read /Users/robsawyer/Sites/specs/config/locales/es.json for locale: es +0ms
  i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/fr.json +0ms
  i18n:debug read /Users/robsawyer/Sites/specs/config/locales/fr.json for locale: fr +0ms
  i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/de.json +1ms
  i18n:debug read /Users/robsawyer/Sites/specs/config/locales/de.json for locale: de +0ms
debug: --------------------------------------------------------
debug: :: Mon Jul 06 2015 10:34:11 GMT-0700 (PDT)
debug: Environment : test/bootstrap.test.*,test
debug: Port        : 1335
debug: --------------------------------------------------------
debug: --- Populated the database. ---
  Barrels
    constructor
      ✓ should load all the json files from default folder
      ✓ should set generate lowercase property names for models
    populate()
      populate(cb)
        ✓ should populate the DB with users

  Auth
    Register User
      JSON Requests
        POST
          ✓ /auth/local/register should register a user
    Sign Out Registered User
      JSON Requests
        GET
          ✓ should start with signin
          ✓ should sign the user out (57ms)
          ✓ should destroy the user session
    UnAuthenticated
      JSON Requests
        POST
          ✓ /auth/local should login user
debug: { jar:
   { setCookie: [Function: setCookie],
     getCookie: [Function: getCookie],
     getCookies: [Function: getCookies] } }
          1) /userplansetting/edit should allow access

  actions
    login
      ✓ should assume auth method if only one is required

  actions
    logout
      ✓ should trigger default logout if params.type is undefined

  UserModel
    to have
      ✓ attributes


warn: Lowering sails...

  11 passing (4s)
  1 failing

  1) Auth UnAuthenticated JSON Requests POST /userplansetting/edit should allow access:
     Uncaught AssertionError: expected [Error: Forbidden] to not exist

更新:注册模拟用户时似乎没有生成护照记录。因此,当我稍后尝试登录这些用户时,他们没有通过授权墙。

我下面的注册方法生成一个空的护照数组。

  ###
  # Handles registering a user based on the user id
  ###
  registerUser: (key, logout) ->
    if not logout then logout = true
    promise = new RSVP.Promise( (fulfill, reject) ->
      if not global.agent
        global.agent = request.agent(sails.hooks.http.app)
      uStub = userStub()
      password = global.fixtures.passport[key].password
      userObj =
        email: global.fixtures.user[key].email
        username: global.fixtures.user[key].username
        biography: uStub.biography
        displayName: global.fixtures.user[key].displayName
        language: uStub.language
        password: password
      global.agent
        .post("/auth/local/register")
        .send(userObj)
        .redirects(1)
        .end( (err, res) ->
          if err
            sails.log.error err
            reject(err)
          else
            global.agent.saveCookies(res)
            if logout
              User.findOne({email: userObj.email})
                .populate('passports')
                .exec(
                  (err, user) ->
                    if err then reject(err)
                    console.log user
                    sails.log.warn "Registered user " + user.id + " and now logging user out."
                    # Log the user out
                    authHelper.logoutUser()
                      .then(
                        (res) ->
                          fulfill(res)
                        , (err) ->
                          reject(err)
                      )
                )

            else
              fulfill(res)
        )
    )

生成:

[ { passports: [],
    username: 'test3',
    displayName: 'Test Three',
    email: 'test3@test.com',
    language: 'en-us',
    email_on_end_date: false,
    online: false,
    admin: false,
    createdAt: Tue Jul 07 2015 15:30:02 GMT-0700 (PDT),
    updatedAt: Tue Jul 07 2015 15:30:02 GMT-0700 (PDT),
    id: 471 } ]

什么时候应该生成:

{ passports: 
   [ { protocol: 'local',
       password: '$2a$10$SVjd6HPwS6k.68E2gAKpC.iS3ibsUZj.n7C3bMkcCRbBoyNJnz8Ru',
       accessToken: 'kHTFCeZ7Gd82G1xRSbl6Zm2+FLavt2IJy0qX9mdejD4HAOduzPz+UPa2ovYUfrWC',
       provider: null,
       identifier: null,
       tokens: null,
       user: 3,
       id: 2,
       createdAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT),
       updatedAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT) } ],
  planSetting: null,
  username: 'test3',
  email: 'test3@test.com',
  displayName: 'Test Three',
  biography: null,
  language: 'en-us',
  email_on_end_date: false,
  online: false,
  admin: false,
  id: 3,
  createdAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT),
  updatedAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT) }

最佳答案

当您执行需要您进行身份验证的请求时,您必须附加 cookie。

        it "/userplansetting/edit should allow access", (done) ->
            # do a seccond request to ensures how user is logged in
            var req = agent2.get(appURL + "/userplansetting/edit");

            # set the cookie
            agent2.attachCookies(req);

            req.end (err, res) ->
                should.not.exist(err)
                sails.log res
                res.status.should.eql 200
                done()

关于node.js - Sails JS Passport session 持久性问题 : Mocha Test Failing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31252275/

相关文章:

javascript - Express 中不清楚的错误处理

javascript - 图像未使用 Jade 渲染

javascript - 使用 knex.js 查询多个表

javascript - 建表时Sequelse错误的外键名

javascript - 如何根据数组中的值删除对象?

testing - 我怎样才能像用户一样思考?

安卓旋转处理

c# - 关于 Appium 的问题

node.js - 使用 multer 将文件保存在不同的文件夹中?

javascript - 请帮我获取哈希密码