Example #1
0
    it('should be able to generate unlock token', function(done) {
        var user = User.new({
            email: faker.internet.email(),
            username: faker.internet.userName(),
            password: faker.internet.password()
        });

        expect(user.generateUnlockToken).to.be.a('function');

        user
            .generateUnlockToken(function(error, lockable) {
                if (error) {
                    done(error)
                } else {
                    expect(lockable.unlockToken).to.not.be.null;
                    expect(lockable.unlockTokenExpiryAt).to.not.be.null;
                    done();
                }
            });
    });
Example #2
0
    it('should be able to lock account', function(done) {
        var User = mongoose.model('LUser');

        var user = new User({
            email: faker.internet.email(),
            password: faker.internet.password(),
            failedAttempts: 5
        });

        expect(user.lock).to.be.a('function');

        user
            .lock(function(error, lockable) {
                if (error) {
                    done(error);
                } else {
                    expect(lockable.lockedAt).to.not.be.null;
                    done();
                }
            });
    });
Example #3
0
 return Promise.all(range(1, 10).map(function(n) {
   var password = faker.internet.password();
   return db('users').insert({
     username      : faker.internet.userName(),
     email         : faker.internet.email(),
     full_name     : faker.name.firstName() + ' ' + faker.name.lastName(),
     password      : bcrypt.hashSync(password),
     plain_password: password,
     social_accounts:{ "facebook_id": uuid(),
                "twitter_id": uuid(),
               "googleplus_id" : uuid()
             },
     user_location : {"lat": 33.33, "lng": 77.61},
     details       : {
       age   :faker.helpers.randomNumber(19, 60),
       gender: n % 2 === 0 ? 'M' : 'F',
     },
     imported_data : faker.helpers.contextualCard(),
     picture: 'https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg'
   });
 }));
Example #4
0
function generateUserData(overrides = {}) {
  const baseUser = generateUserForClient(overrides)
  const password = baseUser.password || faker.internet.password()
  const otherOverrides = Object.assign({}, baseUser)
  delete otherOverrides.password

  const salt = crypto.randomBytes(16).toString('hex')
  const hash = crypto
    .pbkdf2Sync(password, salt, 10000, 512, 'sha512')
    .toString('hex')

  return Object.assign(
    {},
    baseUser,
    {
      _id: faker.random.uuid(),
      hash,
      salt,
    },
    otherOverrides,
  )
}
Example #5
0
    it('should be able to generate unlock token', function(done) {
        var User = mongoose.model('LUser');

        var user = new User({
            email: faker.internet.email(),
            password: faker.internet.password()
        });

        expect(user.generateUnlockToken).to.be.a('function');

        user
            .generateUnlockToken(function(error, lockable) {
                if (error) {
                    done(error);
                } else {
                    expect(lockable.unlockToken).to.not.be.null;
                    expect(lockable.unlockTokenExpiryAt).to.not.be.null;

                    done();
                }
            });
    });
Example #6
0
 process.nextTick(() => {
   e.emit('start');
   for (var i = 1; i <= num; i++) {
     const name = Faker.name.firstName();
     const email = Faker.internet.email();
     e.emit('running', name);
     let password = bcrypt.hashSync(Faker.internet.password(), 10);
     fakeUsers.push({
       name,
       email,
       password
     })
   }
   return (
     dt.Users()
       .insert(fakeUsers)
       .then(function(){
         e.emit('end', num);
         process.exit(0);
       })
   )
 });
Example #7
0
    it('should be able to set trackable details', function(done) {

        var trackable = User.new({
            email: email,
            username: faker.internet.userName(),
            password: faker.internet.password()
        });

        expect(trackable.track).to.exist;
        expect(trackable).to.respondTo('track');

        trackable
            .track(previousIp, function(error, trackable) {
                if (error) {
                    done(error);
                } else {
                    expect(trackable.currentSignInAt).to.not.be.null;
                    expect(trackable.currentSignInIpAddress).to.not.be.null;
                    expect(trackable.currentSignInIpAddress).to.equal(previousIp);
                    done();
                }
            });
    });
Example #8
0
User.remove({}, function(err) {
    var user = new User({
        username: 'lucas',
        password: 'espindola',
        email: 'espdlucas@gmail.com'
    });
    user.save(function(err, user) {
        if(err) return log.error(err);
        else log.info('New user - %s:%s',user.username,user.password);
    });

    for(var i=0; i<4; i++) {
        user = new User({
            username: faker.internet.userName(),
            password: faker.internet.password(),
            email: faker.internet.email()
        });
        user.save(function(err, user) {
            if(err) return log.error(err);
            else log.info('New user - %s:%s',user.username,user.password);
        });
    }
});
Example #9
0
module.exports.createNewFakeUsers = () => {
    var username = faker.internet.userName();
    var photo_album = path.join(process.cwd(),'profiles', username);
    var password = faker.internet.password();

    var salt = bcrypt.genSaltSync(10);
    var hash_pass = bcrypt.hashSync(password, salt);

    var firstname = faker.name.firstName();
    var lastname =  faker.name.lastName();

    var email = faker.internet.email();
    var gender = faker.random.boolean();
    var time_created = faker.date.recent();

    var last_login = faker.date.recent();
    var age = faker.random.number();
    var new_user = new User({username: username,email:email,password,hash_pass,
        name: {firstname:firstname,lastname:lastname},timeCreated:time_created, photoAlbum:photo_album,
    gender:gender,lastLogin:last_login,age:age});

    return new Promise((resolve, reject)=> {
        new_user.save((err, res) => {
            if(err){
                console.error(err);
                reject(err)
            }
            else
            {
                console.log(res);
                resolve(res);
            }
        });
    });


}
Example #10
0
 test.it('8.1 should add/publish api backend as a new user', function() {
     CommonUtils.signUp(driver);
     var userName = faker.internet.userName();
     while (userName.indexOf('.') > -1 || userName.indexOf('_') > -1) {
         userName = faker.internet.userName();
     }
     var email = faker.internet.email();
     newUser.added = true;
     newUser.email = email;
     CommonUtils.fillSignUpForm(driver, userName, email, faker.internet.password());
     CommonUtils.goToDashboard(driver);
     AddAPIBackendUtil.addNewBackend(driver, {
         backendName: 'NewBackend',
         description: 'Test Description',
         hostName: 'google.com',
         portNumber: '80',
         frontendPrefix: '/test',
         backendPrefix: '/test'
     });
     var publishedAPIHostElement = driver.findElement(By.xpath('//*[@class="page-title"]'));
     publishedAPIHostElement.getText().then(function(text){
         assert.equal(text, 'NewBackend');
     });
 });
  test('change password', async () => {
    const authCookies = await getAuthCookies(server, user, userPassword);
    const newPassword = faker.internet.password();
    await request.agent(server)
      .patch('/users/profile/password')
      .set('Cookie', authCookies)
      .send({
        form: {
          password: userPassword,
          newPassword,
          confirmPassword: newPassword,
        },
      });

    const responseWithOldPassword = await request.agent(server)
      .get('/users/profile');
    expect(responseWithOldPassword).toHaveHTTPStatus(302);

    const newAuthCookies = await getAuthCookies(server, user, newPassword);
    const responseWithNewPassword = await request.agent(server)
      .get('/users/profile')
      .set('Cookie', newAuthCookies);
    expect(responseWithNewPassword).toHaveHTTPStatus(200);
  });
  it('should persist data', function(done) {
    const name = faker.name.findName()
    const password = faker.internet.password()

    request(sails.hooks.http.app)
      .post('/api/register/post')
      .send({
        name,
        password
      })
      .expect(200)
      .then(() => {

        User
          .find({
            name
          })
          .then(user => {
            chai.assert.isDefined(user)
            done()
          })
          .catch(error => done(error))
      })
  })
Example #13
0
  describe('DOCUMENT API END POINT', function() {

    var nameObj = {
      username: faker.internet.userName(),
      password: faker.internet.password(),
      firstname: faker.name.firstName(),
      lastname: faker.name.lastName(),
      email: faker.internet.email()
    };
    var documentObj = {
      doc1: {
        title: faker.lorem.sentence(),
        content: faker.lorem.sentences(),
        access: '2'
      },
      doc2: {
        title: faker.lorem.sentence(),
        content: faker.lorem.sentences()
      },
      doc3: {
        title: faker.lorem.sentence(),
        content: faker.lorem.sentences(),
        access: '1, 2'
      }
    };

    it('verifies that GET: document need authentication', function(done) {

      server
        .get('/api/documents/')
        .expect('Content-type', /json/)
        .end(function(err, res) {
          res.status.should.equal(403);
          res.body.success.should.equal(false);
          done();
        });
    });

    it('create and authenticated user', function(done) {

      server
        .post('/api/users/')
        .send(nameObj)
        .expect('Content-type', /json/)
        .end(function(err, res) {
          res.status.should.equal(200);
          res.body.success.should.equal(true);
          server
            .post('/api/users/login')
            .send({ username: nameObj.username, password: nameObj.password })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(200);
              token = res.body.result.token;
              res.body.result.token.should.be.type('string');
              res.body.result.userData.should.be.type('object');
              done();
            });
        });
    });

    it('Verify that document resources are avaliable after authentication',
      function(done) {

        server
          .get('/api/documents/')
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(200);
            res.body.doc.should.be.type('object');
            done();
          });
      });

    it('Verifies that user should be able to create document with only title',
      function(done) {

        server
          .post('/api/documents/')
          .send({ title: faker.lorem.sentence() })
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(200);
            res.body.newDoc.should.be.type('object');
            done();
          });
      });

    it('Verifies that a document is created with title and content',
      function(done) {
        server
          .post('/api/documents/')
          .send(documentObj.doc2)
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(200);
            res.body.newDoc.should.be.type('object');
            done();
          });
      });

    it('Create sample roles for test',
      function(done) {

        server
          .post('/api/role/')
          .send({ role: faker.lorem.word() })
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(200);
            res.body.success.should.equal(true);
            res.body.message.should.be.type('string');
            done();
          });
      });

    it('Create second role for document test', function(done) {

      server
        .post('/api/role/')
        .send({ role: faker.lorem.word() })
        .set({ token: token })
        .expect('Content-type', /json/)
        .end(function(err, res) {
          res.status.should.equal(200);
          res.body.success.should.equal(true);
          res.body.message.should.be.type('string');
          done();
        });
    });

    it('Verify that documment can have multiple role',
      function(done) {

        documentObj.doc3.title = faker.lorem.sentence();

        server
          .post('/api/documents/')
          .send(documentObj.doc3)
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(200);
            res.body.newDoc.should.be.type('object');
            done();
          });
      });

    it('Verify that documment title is unquie',
      function(done) {

        server
          .post('/api/documents/')
          .send(documentObj.doc3)
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(401);
            res.body.success.should.equal(false);
            done();
          });
      });

    it('Verify that documment cannot have role that doesnt exist',
      function(done) {

        var doc = {
          title: faker.lorem.sentence(),
          content: faker.lorem.sentences(),
          access: '0'
        };

        server
          .post('/api/documents/')
          .send(doc)
          .set({ token: token })
          .expect('Content-type', /json/)
          .end(function(err, res) {
            res.status.should.equal(400);
            res.body.success.should.equal(false);
            res.body.message.should.equal('One or more roles does not exist');
            done();
          });
      });

    describe('Ensure that user cannot edit document not assigned to them',
      function() {

        it('It create a document with a specific role',
          function(done) {

            server
              .post('/api/documents/')
              .send(documentObj.doc1)
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(200);
                res.body.newDoc.should.be.type('object');
                done();
              });
          });

        it('Ensure the document is created',
          function(done) {

            server
              .get('/api/documents/')
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                var docs = res.body.doc;
                docId = docs[0];
                res.status.should.equal(200);
                res.body.doc.length.should.be.above(0);
                done();
              });
          });


        it('Ensure that document cannot be updated with an invalid role',
          function(done) {

            server
              .put('/api/documents/' + docId._id)
              .send({ access: '0' })
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(400);
                done();
              });
          });

        describe('Create a new user and a token', function() {

          var newUser = {
            firstname: faker.name.firstName(),
            lastname: faker.name.lastName(),
            username: faker.internet.userName(),
            password: faker.internet.password(),
            email: faker.internet.email()
          };

          it('Create a new user',
            function(done) {

              server
                .post('/api/users/')
                .send(newUser)
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.success.should.equal(true);
                  done();
                });
            });

          it('Login and create a new token and ensure that POST:login ' +
            ' only that needed data from the posted object',
            function(done) {

              server
                .post('/api/users/login')
                .send(newUser)
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  token2 = res.body.result.token;
                  res.body.result.token.should.be.type('string');
                  done();
                });
            });

          it('Ensure a user does not view a document not assigned to them',
            function(done) {

              server
                .get('/api/documents/' + docId._id)
                .expect('Content-type', /json/)
                .set({ token: token2 })
                .end(function(err, res) {
                  res.status.should.equal(403);
                  res.body.message.should.equal('Access denied!');
                  done();
                });
            });

          it('Verify if a user cannot delete a document not assigned to them',
            function(done) {

              server
                .delete('/api/documents/' + docId._id)
                .expect('Content-type', /json/)
                .set({ token: token2 })
                .end(function(err, res) {
                  res.status.should.equal(401);
                  res.body.success.should.equal(false);
                  res.body.message.should.equal('FORBIDDEN');
                  done();
                });
            });

        });

      });
  });
Example #14
0
      createPost = async ({
        includeUser = true,
        includeTags = true,
        includeImage = true,
        includeComments = true
      } = {}) => {
        let include = [];

        const post = await Post.create({
          body: faker.lorem.paragraphs(),
          title: faker.lorem.sentence(),
          isPublic: faker.random.boolean()
        });

        const postId = post.getPrimaryKey();

        if (includeUser) {
          const user = await User.create({
            name: `${faker.name.firstName()} ${faker.name.lastName()}`,
            email: faker.internet.email(),
            password: faker.internet.password(8)
          });

          instances.add(user);
          include = [...include, 'user'];

          Reflect.set(post, 'user', user);
        }

        if (includeImage) {
          const image = await Image.create({
            postId,
            url: faker.image.imageUrl()
          });

          instances.add(image);
          include = [...include, 'image'];
        }

        if (includeTags) {
          const tags = await Promise.all([
            Tag.create({
              name: faker.lorem.word()
            }),
            Tag.create({
              name: faker.lorem.word()
            }),
            Tag.create({
              name: faker.lorem.word()
            })
          ]);

          const categorizations = await Promise.all(
            tags.map(tag => {
              return Categorization.create({
                postId,
                tagId: tag.getPrimaryKey()
              });
            })
          );

          tags.forEach(tag => {
            instances.add(tag);
          });

          categorizations.forEach(categorization => {
            instances.add(categorization);
          });

          include = [...include, 'tags'];
        }

        if (includeComments) {
          const comments = await Promise.all([
            Comment.create({
              postId,
              message: faker.lorem.sentence()
            }),
            Comment.create({
              postId,
              message: faker.lorem.sentence()
            }),
            Comment.create({
              postId,
              message: faker.lorem.sentence()
            })
          ]);

          comments.forEach(comment => {
            instances.add(comment);
          });

          include = [...include, 'comments'];
        }

        await post.save(true);

        return await Post
          .find(postId)
          .include(...include);
      };
describe('Edit user', () => {
  let server;
  const user = makeUser();
  const userPassword = faker.internet.password();

  const hackerUser = makeUser();
  const hackerUserPassword = faker.internet.password();

  beforeEach(async () => {
    server = app().listen();
    await signUpUser(server, user, userPassword);
    await signUpUser(server, hackerUser, hackerUserPassword);
  });

  test('edit user while not signed in', async () => {
    const response = await request.agent(server)
      .get('/users/profile');
    expect(response).toHaveHTTPStatus(302);
  });

  test('edit self', async () => {
    const authCookies = await getAuthCookies(server, user, userPassword);
    const signedInUser = await getUserBy({ email: user.email });
    const newUserData = makeUser();

    await request.agent(server)
      .patch('/users/profile')
      .set('Cookie', authCookies)
      .send({
        form: {
          ...newUserData,
        },
      });
    const changedUser = await getUserBy({ id: signedInUser.id });
    expect(changedUser).toMatchObject(newUserData);
  });

  test('change password', async () => {
    const authCookies = await getAuthCookies(server, user, userPassword);
    const newPassword = faker.internet.password();
    await request.agent(server)
      .patch('/users/profile/password')
      .set('Cookie', authCookies)
      .send({
        form: {
          password: userPassword,
          newPassword,
          confirmPassword: newPassword,
        },
      });

    const responseWithOldPassword = await request.agent(server)
      .get('/users/profile');
    expect(responseWithOldPassword).toHaveHTTPStatus(302);

    const newAuthCookies = await getAuthCookies(server, user, newPassword);
    const responseWithNewPassword = await request.agent(server)
      .get('/users/profile')
      .set('Cookie', newAuthCookies);
    expect(responseWithNewPassword).toHaveHTTPStatus(200);
  });

  test('delete user', async () => {
    const usersCount = 2;
    const usersListAtStart = await User.findAll();
    expect(usersListAtStart).toHaveLength(usersCount);

    const notSignedInResponse = await request.agent(server)
      .delete('/users');
    expect(notSignedInResponse).toHaveHTTPStatus(302);

    const authCookies = await getAuthCookies(server, hackerUser, hackerUserPassword);
    await request.agent(server)
      .delete('/users')
      .set('Cookie', authCookies);
    const usersListAfterDeletion = await User.findAll();
    expect(usersListAfterDeletion).toHaveLength(usersCount - 1);
  });

  afterEach((done) => {
    server.close();
    done();
  });
});
Example #16
0
describe('msgtree routes', function()  {
  const _ = require('lodash');
  const request = require('supertest');
  const faker = require('faker');
  const app = require('../../app').app;

  it('HTTP GET /ping - ping REST API', function(done) {
    request(app)
      .get('/ping')
      .send()
      .expect('Content-Type', 'text/plain; charset=utf-8')
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.text).toBe('pong!');
        done();
      });
  });

  const accountData = {
    username: faker.internet.userName(),
    password: faker.internet.password()
  };

  it('HTTP POST /register - successful register a new user account', function(done) {
    request(app)
      .post('/register')
      .send(accountData)
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body).toEqual({ user: accountData.username });
        done();
      });
  });

  it('HTTP POST /register - failed register a new user account', function(done) {
    request(app)
      .post('/register')
      .send(accountData)
      .expect('Content-Type', /json/)
      .expect(500)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body.error.name).toEqual('UserExistsError');
        done();
      });
  });

  const wrongAccount = {
    username: faker.internet.userName(),
    password: faker.internet.password()
  };

  it('HTTP POST /login - failed login with the unknown username and password', function(done) {
    request(app)
      .post('/login')
      .send(wrongAccount)
      .expect('Content-Type', /json/)
      .expect(401)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body.error.name).toEqual('IncorrectUsernameError');
        done();
      });
  });

  let cookie;
  it('HTTP POST /login - successful login with the username and password', function(done) {
    request(app)
      .post('/login')
      .send(accountData)
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        cookie = res.headers['set-cookie'];

        expect(res.body).toEqual({ username: accountData.username });
        done();
      });
  });

  const commentData = {
    text: faker.lorem.paragraph()
  };
  it('HTTP POST /createComment - create a new comment', function(done) {
    request(app)
      .post('/createComment')
      .set('cookie', cookie)
      .send(commentData)
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body.text).toEqual(commentData.text);
        done();
      });
  });

  it('HTTP GET /getComments - gets all comments', function(done) {
    request(app)
      .get('/getComments')
      .send()
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body.length).toBeGreaterThan(1);
        done();
      });
  });

  it('HTTP GET /getMaxDepth - gets a comment with the max depth', function(done) {
    request(app)
      .get('/getMaxDepth')
      .send()
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        expect(res.body).hasFields(['_id', 'text', 'postedAt', 'postedBy', 'depth']);
        done();
      });
  });

  it('HTTP GET /getAccountsStatistic - get all accounts with comments count', function(done) {
    request(app)
      .get('/getAccountsStatistic')
      .send()
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) throw err;

        const accounts = res.body;

        // check schema
        accounts.forEach(account => {
          expect(account).hasFields(['username', 'count']);
        });

        // check sorting
        const sorted = _.reverse(_.sortBy(accounts, 'count'));
        expect(accounts.map(a => a.count)).toEqual(sorted.map(a => a.count)); // ignore 'username' field

        done();
      });
  });
});
Example #17
0
test.beforeEach(t => {
  t.context.login = internet.userName()
  t.context.email = internet.email()
  t.context.password = internet.password()
})
Example #18
0
describe('[USER]'.bold.green, function() {
  var userData = {
    firstName: faker.name.firstName(),
    lastName: faker.name.lastName(),
    username: faker.internet.userName(),
    email: faker.internet.email(),
    password: faker.internet.password()
  };

  describe('Model'.green, function() {
    before(function(done) {
      UserModel.collection.drop();
      done();
    });

    describe('#new()'.cyan,function() {
      it('should succesfully create a new user', function(done) {
        var sampleUser = new UserModel(userData);
        sampleUser.setPassword(userData.password);
        sampleUser.save(function(err, saved) {
          expect(saved).to.be.an.instanceof(UserModel);
          expect(saved).to.have.property('firstName', userData.firstName);
          expect(saved).to.have.property('lastName', userData.lastName);
          expect(saved).to.have.property('username', userData.username);
          expect(saved).to.have.property('email', userData.email);
          expect(saved).to.not.have.property('password');
          expect(saved.fullName()).to.eql(saved.firstName + " " + saved.lastName);
          UserModel.collection.drop();
          done();
        })
      });
    });
  });

  describe('Authentication'.green, function() {
    before(function(done) {
      UserModel.collection.drop();
      done();
    });

    describe('#register()'.cyan, function() {
      it('allows new users to register', function(done) {
        request(app)
          .post('/auth/register')
          .send(userData)
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function(err, res) {
            expect(res.body).to.be.an('object');
            expect(res.body).to.have.property('token');
            done();
          });
      });
    });

    describe('#login()'.cyan, function() {
      it('allows existing users to log in', function(done) {
        request(app)
          .post('/auth/login')
          .send(userData)
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function(err, res) {
            expect(res.body).to.be.an('object');
            expect(res.body).to.have.property('token');
            done();
          });
      });
    });
  });
});
Example #19
0
  describe('DOCUMENTS API ENDPOINT:', () => {
    var jwtToken,
      userID,
      docID,
      fakeUser = {
        username: faker.internet.userName(),
        email: faker.internet.email(),
        name: {
          first: faker.name.firstName(),
          last: faker.name.lastName()
        },
        password: faker.internet.password(),
        role: 'viewer'
      },
      newDocument = {
        title: faker.lorem.sentence(),
        content: 'Some content'
      };

    before(done => {
      api
        .post('/api/v1/users')
        .send(fakeUser)
        .end((err, res) => {
          assert.equal(res.status, 201);
          jwtToken = res.body.token;
          userID = res.body.user._id;
          done();
        });
    });

    var description = 'POST: should return documents with ' + 
      'defined published dates';
    it(description, done => {
      assert.isOk(jwtToken);
      api
        .post(apiUrl)
        .set('X-ACCESS-TOKEN', jwtToken)
        .send(newDocument)
        .end((err, res) => {
          assert.equal(res.status, 201);
          assert(res.body.createdAt);
          docID = res.body._id;
          done();
        });
    });

    it('POST: only authenticated users can create documents', done => {
      api
        .post(apiUrl)
        .send(newDocument)
        .end((err, res) => {
          assert.equal(res.status, 401);
          done();
        });
    });

    it('GET: should return documents with paginated limits', done => {
      var count = 10;
      api
        .get(apiUrl + '?limit=' + count)
        .end((err, res) => {
          assert.equal(res.status, 200);
          assert.isArray(res.body.data);
          assert.isAtMost(res.body.data.length, count);
          done();
        });
    });

    it('GET: should return documents within paginated limits', done => {
      var count = 10,
        offset = 10;

      api
        .get(apiUrl + '?limit=' + count + '&after=' + offset)
        .end((err, res) => {
          assert.equal(res.status, 200);
          assert.isArray(res.body.data);
          assert.isAtMost(res.body.data.length, count);
          done();
        });
    });

    var description1 = 'GET: should return documents in ' +
      'descending order of published date';
    it(description1, done => {
      api
        .get(apiUrl)
        .end((err, res) => {
          var documents = res.body.data,
            prevSortedDate = documents[0].createdAt,
            sorted  = true;

          assert.equal(res.status, 200);

          for (var i in documents) {
            if (i.createdAt < prevSortedDate) {
              sorted = false;
            }
          }

          done();
        });
    });

    it('PUT: should be able to edit a document', done => {
      var newContent = faker.lorem.sentence();

      api
        .put(apiUrl + '/' + docID)
        .set('X-ACCESS-TOKEN', jwtToken)
        .send({content: newContent})
        .end((err, res) => {
          assert.equal(res.status, 200);
          api
            .get(apiUrl + '/' + docID)
            .end((err, res) => {
              assert.equal(res.status, 200);
              assert(res.body.content === newContent);
            });
          done();
        });
    });

    var description2 = 'GET: should return documents created ' +
      'by a particular user';
    it(description2, done => {

      api
        .get('/api/v1/users/' + 
          userID + '/documents')
        .set('X-ACCESS-TOKEN', jwtToken)
        .end((err, res) => {
          assert.equal(res.status, 200);
          assert.isAtLeast(res.body.data.length, 1);

          res.body.data.forEach((docs) => {
            assert(docs.ownerId === userID);
          });

          done();
        });
    });

    var description3 = 'GET: should not return documents with higher ' +
      'role access';
    it(description3, done => {
      newDocument.title = faker.lorem.sentence();
      newDocument.role = 'admin';

      api
        .post(apiUrl)
        .set('X-ACCESS-TOKEN', jwtToken)
        .send(newDocument)
        .end((err, res) => {
          var viewerDocId = res.body._id;
          assert.equal(res.status, 201);

          // It should return 401
          api
            .get(apiUrl + '/' + viewerDocId)
            .end((err, res) => {
              assert.equal(res.status, 401);
              assert.equal(res.body.status, 'You cant touch that');
              
              // Now it should return 200
              api
                .get(apiUrl + '/' + viewerDocId)
                .set('X-ACCESS-TOKEN', jwtToken)
                .end((err, res) => {
                  assert.equal(res.status, 200);
                  done();
                });
            });


        });
    });

    it('POST: un-authenticated users cant delete documents', done => {
      api
        .delete(apiUrl + '/' + docID)
        .send(newDocument)
        .end((err, res) => {
          assert.equal(res.status, 401);
          assert.equal(res.body.status, 'Unauthorized');

          done();
        });
    });

    it('POST: only authenticated users can delete documents', done => {
      api
        .delete(apiUrl + '/' + docID)
        .set('X-ACCESS-TOKEN', jwtToken)
        .send(newDocument)
        .end((err, res) => {
          assert.equal(res.status, 200);
          assert.equal(res.body.status, 'Successfuly deleted');

          done();
        });
    });
  });
app.get('/api/fake', function(req, res) {
	res.json({
		"address": {
			zipCode: faker.address.zipCode(),
			city: faker.address.city(),
			cityPrefix: faker.address.cityPrefix(),
			citySuffix: faker.address.citySuffix(),
			streetName: faker.address.streetName(),
			streetAddress: faker.address.streetAddress(),
			streetSuffix: faker.address.streetSuffix(),
			streetPrefix: faker.address.streetPrefix(),
			secondaryAddress: faker.address.secondaryAddress(),
			county: faker.address.county(),
			country: faker.address.country(),
			countryCode: faker.address.countryCode(),
			state: faker.address.state(),
			stateAbbr: faker.address.stateAbbr(),
			latitude: faker.address.latitude(),
			longitude: faker.address.longitude()
		},
		"commerce": {
			color: faker.commerce.color(),
			department: faker.commerce.department(),
			productName: faker.commerce.productName(),
			price: faker.commerce.price(),
			productAdjective: faker.commerce.productAdjective(),
			productMaterial: faker.commerce.productMaterial(),
			product: faker.commerce.product()
		},
		"company": {
			suffixes: faker.company.suffixes(),
			companyName: faker.company.companyName(),
			companySuffix: faker.company.companySuffix(),
			catchPhrase: faker.company.catchPhrase(),
			bs: faker.company.bs(),
			catchPhraseAdjective: faker.company.catchPhraseAdjective(),
			catchPhraseDescriptor: faker.company.catchPhraseDescriptor(),
			catchPhraseNoun: faker.company.catchPhraseNoun(),
			bsAdjective: faker.company.bsAdjective(),
			bsBuzz: faker.company.bsBuzz(),
			bsNoun: faker.company.bsNoun()
		},
		"date": {
			past: faker.date.past(),
			future: faker.date.future(),
			between: faker.date.between(),
			recent: faker.date.recent(),
			month: faker.date.month(),
			weekday: faker.date.weekday()
		},
		"finance": {
			account: faker.finance.account(),
			accountName: faker.finance.accountName(),
			mask: faker.finance.mask(),
			amount: faker.finance.amount(),
			transactionType: faker.finance.transactionType(),
			currencyCode: faker.finance.currencyCode(),
			currencyName: faker.finance.currencyName(),
			currencySymbol: faker.finance.currencySymbol(),
			bitcoinAddress: faker.finance.bitcoinAddress()
		},
		"hacker": {
			abbreviation: faker.hacker.abbreviation(),
			adjective: faker.hacker.adjective(),
			noun: faker.hacker.noun(),
			verb: faker.hacker.verb(),
			ingverb: faker.hacker.ingverb(),
			phrase: faker.hacker.phrase()
		},
		"helpers": {
			randomize: faker.helpers.randomize(),
			slugify: faker.helpers.slugify(),
			replaceSymbolWithNumber: faker.helpers.replaceSymbolWithNumber(),
			replaceSymbols: faker.helpers.replaceSymbols(),
			shuffle: faker.helpers.shuffle(),
			mustache: faker.helpers.mustache(),
			createCard: faker.helpers.createCard(),
			contextualCard: faker.helpers.contextualCard(),
			userCard: faker.helpers.userCard(),
			createTransaction: faker.helpers.createTransaction()
		},
		"image": {
			image: faker.image.image(),
			avatar: faker.image.avatar(),
			imageUrl: faker.image.imageUrl(),
			abstract: faker.image.abstract(),
			animals: faker.image.animals(),
			business: faker.image.business(),
			cats: faker.image.cats(),
			city: faker.image.city(),
			food: faker.image.food(),
			nightlife: faker.image.nightlife(),
			fashion: faker.image.fashion(),
			people: faker.image.people(),
			nature: faker.image.nature(),
			sports: faker.image.sports(),
			technics: faker.image.technics(),
			transport: faker.image.transport()
		},
		"internet": {
			avatar: faker.internet.avatar(),
			email: faker.internet.email(),
			exampleEmail: faker.internet.exampleEmail(),
			userName: faker.internet.userName(),
			protocol: faker.internet.protocol(),
			url: faker.internet.url(),
			domainName: faker.internet.domainName(),
			domainSuffix: faker.internet.domainSuffix(),
			domainWord: faker.internet.domainWord(),
			ip: faker.internet.ip(),
			userAgent: faker.internet.userAgent(),
			color: faker.internet.color(),
			mac: faker.internet.mac(),
			password: faker.internet.password()
		},
		"lorem": {
			word: faker.lorem.word(),
			words: faker.lorem.words(),
			sentence: faker.lorem.sentence(),
			sentences: faker.lorem.sentences(),
			paragraph: faker.lorem.paragraph(),
			paragraphs: faker.lorem.paragraphs(),
			text: faker.lorem.text(),
			lines: faker.lorem.lines()
		},
		"name": {
			firstName: faker.name.firstName(),
			lastName: faker.name.lastName(),
			findName: faker.name.findName(),
			jobTitle: faker.name.jobTitle(),
			prefix: faker.name.prefix(),
			suffix: faker.name.suffix(),
			title: faker.name.title(),
			jobDescriptor: faker.name.jobDescriptor(),
			jobArea: faker.name.jobArea(),
			jobType: faker.name.jobType()
		},
		"phone": {
			phoneNumber: faker.phone.phoneNumber(),
			phoneNumberFormat: faker.phone.phoneNumberFormat(),
			phoneFormats: faker.phone.phoneFormats()
		},
		"random": {
			number: faker.random.number(),
			arrayElement: faker.random.arrayElement(),
			objectElement: faker.random.objectElement(),
			uuid: faker.random.uuid(),
			boolean: faker.random.boolean(),
			word: faker.random.word(),
			words: faker.random.words(),
			image: faker.random.image(),
			locale: faker.random.locale(),
			alphaNumeric: faker.random.alphaNumeric()
		},
		"system": {
			fileName: faker.system.fileName(),
			commonFileName: faker.system.commonFileName(),
			mimeType: faker.system.mimeType(),
			commonFileType: faker.system.commonFileType(),
			commonFileExt: faker.system.commonFileExt(),
			fileType: faker.system.fileType(),
			fileExt: faker.system.fileExt(),
			directoryPath: faker.system.directoryPath(),
			filePath: faker.system.filePath(),
			semver: faker.system.semver()
		}
	})
});
Example #21
0
  describe('User Operations', function() {

    var nameObj = {
      username: faker.internet.userName(),
      password: faker.internet.password(),
      firstname: faker.name.firstName(),
      lastname: faker.name.lastName(),
      email: faker.internet.email(),
    };

    describe('A user is created when firstname and lastname is sent',
      function() {

        it('Verifies that a new user is created', function(done) {

          server
            .post('/api/users/')
            .send(nameObj)
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(200);
              res.body.success.should.equal(true);
              done();
            });
        });

        it('Rejects a user without firstname and lastname',
          function(done) {

            server
              .post('/api/users/')
              .send({ username: nameObj.username, password: nameObj.password })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(400);
                res.body.success.should.equal(false);
                done();
              });
          });

        it('Rejects a user without invalid data',
          function(done) {

            server
              .post('/api/users/')
              .send({ username: nameObj.username, password: nameObj.password })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(400);
                res.body.success.should.equal(false);
                done();
              });
          });

        it('Rejects a user with invalid data',
          function(done) {

            var invalidUserData = {
              firstname: '&^*&^^&&^&',
              lastname: '*&^*()*&(',
              username: '___kdlkdnknkdn',
              password: 'gusgysygsy'
            };

            server
              .post('/api/users/')
              .send(invalidUserData)
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(400);
                res.body.success.should.equal(false);
                done();
              });
          });

      });

    describe('Authenticate user before user can EDIT, DELETE and ' +
      'VIEW user resources',
      function() {

        it('Authenticate user to get all user data ', function(done) {

          server
            .get('/api/users/')
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(403);
              res.body.message.should.equal('Access denied.');
              res.body.success.should.equal(false);
              done();
            });
        });

        it('Authenticate user to get a user data ', function(done) {

          server
            .get('/api/users/1')
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(403);
              res.body.message.should.equal('Access denied.');
              res.body.success.should.equal(false);
              done();
            });
        });

        it('Authenticate user to edit a user data ', function(done) {

          server
            .put('/api/users/1')
            .send({ firstname: nameObj.firstname })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(403);
              res.body.message.should.equal('Access denied.');
              res.body.success.should.equal(false);
              done();
            });
        });

        it('Authenticate user to delete user data ', function(done) {

          server
            .delete('/api/users/1')
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(403);
              res.body.message.should.equal('Access denied.');
              res.body.success.should.equal(false);
              done();
            });
        });
      });

    describe('Should return data when user has a valid token', function() {

      var error = 'Oops!!! Invalid Username/Password';

      it('POST: login should reject user with invalid user data',
        function(done) {

          server
            .post('/api/users/login')
            .send({ username: 'Stephen', password: 'stephen' })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(400);
              res.body.message.should.equal(error);
              res.body.success.should.equal(false);
              done();
            });
        });

      it('POST: login should Reject user with incorrect password',
        function(done) {

          server
            .post('/api/users/login')
            .send({ username: nameObj.username, password: 'stephen' })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(400);
              res.body.message.should.equal(error);
              res.body.success.should.equal(false);
              done();
            });
        });

      it('POST: login should send a token to users when' +
        ' a valid username and password is sent',
        function(done) {

          server
            .post('/api/users/login')
            .send({ username: nameObj.username, password: nameObj.password })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(200);
              res.body.token.should.be.type('string');
              token = res.body.token;
              done();
            });
        });

      it('GET: users should reject users with invalid token',
        function(done) {

          server
            .get('/api/users/')
            .set({ token: 'jknknknknkvnxk' + token })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(403);
              res.body.message.should.equal('Invalid token');
              res.body.success.should.equal(false);
              done();
            });
        });

      it('GET: users should get all user when given a valid token',
        function(done) {

          server
            .get('/api/users/')
            .set({ token: token })
            .expect('Content-type', /json/)
            .end(function(err, res) {
              res.status.should.equal(200);
              res.body.user.should.be.an.Array;
              res.body.user.length.should.be.above(0);
              done();
            });
        });

      describe('GET user/:id should get a user data when valid token is sent',
        function() {

          it('GET user/:username should get a user data when valid' +
            ' token is sent',
            function(done) {

              server
                .get('/api/users/' + nameObj.username)
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  userId = res.body.user._id;
                  res.body.user.should.be.json;
                  res.body.user.should.have.property('name');
                  done();
                });
            });

          it('GET user/:id should get a user data when valid' +
            ' token is sent',
            function(done) {

              server
                .get('/api/users/' + userId)
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.user.should.be.json;
                  res.body.user.should.have.property('name');
                  done();
                });
            });

          it('GET user/:id should reject invalid username/id',
            function(done) {

              server
                .get('/api/users/)khnk(')
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(400);
                  res.body.message.should.equal('Invalid username/id');
                  done();
                });
            });
        });

      describe('PUT user/:id should edit a user data when valid token is sent',
        function() {

          it('PUT user/:id should edit a user data when valid token is sent',
            function(done) {

              var newName = faker.name.firstName();

              server
                .put('/api/users/' + userId)
                .send({ username: newName })
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.user.should.be.json;
                  res.body.user.should.have.property('username', newName);
                  done();
                });
            });

          it('GET role for test',
            function(done) {

              var newName = faker.name.firstName();

              server
                .get('/api/role/')
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  roleData = res.body.roles[2];
                  res.body.roles.should.be.type('object');
                  done();
                });
            });

          it('PUT user/:id should edit a user data when valid token is sent',
            function(done) {

              var newName = faker.name.firstName();

              server
                .put('/api/users/' + userId)
                .send({ role: roleData.role })
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.user.should.be.type('object');
                  res.body.user.should.have.property('role',
                    roleData._id.toString());
                  done();
                });
            });

          it('Ensure that user can edit password',
            function(done) {

              var newName = faker.name.firstName();

              server
                .put('/api/users/' + userId)
                .send({ password: 'roleData.role' })
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.user.should.be.type('object');
                  res.body.user.should.have.property('role',
                    roleData._id.toString());
                  done();
                });
            });

          it('Ensure user can update name',
            function(done) {

              var newName = faker.name.firstName();

              server
                .put('/api/users/' + userId)
                .send({ firstname: 'steve', lastname: 'Oduntan' })
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.user.should.have.property('password');
                  res.body.user.should.be.type('object');
                  done();
                });
            });

          it('PUT user/:id should not allow invalid role update',
            function(done) {

              var newName = faker.name.firstName();

              server
                .put('/api/users/' + userId)
                .send({ role: 'steve' })
                .set({ token: token })
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(400);
                  res.body.success.should.equal(false);
                  res.body.message.should.equal('Invalid User role');
                  done();
                });
            });
        });

      describe('DELETE users/id should delete user', function() {

        it('DELETE should should only work with user id',
          function(done) {

            server
              .delete('/api/users/' + nameObj.username)
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(400);
                res.body.message.should.equal('Invalid user id');
                done();
              });
          });

        it('DELETE user/:id should delete a user data',
          function(done) {

            var newName = faker.name.firstName();

            server
              .delete('/api/users/' + userId)
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(200);
                res.body.user.should.equal('removed');
                done();
              });
          });

        it('user/:id should should be deleted',
          function(done) {

            var newName = faker.name.firstName();

            server
              .get('/api/users/' + userId)
              .set({ token: token })
              .expect('Content-type', /json/)
              .end(function(err, res) {
                res.status.should.equal(403);
                res.body.success.should.equal(false);
                res.body.message.should.equal('Invalid token');
                done();
              });
          });
      });
    });
  });
Example #22
0
        describe('Create a new user and a token', function() {

          var newUser = {
            firstname: faker.name.firstName(),
            lastname: faker.name.lastName(),
            username: faker.internet.userName(),
            password: faker.internet.password(),
            email: faker.internet.email()
          };

          it('Create a new user',
            function(done) {

              server
                .post('/api/users/')
                .send(newUser)
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  res.body.success.should.equal(true);
                  done();
                });
            });

          it('Login and create a new token and ensure that POST:login ' +
            ' only that needed data from the posted object',
            function(done) {

              server
                .post('/api/users/login')
                .send(newUser)
                .expect('Content-type', /json/)
                .end(function(err, res) {
                  res.status.should.equal(200);
                  token2 = res.body.result.token;
                  res.body.result.token.should.be.type('string');
                  done();
                });
            });

          it('Ensure a user does not view a document not assigned to them',
            function(done) {

              server
                .get('/api/documents/' + docId._id)
                .expect('Content-type', /json/)
                .set({ token: token2 })
                .end(function(err, res) {
                  res.status.should.equal(403);
                  res.body.message.should.equal('Access denied!');
                  done();
                });
            });

          it('Verify if a user cannot delete a document not assigned to them',
            function(done) {

              server
                .delete('/api/documents/' + docId._id)
                .expect('Content-type', /json/)
                .set({ token: token2 })
                .end(function(err, res) {
                  res.status.should.equal(401);
                  res.body.success.should.equal(false);
                  res.body.message.should.equal('FORBIDDEN');
                  done();
                });
            });

        });
Example #23
0
const faker = require('faker');


module.exports = {
	usuario:{
		nombre  : faker.name.firstName(),
		apellido: faker.name.lastName(),
		correo  : faker.internet.email(),
		clave   : faker.internet.password(),
		rango   : 'general'
	}
};
Example #24
0
	users: (function() {
		let res = [];
		for (let i = 0; i < 5; i++) {
			let lang = faker.helpers.randomize(['en-US', 'en-GB', 'de', 'fr', 'it']);
			//faker.locale = lang;
			let user = faker.helpers.createCard();
			user.id = i + 1;
			user.type = faker.helpers.randomize(["personal", "business"]);
			user.password = faker.internet.password(10);
			user.bio = faker.lorem.paragraph();
			let dob = faker.date.past(40, "1998-01-01");
			user.dob = dob.valueOf();
			user.time = moment().format("hh:mm:ss");
			user.age = moment().year() - moment(dob).year();
			user.rank = faker.random.number({
				min: 1,
				max: 10
			});
			user.role = faker.helpers.randomize(roles).id;
			//user.mobile = faker.phone.phoneNumber();
			user.avatar = faker.internet.avatar();

			user.skills = [];
			user.skills.push(faker.helpers.randomize(skills));
			user.skills.push(faker.helpers.randomize(skills));

			user.language = lang;
			user.status = faker.helpers.randomize([true, false, true]);
			user.created = faker.date.recent(30).valueOf();
			user.dt = faker.date.recent(30).valueOf();
			user.favoriteColor = faker.internet.color();

			if (user.type == "business") {
				user.company = {
					"name": faker.company.companyName(),
					"catchPhrase": faker.company.catchPhrase(),
					"bs": faker.company.bs(),
					"website": faker.internet.domainName(),
					"phone": faker.phone.phoneNumber(),
					"address": {
						"street": faker.address.streetAddress(),
						"city": faker.address.city(),
						"country": faker.address.country(),
						"zipcode": faker.address.zipCode(),
						"geo": {
							"lat": faker.address.latitude(),
							"lng": faker.address.longitude()
						}
					}

				}
			} else {
				user.company = undefined;
			}

			user.posts = undefined;
			user.accountHistory = undefined;

			res.push(user);
			//console.log(user);
		}
		//console.log(res);
		return res;
	})()
Example #25
0
describe('[BOOKMARKS]'.bold.green, function() {
  var token,
      userData = {
        firstName: faker.name.firstName(),
        lastName: faker.name.lastName(),
        username: faker.internet.userName(),
        email: faker.internet.email(),
        password: faker.internet.password()
      },
      bookmark,
      bookmarkData = {
        url: 'http://brunozatta.com'
      };

  before(function(done) {
    UserModel.collection.drop();
    BookmarkModel.collection.drop();
    supertest(app)
      .post('/auth/register')
      .send(userData)
      .set('Accept', 'application/json')
      .end(function() {
        supertest(app)
          .post('/auth/login')
          .send(userData)
          .set('Accept', 'application/json')
          .end(function(err, res) {
            token = res.body.token;
            supertest(app)
              .post('/bookmarks')
              .send(bookmarkData)
              .set({Accept: 'application/json', Authorization: token})
              .end(function(err, res) {
                bookmark = res.body;
                done();
              });
          });
      });
  });

  describe('#get()'.cyan, function() {
    it('should get all bookmarks', function(done) {
      supertest(app)
        .get('/bookmarks')
        .set({Accept: 'application/json', Authorization: token})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res) {
          expect(res.body).to.be.an('array');
          expect(res.body[0]).to.have.property('name', bookmark.url);
          expect(res.body[0]).to.have.property('url', bookmark.url);
          expect(res.body.length).to.eql(1);
          done();
        });
    });
  });

  describe('#post()'.cyan, function() {
    it('should create a new bookmark', function(done) {
      supertest(app)
        .post('/bookmarks')
        .send(bookmarkData)
        .set({Accept: 'application/json', Authorization: token})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res) {
          expect(res.body).to.be.an('object');
          expect(res.body).to.have.property('url', bookmarkData.url);
          expect(res.body).to.have.property('name', bookmarkData.url);
          expect(res.body).to.have.property('content');
          done();
        });
    });
  });

  describe('#getOne()'.cyan, function() {
    it('should get a single bookmark', function(done) {
      supertest(app)
        .get('/bookmarks/' + bookmark._id)
        .set({Accept: 'application/json', Authorization: token})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res) {
          expect(res.body).to.eql(bookmark);
          done();
        });
    });
  });

  describe('#put()'.cyan, function() {
    it('should update a specific bookmark', function(done) {
      var update = {
        name: 'portfolio',
        url: 'https://www.google.com/'
      };
      supertest(app)
        .put('/bookmarks/' + bookmark._id)
        .send(update)
        .set({Accept: 'application/json', Authorization: token})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res) {
          bookmark = res.body;
          expect(res.body).to.have.property('name', update.name);
          expect(res.body).to.have.property('url', update.url);
          done();
        });
    });
  });

  describe('#delete()'.cyan, function() {
    it('should delete a specific bookmark', function(done) {
      supertest(app)
        .delete('/bookmarks/' + bookmark._id)
        .set({Accept: 'application/json', Authorization: token})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res) {
          expect(res.body).to.eql(bookmark);
          done();
        });
    });
  });
});
Example #26
0
/**
 * Created by duatis on 22/07/16.
 * Test for account
 */
var chai = require('chai');
var expect = chai.expect;
var Account = require('../models/account');
var faker = require('faker');

var username = faker.name.findName();
var password = faker.internet.password();

describe('Account', function() {

    beforeEach(function(done) {
        var account = new Account({
            username: username
        });

        Account.register(account,password,function(error, account) {
            if (error) console.log('error' + error.message);
            else console.log('no error');
            done();
        });
    });

    it('find a user by username', function(done) {
        Account.findOne({ username: username }, function(err, account) {
            expect(account.username).to.eql(username);
            done();
        });
Example #27
0
let makeData = (item) => {
  let _type = item._type;
  let _assert = item._assert;
  let _length = item._length;
  let _schema = item._schema;
  let _choices = item._choices ? item._choices.split(',') : [];

  let globalSchema = process.currentPlan?process.currentPlan.schema:false;

  if(globalSchema && _schema && globalSchema[_schema]){
    return globalSchema[_schema];
  }

  _type = (_type && typeof _type == 'string') ? _type.toLowerCase() : _type;

  if (_assert !== undefined) {
    return _assert;
  }


  if (_choices.length > 0) {
    return _choices[Number.parseInt(Math.random() * _choices.length)];
  }

  let ret = null;
  switch (_type) {
    case 'string':
      ret = faker.random.word();
      if (_length) {
        ret = ret.substr(0, _length);
      }
      break;
    case 'number':
      let options = {};
      if (_length) {
        options['max'] = Number.parseInt('1'+'0'.repeat(_length)) - 1;
      }
      ret = faker.random.number(options);

      break;
    case 'mobile':
      ret = faker.phone.phoneNumber('1##########');
      break;
    case 'fullmobile':
      ret = faker.random.number({max:99})+'-' + faker.phone.phoneNumber('1##########');
      break;
    case 'email':
      ret = faker.internet.email();
      break;
    case 'password':
      ret = faker.internet.password();
      break;
    case 'object':
      return {'a': 1};
      break;
    case 'array':
      return ['a', 'b', 'c'];
      break;
    case 'bool':
      return faker.random.boolean();
      break;
    default :
      ret = null;
      break;
  }

  return ret;
};
Example #28
0
'use strict';

let faker = require('faker');
let config = require('../config');

module.exports = {
	API: `http://localhost:${config.server.port}/api`,

	user: {
		test: true,
		firstname: faker.name.firstName(),
		lastname: faker.name.lastName(),
		email: faker.internet.email(),
		password: faker.internet.password(),
		birthdate: faker.date.past(),
		gender: 'male'
	}
};
Example #29
0
var HomePage = function() {

    //random generates from 'faker' library
    var randomFirstName = faker.name.firstName();
    var randomLastName = faker.name.lastName();
    var randomEmail = faker.internet.email();
    var randomPassword = faker.internet.password();
    var randomUsername = faker.internet.userName();

    //title and texts of notifications/error messages
    this.pageTitle = 'Etsy :: Your place to buy and sell all things handmade';
    this.passwordExistText = 'Password was incorrect.';
    this.passwordBlankText = "Can't be blank.";

    //sign in form elements selected by id
    this.signInButton = element(by.id('sign-in'));
    this.singInLoginForm = element(by.id('signin-button'));
    this.usernameField = element(by.id('username-existing'));
    this.userPasswordField = element(by.id('password-existing'));
    this.passwordExistingError = element(by.id('password-existing-error'));
    this.usernameExistingError = element(by.id('username-existing-error'));
    this.registerTab = element(by.id('register-tab'));

    //register form elements
    this.registerButtonOnMainPage = element(by.id('register'));
    this.firstNameField = element(by.id('first-name'));
    this.lastNameField = element(by.id('last-name'));
    this.emailField = element(by.id('email'));
    this.passwordField = element(by.id('password'));
    this.passwordConfirmField = element(by.id('password-repeat'));
    this.usernameRegisterField = element(by.id('username'));
    this.etsyFinds = element(by.id('etsy_finds'));
    this.registerButtonRegisterPopUp = element(by.id('register_button'));

    //functions to interact with our page
    this.goToRegister = function() {
        helper.waitElementToBeClickable(this.registerButtonOnMainPage)
        this.registerButtonOnMainPage.click()
    }

    this.goToRegisterTab = function() {
        helper.waitElementToBeClickable(this.registerTab)
        this.registerTab.click()
    }

    this.goToLogin = function() {
        helper.waitUntilReady(this.signInButton)
        this.signInButton.click()
    }

    this.doRegister = function() {
        helper.waitUntilReady(this.firstNameField)
        this.firstNameField.sendKeys(randomFirstName)
        this.lastNameField.sendKeys(randomLastName)
        this.emailField.sendKeys(randomEmail)
        this.passwordField.sendKeys(randomPassword)
        this.passwordConfirmField.sendKeys(randomPassword)
        this.usernameRegisterField.sendKeys(randomUsername)
        helper.waitUntilReady(this.etsyFinds)
        this.etsyFinds.click()
    }
}