I want to log every request sent to Django.
There are some posts online about logging middleware.
The Django documentation talks about logger configuration and it seems that I can set it up to log everything without writing middleware.
Can I log everything without middleware?
What can middleware give me that a well-tuned Django logging config cannot?
Can I log INFO level messages, with DEBUG = False and no middleware?
How much extra load does logging everything add to my app?
if want to log every request, in that case, you should use Logging in middleware
https://djangosnippets.org/snippets/428/
Related
I used Django Tastypie to build my api and i'm thinking in the correct way to create a login form so the user can login in the application, right now what I do is send a GET request with username/password he submited in the form as filtering options, but i'm pretty sure thats not secure at all. How can i do the same using POST request?
When i open the console with firebug:
GET URL/app/api/v1/user/?email=USER&password=PASS
Api-Auth and Content-Type are on the header.
#leosilvano
Don't handle user authentication and authorization using angular js not that its impossible but just that its not too secure and implementing also take some effort when Django's provides something which far easy than this.
I happen to be using django + angularjs + tastypie (REST API ). If you like take a look at my way of implementation.
Include your index.html of the angularJs in your templates ( Django Templates ) and place your directives, controllers, js, css and etc in the static folder ( Django Static ). Make your API calls after the auth processes. This will work seamlessly and you will run into less issues as well.
Reasons:
user_auth models becomes so handy while registering and logging in using templates and you don't need to sweat trying to write your own authentication which i'm sure you have to do when you go with Angular Js login auth implementation.
Use of decorators like for a view lets say "profile" if you need to check if the user is logged in all you need to do it something like the following
#login_required(login_url='/login/')
def profile(request):
return render_to_response('profile.html')
Passing password through "GET" is bad .. and passing auth values through "POST" and getting it via JSON .. is also not a good idea. Because you will be susceptible to middle-man attacks ..
Remember you have to take measures for CORS requests when using Angularjs for login since anyone can view the json response and they will be able to reproduce the same structure. Implementing Perm-Mixins and Groups is way more easier when using Django templates.
Handling exceptions like 404 or if you want to handle only post requests and thereby take user to a custom page ( actions like redirect ) becomes difficult. I am aware of SPA's but still if there happens to be redirection .. in my case i needed to redirect to another site. Following shows how simple it can be achieved including http statuses.
if request.method != 'POST':
return HttpResponseNotFound(render_to_response('404.html', { 'message' : 'Only POST Requests are allowed for authentication process.', 'baseurl' :request.build_absolute_uri('/').rstrip('/')}))
Solution:
Use Angular Js and REST (Tastypie) interaction to happen after you login. Use Django template for login authorization. Make use of the django modules .. it saves a lot of time.
If you still want to login using REST API .. by send post to django .. please take a look at the following post
How can I login to django using tastypie
You can POST data using the $http module
Just do:
$http.post(url, data)
Always send authentication data through https or your password will be sent in clear text.
I have created a REST web service using Django. This web service has a log file. I'd like to log all web service (http) requests in the log file. However, the web service request handling is done by Django, I only setup url-request handlers mapping and create the request handlers (views in Django nomenclature). Is there a way to log all requests in a central point, without needing to log each request in its associated request handler (view)?
Thanks in advance.
Yes Django has a built in signals framework.
It allows you to register a function to be called everytime a request starts.
This documenation page explains how to do it step by step
Using the decorator method:
from django.core.signals import request_started
from django.dispatch import receiver
#receiver(request_started)
def my_callback(sender, **kwargs):
# log the request here
pass
Where should this code live? You can put signal handling and
registration code anywhere you like. However, you’ll need to make sure
that the module it’s in gets imported early on so that the signal
handling gets registered before any signals need to be sent. This
makes your app’s models.py a good place to put registration of signal
handlers.
I want to secure my Task Queue URLs against malicious access.
In the views that the Task Queue requests I've got:
if not users.is_current_user_admin():
return HttpResponse(status=403)
But my Task Queues are receiving 403 errors! I was under the impression from this GAE documentation that the Task Queue user was gauranteed to be an admin. What gives?
NOTE: I'm using DjangoNonRel so I can't specify the admin only url access in my app.yaml, I have to do it programmatically in the views.
Tasks can bypass login: admin restrictions, however users.is_current_user_admin() will still return false, as there is technically no current user.
Using Django-nonrel shouldn't stop you from protecting your tasks with app.yaml. Just add a protected handler above your Django catch-all:
handlers:
- url: /tasks/.+
script: main.py
login: admin
- url: .*
script: main.py
Any URLs that start with /tasks/ will be accessible to the task queue and inaccessible to non-admin visitors, without changing how anything routes.
Your handlers can look for a task queue HTTP header, such as X-AppEngine-QueueName.
From official GAE docs :
Requests from the Task Queue service contain the following HTTP headers:
X-AppEngine-QueueName
X-AppEngine-TaskName
X-AppEngine-TaskRetryCount
X-AppEngine-TaskExecutionCount
X-AppEngine-TaskETA
These headers are set internally by Google App Engine. If your
request handler finds any of these headers, it can trust that the
request is a Task Queue request. If any of the above headers are
present in an external user request to your app, they are stripped.
You can accomplish this by doing 2 checks
Check remote address, it will be 0.1.0.1
Check for existence of header [X-Appengine-Cron].
This will secure you Task Queue URLs (this is only applicable for Pull Queues as per my knowledge).
I wrote a decorator which does this checks for me.Hope this was helpful
For more info, Please refer Docs
I am creating a chat like facebook chat... so in views.py of my Chat Application, I need to retrieve only the last messages every 3-4 seconds with ajax poll ( the latency is not a problem for me ).
If I can disable some Middlewares and some Request Context in this view, the response will be faster... no ?
My question is:
Is there a way to disable some Middlewares and some Request Context in some views ?
This is not likely to be feasible. Best to have a second Django project or WSGI app to handle these requests.
We have a website running on Apache, access to which has a number of static pages protected via HTTP Basic authentication.
I've written a new part of the site with Django using Django's built in support for user management.
The problem I have is that users have to log in once via the HTTP Basic authentication and then again using a Django login form. This both clumsy and very confusing for users.
I was wondering if anyone had found a way to make Django log a user in using the HTTP Basic authentication information.
I not expecting to pass a password to Django, but rather if a user dave has been authenticated by Apache then they should be automatically logged into Django as dave too.
(One option would be to make Apache and Django share a user store to ensure common usernames and passwords but this would still involve two login prompts which is what I'm trying to avoid.)
For just supporting basic auth on some requests (and not mucking with the web server -- which is how someone might interpret your question title), you will want to look here:
http://www.djangosnippets.org/snippets/243/
This has been added to the Django 1.3 release. See more current documentation for this here:
http://docs.djangoproject.com/en/dev/howto/auth-remote-user/
Do check out Oli's links. You basically see the authenticated username as verified by Basic HTTP Authentication in Django by looking at request.META['REMOTE_USER'].
Update: Tested the proposed patch for ticket #689, which is available up-to-date in telenieko's git repository here. It applies cleanly at least on revision 9084 of Django.
Activate the remote user authentication backend by
adding the RemoteUserAuthMiddleware after AuthenticationMiddleware
adding the setting AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.RemoteUserAuthBackend',)
If you use lighttpd and FastCGI like I do, activate mod_auth, create credentials for a test user (I called it testuser and set 123 as the password) and configure the Django site to require basic authentication.
The following urls.py can be used to test the setup:
from django.conf.urls.defaults import *
from django.http import HttpResponse
from django.contrib.auth.models import User
urlpatterns = patterns('',
url(regex='^$',
view=lambda request: HttpResponse(repr(request), 'text/plain')),
url(regex='^user/$',
view=lambda request: HttpResponse(repr(request.user), 'text/plain')),
url(regex='^users/$',
view=lambda request: HttpResponse(
','.join(u.username for u in User.objects.all()),
'text/plain')),
)
After reloading lighty and the Django FCGI server, loading the root of the site now asks for authentication and accepts the testuser credentials, and then outputs a dump of the request object. In request.META these new properties should be present:
'AUTH_TYPE': 'Basic'
'HTTP_AUTHORIZATION': 'Basic dGVzdHVzZXI6MTIz'
'REMOTE_USER': 'testuser'
The /user/ URL can be used to check that you're indeed logged in as testuser:
<User: testuser>
And the /users/ URL now lists the automatically added testuser (here the admin user I had created when doing syncdb is also shown):
admin,testuser
If you don't want to patch Django, it's trivial to detach the RemoteUserAuthBackend and RemoteUserAuthMiddleware classes into a separate module and refer to that in the Django settings.
Yes you can use basic autorization with django as something similar:
def post(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
token_type, _, credentials = auth_header.partition(' ')
import base64
expected = base64.b64encode(b'<username>:<password>').decode()
if token_type != 'Basic' or credentials != expected:
return HttpResponse(status=401)
authorization success flow code ...
request.META contains key HTTP_AUTHORIZATION in which your Autorization is present.
In case if you are using apache with modWSGI, the key HTTP_AUTHORIZATION might not be present. You need to add below line in your WSGI config
WSGIPassAuthorization On
Refer this detailed answer:
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi
Hope it is useful for someone who is wondering why HTTP_AUTHORIZATION key is not present
There is httpauth.py. I'm still a complete newb with Django so I've no idea how it fits in exactly, but it should do what you're looking for.
Edit: here's a longer bug thread on the subject.
Because django can be run in several ways, and only modpython gives you close integration with Apache, I don't believe there is a way for django to log you in basic on Apache's basic auth. Authentication should really be done at the application level as it'll give you much more control and will be simpler. You really don't want the hassle of sharing a userdata between Python and Apache.
If you don't mind using a patched version of Django then there is a patch at http://www.djangosnippets.org/snippets/56/ which will give you some middleware to support basic auth.
Basic auth is really quite simple - if the user isn't logged in you return a 401 authentication required status code. This prompts the browser to display a login box. The browser will then supply the username and password as bas64 encoded strings. The wikipedia entry http://en.wikipedia.org/wiki/Basic_access_authentication is pretty good.
If the patch doesn't do what you want then you could implement basic auth yourself quite quickly.
This seems to be a task for custom AuthenticationBackend - see Django documentation on this subject, djangosnippets.org has some real-life examples of such code (see 1 or 2) (and this is not really a hard thing).
AuthenticationBackend subclasses have to have only 2 methods defined and their code is pretty straightforward: one has to return User object for user ID, the second has to perform credentials check and return User object if the credentials are valid.