Note that there are some explanatory texts on larger screens.

plurals
  1. POAuthentication over REST
    primarykey
    data
    text
    <p><em><strong>Update 3</em></strong>: The REST API Permissions: when defining the viewset associate the proper permission class...</p> <pre><code>class TopSecretViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = myModels.TopSecret.objects.all() serializer_class = mySerializers.TopSecretSerializer permission_classes = (myAuth.MyIsAuthenticated,) </code></pre> <p><em><strong>Update 2</em></strong>: The REST Authentication</p> <p><strong>Edit</strong>: <em>return a Permissions Object with the user</em></p> <p>Settings.py</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'app.authentication.MyAuthentication', ) </code></pre> <p>authentication.py</p> <pre><code>class MyIsAuthenticated(BasePermission): """ Allows access only to authenticated, if it is AnnoymousUser we don't allow access. There will be more code here - but this is good for the example """ def has_permission(self, request, view): if request.user and isinstance(request.user, myModels.User): return True return False ###################################################### # TODO: return the apropiate permissions ###################################################### class MyAuthentication(authentication.BaseAuthentication): def authenticate(self, request): cookies = request.COOKIES if 'user' in cookies: userCookie = request.COOKIES['user'] userJson = base64.b64decode(userCookie) userDict = json.loads(userJson) userId = userDict['user_id'] if not userId: return None try: user =myModels.User.objects.get(user_id=userId) except myModels.User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, MyIsAuthenticated) return None </code></pre> <p><em><strong>Update</em></strong>: Working the solution</p> <p>The django restframework viewset:</p> <p><strong>Edit</strong>: <em>added a base64 encode cookie of the user object (which is being returned in the JSON payload as well</em></p> <pre><code>##################################################################### # handles two REST APIs GET/list users (through the mixin and) in # accordance to the rules of the UserLoginSerializer # the POST/create - and while I don't like handling this in the # create method, this is the post of the login credentials ##################################################################### class UserViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = myModels.User.objects.all() serializer_class = mySerializers.UserLoginSerializer def set_cookie(response, key, value, days_expire=7, host=''): if days_expire is None: max_age = 1 * 24 * 60 * 60 #1 day else: max_age = days_expire * 24 * 60 * 60 expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age),"%a, %d-%b-%Y %H:%M:%S GMT") host = host.split(':')[0] response.set_cookie(key, value, max_age=max_age, expires=expires, domain=host) return response def create(self, request): login_email = request.DATA['email'] login_password = request.DATA['password'] login_password = login_password user = myModels.User.objects.get(email=login_email) md5 = hashlib.md5() md5.update(login_password) login_password_md5 = unicode(md5.hexdigest()) if (user and login_password_md5 == user.password): user.last_login = datetime.now() user.save() role = 4 #verfied user responseData = { 'user_id': user.user_id , 'firstName': user.firstname , 'lastName': user.lastname , 'email': login_email , 'role': role } return set_cookie( Response(responseData) , 'user' , base64.b64encode(json.dumps(responseData, ensure_ascii=False)) , days_expire=1 , host = request.META['HTTP_HOST']) else: role = 1 #anonymous return Response({'email': login_email, 'role': role, 'message': 'Unknown Email or Incorrect Password' , 'user_id': -1, 'first_name': '' , 'last_name': ''}) </code></pre> <h2>Original Post</h2> <p><em><strong>Edit</em></strong>: <em>I am hooking this up to a PHP legacy application to run side by side until I can completely port to Python over the next year or so. Therefore the attraction of the built in Django Authentication is not as appealing</em></p> <p>I have a single page web app, that shows a bunch of <em>teaser</em> content. If you click on the content you get prompted to log in. I use a div overlay-ed on the screen to display the log in form, and I want to submit the data on this form to the server for authentication. </p> <p>Our site currently runs over HTTPS, so I am thinking a simple solution is best for now.</p> <p>Question 1: The Log In service: I was thinking about performing the log in over a POST REST request, but I am not sure this is the right approach - or really - if there is a better approach.</p> <p>Question 2: Using Django-Rest-Framework i need to coordinate the Authentication and the Log In service. I was thinking that I would create a custom Authentication that would read a cookie and identify the proper user and permissions. Does this seem like a reasonable solution?</p> <p>Question 3: The Cookie? Where should I write the cookie? Should I embed it in the response from the server as part of the Log In service, OR should I write it on the js/client side upon a successful log in. I think the former is the probably the better method, and can allow me to en[de]crypt the cookie in the future having all of the code in a single place (the server). Does anybody think that writing the cookie in the javascript side upon a successful log in is better?</p> <p>My Client Stack: AngularJs, RESTangular (it picks up cookies nicely), and other less interesting pieces</p> <p>My Server Stack: Python 2.7, Django 1.5, Django-Rest-Framework</p> <p>Always - thanking you in advance!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload