This authenticate together django.contrib.auth.models.User like django normal login does.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | # coding: utf-8
from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import AuthenticationForm
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext as _
class DjangoAuthentication(object):
"""
Django authentication for piston
"""
request = None
errors = None
def is_authenticated(self, request):
"""
if user is_authenticated: return True
else try to autenticate with django and return true/false dependent of
result
"""
self.request = request
# is authenticated
if self.request.user.is_authenticated():
return True
# not authenticated, call authentication form
f = AuthenticationForm(data={
'username': self.request.POST.get('username',''),
'password': self.request.POST.get('password',''),
})
# if authenticated log the user in.
if f.is_valid():
auth_login(self.request,f.get_user())
# this ** should ** return true
return self.request.user.is_authenticated()
else:
# fail to auth, save form errors
self.errors = f.errors
return False
def challenge(self):
"""
`challenge`: In cases where `is_authenticated` returns
False, the result of this method will be returned.
This will usually be a `HttpResponse` object with
some kind of challenge headers and 401 code on it.
"""
resp = { 'error': _('Authentication needed'), 'msgs': self.errors }
return HttpResponse(simplejson.dumps(
resp, cls=DateTimeAwareJSONEncoder,
ensure_ascii=False, indent=4),
status=401,mimetype="application/json")
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.