How to bypass authentication when testing


#1

I’m using Velocity and Mocha for testing. I also have alanning:roles included. I’m trying to test the code below, but can’t seem to figure out how to either bypass the authentication or to simulate an authorized user.

Do any of you folks know how to simulate an authorized user (I’m using google auth) or have suggestions on how to setup the server-side code to make it easier for me to test?

Thanks!

Meteor.methods({
    'addItem': function ( itemName ) {
        // Authorize User
        if (!Roles.userIsInRole(Meteor.user(), ['admin'])) {
            throw new Meteor.Error(403, "Not authorized");
        }
        
        var exists = Items.find({'name':itemName}).fetch().length;

        if (exists) {
            throw new Meteor.Error( 'item-exists', 'Item already exists.' );
        }

        //Add Item
        return Items.insert({'name': itemName});
    }
});

#2

Are you doing a unit or integration test?


#3

Hi Sam,
I’m doing a unit test.


#4

You could add disableAdmin to your local settings.json file and do something like:
if (!Meteor.settings.public.disableAdmin && !Roles.userIsInRole(Meteor.user(), [‘admin’])) {
throw new Meteor.Error(403, “Not authorized”);
}


#5

@elie Thanks! I will try this out. Having trouble with old tests not disappearing from the HTML reporter for some reason. I will get back to you with any results. Thank you!


#6

Whilst the disableAdmin will work, I would advise against adding test-specific code to your normal execution paths. Tests should test your code, not change it.

You can call your Meteor.method with an apply and set the userId in the invocation context (by passing in a this object with the userId). See here.

Meteor stubs already gives you support to do the above out the box for Meteor methods. See here.

Let me know if that’s enough to go by, I’m happy to help.

RE the old tests not disappearing, it’s a known bug in the reporter. We’ll fix soon :smile:

PS If you add the testing category to testing questions I’ll get notified.


#7

@sam Awesome! Thanks the info, I will try this out.


#8

@geneparcellano, would you mind sharing whatever you get working?


#9

@meonkeys I haven’t applied Sam’s suggestions yet, but I managed to get passed the Login by manually creating a user with admin rights in the test db. I used Meteor.loginWithPassword('e@mail.com', 'password') to simulate a user logging in.

Here’s a link to the repo: [https://github.com/geneparcellano/velocity-mocha][1]

I’m a designer so excuse my sloppy code.
[1]: https://github.com/geneparcellano/velocity-mocha


#10

I wrote a package that does exactly this: https://atmospherejs.com/csauer/accounts-phony


#11

Thanks @csauer, I’ll try it out. :thumbsup: