I am using Tastypie to make my API. I am using the following function to login
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
try:
user = User.objects.get(username=data.get('username', ''))
if user.get_profile().status == 3 or user.get_profile().status == 4:
return self.create_response(request, {'success': False, 'reason': 'Account Disabled or Closed' })
user = authenticate(username=username, password=password)
if user:
if user.get_profile().status == 2:
return self.create_response(request, {'success': True,'is_verified':False })
return self.create_response(request, {'success': True,'is_verified':True })
else:
return self.create_response(request, {'success': False, 'reason': 'Wrong Email or Password' })
except User.DoesNotExist:
return self.create_response(request, { 'success': False, 'reason':'Email not registered' })
But when I use jQuery to login with
<script type="text/javascript">
$(document).ready(function() {
$( "#signin" ).click(function() {
var username=$("#inputEmail1").val();
var password=$("#inputPassword1").val();
if (username.length == 0 || password.length == 0) {
alert('enter email and password to login.')
}else{
$.ajax({
type: "POST",
url: "/api/v1/user/signin/",
data: JSON.stringify({ 'username':username,'password':password }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, xhr){
$.cookie();
if (data.success){
if (data.is_verified) {
alert('Logged in and is_verified');
}else{
alert('Logged in but not verified');
}
}else{
alert('Incorrect username or password');
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
};
});
})
</script>
But when I try to fetch my cookie with $.cookie(); in firebug (using jquery-cookie) but it returns an empty object (Object {})
am I missing something? should I be adding something? This does work just fine with iOS. it somehow fetches the cookie and remembers the session. but not here.
Your signin
method isn't setting any cookies, so there is no cookie that jQuery can access. I don't know how this is working for you on iOS (a leftover cookie from another session/manual login?) but unless you can see a Set-Cookie header when you sniff the traffic to iOS, the problem is in signin
.
To set up a session cookie in Django, you need to add the value you want to save to request.session
:
request.session['success'] = true
return self.create_response(request, {'success': True,'is_verified':False })
Incidentally you also have an information disclosure vulnerability in this code as it allows an attacker to determine if a username if valid on the system or not. Normally a login
function should return the same error (in the same time) for an invalid username or an invalid password.