user2268507
user2268507

Reputation:

Authentication token to only apply to one id

I am using this tutorial to incorporate authentication into my app: http://blog.miguelgrinberg.com/post/restful-authentication-with-flask

At the moment I have the following route:

@app.route('/checkin/venue/<int:venue_id>', methods = ['POST'])
@auth.login_required

My verify_password function is quite similar to that specified in the tutorial except I am accessing my own db.

The issue is that when I generate a token, it can be used across multiple venue_id's even though the token was generated using the credentials of a singlevenue.

Is there a way that I could pass the venue_id variable to the function verify_password(email_or_token, password) so when I call verify_auth_token I will be able to check that the venue_id encoded in the token actually corresponds to that made in the call:

@app.route('/checkin/venue/<int:venue_id>', methods = ['POST'])

Thanks for your help.

Upvotes: 3

Views: 89

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67502

You don't say this explicitly, but I assume you have the venue_id in the token, correct? If not, you should add it. The token can store any data you want so add the venue_id there in addition to the user_id.

So what you need is to compare the venue_id given in your request URL against the one in the token. And this is easy to do, since you can access the venue id in your URL as request.view_args['venue_id'].

So assuming you followed the design in my tutorial, you now have a User.verify_auth_token(token) method that decodes the token and verifies it. You can add an argument to this method that is the venue_id, and incorporate that verification in the logic of that method.

Then in your verify_password callback you can do something like this:

@auth.verify_password
def verify_password(token, password):
    user = User.verify_auth_token(token, request.view_args.get('venue_id', 0))
    if not user:
        return False
    g.user = user
    return True

Note that I chose a default of 0 for the case of a request that does not include a venue_id argument. This is just to avoid a crash. In your verification function you can choose to accept a venue_id of 0 as meaning that this request works for all venues, so in that case you skip the check on the venue.

Hope this helps!

Upvotes: 1

Related Questions