2015-07-06 1 views
2

Я пытаюсь написать некоторые базовые тесты проверки подлинности с использованием Mocha, Chai и Superagent с SailsJS и Passport в качестве основы аутентификации. Ниже приведен мой тестовый сценарий, и по какой-то причине я не могу поддерживать постоянный сеанс, как мой последний тест, чтобы проверить, не имеет ли пользователь доступ к /userplansetting/edit. Примечание. Я подтвердил, что это работает при входе в систему через веб-интерфейс.S SessionJS Passport Session Persistance Issue: Mocha Test Failed

Update: Вот репо, который содержит подобный код и приводит результаты 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 

Update: Оказывается, что запись паспорта не генерируется, когда регистрируя насмешливых пользователей. Поэтому, когда я пытаюсь зарегистрировать этих пользователей позже, они не пропускают стену авторизации.

Мой регистрационный метод ниже создает пустой массив паспортов.

### 
    # 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: '[email protected]', 
    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: '[email protected]', 
    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) } 
+0

Следующий ответ был верным, но возникла еще одна проблема. Мне пришлось создать агент для каждого макетного пользователя (см. [AuthHelper.coffee] (https://github.com/robksawyer/sailsjs-starter-template/blob/master/test/helpers/authHelper.coffee)). Это был единственный способ получить паспорта для связи, когда пользователь был зарегистрирован. В итоге я написал отличный метод (см. [MockUtils.coffee] (https://github.com/robksawyer/sailsjs-starter-template/blob/master/test/helpers/mockUtils.coffee)), чтобы помочь в этом. –

+0

Вы можете увидеть полную реализацию на https://github.com/robksawyer/sailsjs-starter-template/blob/master/test –

ответ

1

Вы должны прикрепить куки, когда вы делаете запрос, который должен вам пройти проверку подлинности.

 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() 
+0

Я думал, что это была проблема и изначально, но при дальнейшей проверке. Кажется, что когда я регистрирую своих насмешливых пользователей, паспорт не создается (см. Пример выше в оригинальном вопросе). Я проверил команду register с помощью следующего, и паспорта отображаются как пустой массив. Однако, когда я регистрируюсь через интерфейс, паспорта ассоциируются правильно. –

 Смежные вопросы

  • Нет связанных вопросов^_^