python-2.7google-app-enginegoogle-cloud-endpointsendpoints-proto-datastore

How can I require an api-token field on requests?


I'm currently building a Google Cloud Endpoints backend with the endpoints-proto-datastore library, and am running into trouble requiring an apikey when you request a user. Once a user logs in, they receive an APIkey which they send back for successive puts (which works) but how do I require the username/email and apikey on a GET ? Currently if a user does a get like so:

@User.method(request_fields=('id', 'apiToken',), path='users', http_method='GET', name='user.get')
def user_get(self, query):
    return query

The user is pulled from the datastore because the ID is correct, and it completely ignores the apiToken. How do I require both fields? (on a different note, how do I send back the user's ID on a request?)


Solution

  • The easiest way I found to do this is:

       @User.method(request_fields=('id', 'apiToken',), path='users', http_method='GET', name='user.get')
    def user_get(self, user_model):
        user = ndb.Key('User', int(user_model.id)).get()
        if user.apiToken != user_model.apiToken:
            raise endpoints.UnauthorizedException('You are not authorized to view this data')
        return user.clean()
    

    The user_model will have the userId and the apiToken stored in it, so I pull the "real" data from ndb with the key and check if the user_model has the correct token and return the model if it is correct, if not, I refuse