Reputation: 3475
I've been developing a mobile app to access one of my django websites. I've done the restful API using TastyPie and developed the front end using JQMobile. I've come to the part where I want to log users and have access to that logged in user.
I've done a lot of reading and searching, but I'm still really unsure what is the best approach. Ideally, I'd like to log in the user with their username and password, and then filter some of the API's returned data on this user (which I can do via the TastyPie documentation).
How have other people approached authenticating users with JQMobile and Django. I'm using PhoneGap as well so I can store returned user info from a login in the local storage if required. But I'm not quite sure how to code it all together to make request.user available on the django side when the mobile users are using the app.
So far I've come up with this from another couple of posts in the UserResource on the TastyPie side of things to sign in a user, but I'm not sure what to do once the user is signed in.
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
list_allowed_methods = ['get', 'post']
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
# Per https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.login...
username = request.GET['username']
password = request.GET['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return self.create_response(request, {'success': True})
else:
# Return a 'disabled account' error message
return self.create_response(request, {'success': False})
else:
# Return an 'invalid login' error message.
return self.create_response(request, {'success': False})
Does anyone have any code they can share, or any pointers how to log in the users and maintain their state?
Cheers, Ben
Upvotes: 2
Views: 1164
Reputation: 1719
Phonegap is actually just a browser wrapped in some native code, which means it has the same means to persist sessions like normal web browser do - cookies!
Every ajax request being sent to the backend API can contain the sessionid
cookie just like a normal GET
request. The requst.user
object will be available to you in your views.
You don't need to build anything special or use localstorage for that. The only thing to verify is that your domain is whitelisted so your app can access it.
Upvotes: 1