Getting unlogged after a redirect in django - django

I have 2 Django projects :
project_redirect, which is running on http://localhost.com:8005
project_logged_in, which is running on http://localhost.com:8000 (I'm authenticated in this one)
When I try to do a redirect from project_redirect to a view that requires authentication in my project_logged_in, I get unlogged in project_logged_in (checked that with request.user.is_authenticated() in the first line of the view).
my redirect view is as sample as :
def test_redirect_view(request):
return HttpResponseRedirect('http://localhost.com:8000/login_required_view/')
Why would this happen?

Your session cookie is being shared by both projects as they are using the same domain.
Try setting SESSION_COOKIE_NAME in both projects to something unique.

Related

Handling Django Registrations for Duplicate Entries

Question PART 1:
Project => App => forms.py
![User Creation Form using default Django Structure]
Project => App => urls.py
![URL Routes defined in urls.py of Django App]
Project => App => views.py
![User Authentication using default Django Structure]
Instead of using SQLite, I am using MongoDB Database and the entries are being stored in the auth_user table but I wanna get rid of duplicate entries (i.e. same username/email). If the user enters a same username/email, the page gives a DatabaseError Exception which I believe is handled by Django itself.
Question PART 2:
Project => settings.py
![Have included MessageTags into settings.py]
Also how to give specific redirect locations to messages in Django !? Once the user completes registration, the success message is displayed and he is redirected to the login page to access the dashboard and other features. But when the user logs in successfully, he is redirected to the dashboard but the Success Message is being displayed when he logs out (in the logout page).
Approach PART 1:
Can I, using try catch, handle the exception and allow the user to change the entered values to something unique and get his details saved into the database !?
Approach PART 2:
Sometimes the messages are appearing onto different pages than specified pages while using render/redirect for views.py functions(i.e routes). I tried redirecting each message to specific routes but I guess it overwrites to the last render/redirect route.
Regards,
Joe.

Django all auth facebook login with Use Strict Mode for Redirect URIs

Hi I am trying to implement Facebook login for my website using Django Allauth.
As we can no longer disable Use Strict Mode for Redirect URIs I am getting an error when I try to login via facebook.
The callback URL formed at the time of Facebook login is of this format -
https://example.com/accounts/facebook/login/callback/?code=AQB7W48oY-1XxZv2xU9iahxS80ZPs4oBNLlXWTY7Y93dclyIElEPG-jWKB5ELV7Pv11ckcRYg3L67Wfcz6xqC8yhNLBaFaOQjd4F2AEp8nfScltnY3LoY79g9NjtslCSbQnSlc_hDdBm_rxQtScz-rLChNvAJaky3KYMG_USSTkm9qdyvw5lIMdcIHQjz3CTF8KdgmuFG1T8_WvVqdGDEpfhC_PD7w5tnkcChBEowHnWR656DYa1wrMR1fbP2rqxBocNn6fKPCy_GM_DZynPp8mx0F0YP55vzw2Kv8KchB2nxCaHwQ4dRvJq785w5CfCgDVc6REhbc3CNG2KqZxdxjuG&state=eukVyjHYk04X#_=_
This URL contains the query params code and state because of which it is not an exact match and I checked it via Redirect URI to Check which reported it as invalid.
So on the authentication_error.html I get the following error.
{'provider': 'facebook', 'code': 'unknown', 'exception':
OAuth2Error('Error retrieving access token:
b'{"error":{"message":"Can\'t load URL: The domain of this URL
isn\'t included in the app\'s domains. To be able to load this
URL, add all domains and sub-domains of your app to the App Domains
field in your app
settings.","type":"OAuthException","code":191,"fbtrace_id":"AxoTkIBeoUSKsxuWvMx-Wg4"}}'',)}
My Valid OAuth Redirect URIs has the following URL's
https://example.com/accounts/facebook/login/callback/
https://www.example.com/accounts/facebook/login/callback/
Please help me with this issue, I have looked into all the existing issue but haven't found a solution.
For anyone facing a similar issue, it could be because you missed to add this line to your settings.py file.
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'

Login Required Middleware gets HTTP/1.1" 302

I've done a simple login that works fine while the authenticated user is redirected to a page with url:
url(r'^(?P<user_id>\d+)/$', 'auth.views.main', name='main'),
Now I'm trying to use a LoginRequired-Middleware but when I do and I try to login I get:
"POST /login/ HTTP/1.1" 302 0
"GET /1000/ HTTP/1.1" 302 0
and I remain to the initial login-page.
I use a common snippet for doing that with
LOGIN_URL = ( '/login/' )
What's going wrong?
Unfortunately your provided code is insufficient to determine your error, so I can only give you pointers:
Make sure you aren't actually still caching an HTTP 302 REDIRECT site, from earlier experimenting. See here for useful hints.
Reset your browser-cache. If you are using Chrome, you can get several cache clearance options by pressing CTRL+SHIFT+J (starting the Developer Tools), and long pressing the Reload button next to the top navigation url-bar.
For Firefox, see also these useful suggestions.
http://support.mozilla.org/es/questions/848678
https://superuser.com/questions/23134/how-to-turn-off-firefox-cache
Did you just upgrade Django from version <1.3.x? I came across a situation where passwords were rewritten with a new default-Hasher, and thus one could no longer log in. Check password-hasher consistency directly in your database, within the auth_users - table. For instance SHA1 password-hashes start with sha1...
Make sure to setup the list PASSWORD_HASHERS in your settings.py, is in an order that retains the original project's primary Hasher on top. i.e. the hashing-algorithm that was used to initially hash the user passwords.
Is the url(r'...'...) in the root urls.py of your project?
Make sure 'django.contrib.auth' is listed in your INSTALLED_APPS section of settings.py (though you should get error's if that is not the case) and apps that must be loaded beforehand, are actually placed uppermost.
Check the setup of your TEMPLATE_CONTEXT_PROCESSORS, MIDDLEWARE_CLASSES in settings.py according to your snippet's comments and make sure it is compatible with the SessionMiddleware of your Django version.
Check all codelines in your project that make redirects:
Check for:
from django.views.generic.base import RedirectView
url(r'^.*$', RedirectView.as_view(url='<url_to_view>', permanent=False), name='index')
or
from django.http import HttpResponsePermanentRedirect
HttpResponsePermanentRedirect('url...')
Note that in Django 1.5 the deprecated redirect_to function has been replaced by RedirectView, according to their generic view paradigm.
redirect(...)
url('^pattern/$', lambda _: redirect('/redirecttourl/'))
url(r'^pattern$', redirect('example.com')),
url(r'^pattern$', redirect(projectname.views.home)),
(r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
HttpResponseRedirect(....)
HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
Django's built-in authentication login page includes a next query string. next= determines the the page to return to after login:
See: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required
Check your server's HTTP access logs. Is the content-size of the login-site after the redirect the same as the login before the redirect?
It helps providing the entire HTTP access history during the login process. As you do not hang in an redirect-loop, more HTTP's than the two mentioned must follow.

django socialauth twitter , google oauth , facebook does not work

This is my first post, and I have a problem I could not make it work django OMAB socialauth of three things I just need to google, facebook, and twitter, google works well with open id, but not much twitter and I put in my
settings. py:
TWITTER_CONSUMER_KEY = '00' this is no real
TWITTER_CONSUMER_SECRET = '00' this is no real
FACEBOOK_APP_ID = '' ihave no key
FACEBOOK_API_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
ORKUT_CONSUMER_KEY = ''
ORKUT_CONSUMER_SECRET = ''ihave no key
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
LOGIN_ERROR_URL = '/login/error/'
#SOCIAL_AUTH_USER_MODEL = 'app.CustomUser'
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
FOURSQUARE_CONSUMER_KEY = ''
FOURSQUARE_CONSUMER_SECRET = ''
LOGIN_URL = '/login-form/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL = '/login-error/'
I am using the example that comes in the zip of OMAB socialauth django , but not working.
When I created my twitter app, I wrote my domain www.sisvei.com , I am testing locally socialauth django ie 127.0.0.1:8000, then sign in with twitter sends me to this url:
http://127.0.0.1:8000/login/error/ and a message saying is the Incorrect authentication service
this happens with facebook and google oauth and oauth2
I'm new to django and I this much work comprising this part of django socialath hopefully help me, thank you very much.
You need to be more specific on "why it doesn't work". Where are you getting the errors?
When debugging a third-party oauth/openid app in Django, generally it boils down to:
configuration & keys - did you make sure to obtain all of the necessary API keys for the services you will be using, and to add them to your configuration?
urls - did you remember to add the necessary urlpatterns to your base urls.py file?
authentication setup on the server - often, you'll need to have a file available or respond with a specific header when the authentication service hits your server. Have you checked to make sure that is set up?
databases - have you run syncdb after installing the app? Are all the tables set up?
templates - if the third party app requires you to set up templates, do you have them set up?
custom views - are you using custom views? If so, try using the built-in views that came with the third party app first, to see if they work
After those are confirmed, you're going to want to be able to see what requests are taking place. Use the debugger included in Chrome/Safari, or get the web developer add-on for Firefox, and look at the network requests as they happen. Do you see HTTP responses other than 200 (say, 404, 500, 403, etc?) those mean that the services aren't responding correctly.
From your error, it looks like you have not correctly set up your callback URL on Twitter. It should be sending you to www.sisvei.com, not 127.0.0.1. Alternatively, check the URL when you get to the Twitter login page -- is the callback URL in the URL, and is it pointing to 127.0.0.1? Then Django is sending it the wrong callback URL.
Finally this:
I wrote my domain www.sisvei.com python does not support this
Is unclear. As far as I know, Python doesn't care what the domain is.
WAIT A MINUTE ...
Are you using runserver? Are you getting the following error?
Error: "www.sisvei.com" is not a valid port number or address:port pair.
If so, there is an easy fix! Just run it like so:
python manage.py runserver www.sisvei.com:80
That should resolve your error if that's what's happening. You're probably running it as
python manage.py runserver 127.0.0.1
127.0.0.1 is a reserved IP address that points back to localhost, your own computer. As a result, it is not possible to use it for authentication or any other purpose outside of programs running on your own machine. See this article for more info.
I'm not sure, but I might be having similar problems, oscar. For me, SocialAuth was generating an AuthenticationURL for facebook, foursquare and hotmail, but not for google, twitter or any of the other address it supports. I think it may be something wrong with the API, so I posted an issue on the social-auth google group...you may want to check there to see if anyone updates!!
https://code.google.com/p/socialauth/issues/detail?id=282&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Modified

Django-HttpRedirect fails in Internet explorer

I have a Facebook application using Django. In one of my views I use following piece of code to make user logged-in.
In IE, return HttpResponseRedirect line fails with error message "This content cannot be displayed in a frame...", although other browsers are working fine.
Do you have an idea, why IE fails for HttpResponseRedirect?
(This is problem is produced on IE9 on Windows 7, server is using django-1.3)
def auto_login(request):
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)
theURL='http://apps.facebook.com/myapp/'
return HttpResponseRedirect(theURL)
else:
return HttpResponse("disabled account")
else:
return HttpResponse("Invalid login")
This can be two things, both related to the browser security model.
Option 1 is the redirect to another domain.
Clients may decide to follow the redirect, or to refuse. In particular a HTTP 307 redirect (which allows forwarding of POST data) is not always accepted by clients.
Option 2 is related to the redirect of a resource with HTTP method POST url to another resource with method GET.
If the HTTP method of the current view and the redirect are different (i.e. HTTP POST against the /login url vs. HTTP GET of the facebook/myapp), at least IE8 will refuse to redirect. I'm not sure of this has been changed in IE9.
There's a few things you could try.
You could try another HTTP response code. Assuming there is no need to forward the HTTP parameters from the original request to the redirected request, a response code 303 would be better than a 307.
If your situation involves a redirect of an HTTP POST resource to the external HTTP GET resource at facebook, another attempt is put an extra redirect in the middle:
POST resource on yoursite.com --> redirect to GET resource on yoursite.com --> external redirect to facebook domain.
The "extra redirect" option could fix one browser but break another (browsers have limits on redirects, which may vary per browser type and version). If you would get into this situation you may need to detect the user-agent and switch between IE and other browsers.
A few good links:
Django/IE8 Admin Interface Weirdness
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes