问题
I am creating a mobile app where I need to use authentication. How can I achieve the following:
- I need to create a user. After creating the user it needs to send
Api_client
and a secret as a response to the user. - I have a function to perform verification. After creating the user it needs to call the function for mobile verification.
- Importantly, how can I stop a user who uses a for loop and starts adding users?
I tried this:
models.signals.post_save.connect(create_api_key, sender=User)
That created an API key but is not sending it as a response when creating the user is successful.
回答1:
Here's what I understand from your question :
- You want any user of your mobile app to register himself, anonymously, as a user to your Django application.
- This request must trigger a Tastypie api_key creation, and then return it.
- You want to prevent this request from being spammed.
I don't understand this :
"I have a function for mobile without verification. After creating the user it needs to call the function for mobile verification."
To answer the points I get :
See this SO question regarding user registration with Tastypie How to create or register User using django-tastypie API programmatically?, notably this part :
def obj_create(self, bundle, request=None, **kwargs): username, password = bundle.data['username'], bundle.data['password'] try: bundle.obj = User.objects.create_user(username, '', password) except IntegrityError: raise BadRequest('That username already exists') return bundle
For a complete walkthrough, check this article : http://psjinx.com/programming/2013/06/07/so-you-want-to-create-users-using-djangotastypie/
You're on the right track regarding the api_key creation, except you have to tell the api to actually send it back. You can use the regular way (it requires another request, though) :
i.e make it accessible from UserResource, as described in the article linked above, specifically :
def dehydrate(self, bundle): bundle.data['key'] = bundle.obj.api_key.key try: # Don't return `raw_password` in response. del bundle.data["raw_password"] except KeyError: pass return bundle
If you want to send it right after a User's registration, don't forget to set "always_return_data" to True and add the api_key to the response.
Spam / loop registration :
You should look into your server's capabilities regarding this matter. For example, assuming you're using Nginx : http://wiki.nginx.org/NginxHttpLimitReqModule
Another option might be to use this : http://django-ratelimit-backend.readthedocs.org/en/latest/
Hope this helps !
Regards,
来源:https://stackoverflow.com/questions/23147781/django-tastypie