Logout with python-social-auth - python

I am dabbling a little with Python Django Social Auth using Twitter authentication.
I can login.
But, when I try to log out using django.contrib.auth.logout, it doesn't log out.
What's the way to logout?
Thanks.

Are you trying to log out just from the Django app or do you want to "forget" the Twitter access? Usually the twitter auth token is stored for simplified login the next time a user wants to connect to twitter, so the user doesn't have to "accept" the access again.
Django logout
If you just want to logout from the Django auth system, it should be enough to use the django.contrib.auth.views.logout view or to create a custom logout view.
Social auth disconnect
To completely unlink/disconnect a social account, you need to use the disconnect functions in social-auth. You can get the disconnect url using the following template tag:
{% url "socialauth_disconnect" "backend-name" %}
For more information, please refer to http://django-social-auth.readthedocs.org/en/v0.7.22/configuration.html#linking-in-your-templates.
Force approval prompt
Because you've already allowed your app access to the OAuth provider, the auth provider will remember that decision. There are usually two ways to force a confirmation of that access permission:
Revoke the access permission in the management console of your auth provider (e.g. disapprove twitter app access).
Set an extra OAuth argument that forces the approval prompt. I'm not sure if Twitter provides such a thing, but if you're using Google OAuth2 you can simply add {'approval_prompt': 'force'} to the GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS setting.

Do you have a logout view? You need to have a logout view.
Example:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.

This answer is outdated as django-social-auth is now python-social-auth
See newer Stack Overflow answer here.
Read the docs here

According to the documentation there is a difference between log out and disconnect. In short,
Disconnect - forget the user social account.
Log out - end the current user session and remove any related data (like cookies).
From the question, I assume you still want to allow the user to have the Twitter linked with the account. If you want to disconnect, check this answer.
To log the user out, you can have in your Django settings.py
LOGOUT_URL = "logout"
Then, in your urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path("logout/", auth_views.LogoutView.as_view(template_name="registration/logged_out.html"), name="logout"),
]
Then, to log the user out, you can just use in the template something like
Logout
Also, you'll have to create a the logged_out.html file in appname/templates/registration/ and include in it whatever you want the logged out user to see.

Related

Django admin.site.urls only accessible to superuser (The admin login page only accessible to superuser)

What i want is to limit access to the django admin login page to only the superuser. Meaning if you are not the superuser, and try to access http://127.0.0.1:8000/admin - you should be redirected to 404 page , something like that.The means or the custom view to perform this authentication is the challenge. Please somebody assist me with a hint on how to do it?
urlpatterns = [
path('admin/', my_custom_function,name="check_if_superuser"),
# when somebody hits this url pattern , he/she should be taken to the
# function above for checking if superuser befor being redirected to
# django admin login page
]
and in my views.py i have the following function that does the authentication
def my_custom_function(request):
if request.user.is_superuser():
#... redirect to django admin login page
else:
# return render(404_page)
yeah something like that.
By default, django admin allows login for superuser or stuff user only. So, it is kind of safe to have a admin login panel. Also, if you want to restrict that login path, I think its best to put a firewall on that particular route. So that only whitelisted IPs can access it. You can use NGINX for this, and configuration should be something like this:
location /admin {
# block one workstation
deny 192.168.1.1;
# allow anyone in 192.168.1.0/24
allow 192.168.1.0/24;
# drop rest of the world
deny all;
}
This article could be helpful with the configuration.
I assume there might be a catch 22 in the described scenario.
To check user rights there should be a logged in user
If you put check only on available users - is_superuser and show 404:
logged in, non super_user will receive 404
not logged in visitor can go to admin page
If you add check whether user is logged in and if not show 404 as well:
no one can login from admin page, unless logged in somewhere else and got to admin afterwards
Both scenarios sound inconsistent to me. I think what you are trying to achieve is intended to be done by Django framework in a slightly different way.
There is has_permission() in AdminSite class in django.contrib.admin.sites which
Return True if the given HttpRequest has permission to view at least one page in the admin site
and by default returns request.user.is_active and request.user.is_staff
If you change it in your admin.py, only active superusers will be able to utilize admin:
from django.contrib import admin
def has_superuser_permission(request):
return request.user.is_active and request.user.is_superuser
# Only active superuser can access root admin site (default)
admin.site.has_permission = has_superuser_permission
And even logged in non-sups will be shown message about insufficient rights and prompted to re-login

Directly authenticating a user when hitting django admin login page

I have a reactjs app that already has a user logged in. I attached a link to the web app that make the user able to access Django admin page, but for now it still requires the user to login.
I'd like to bypass the login as the user is already authenticated when logging into the react app.
How do I bypass the log in page and tell django that this user is already authenticated? What if I still want to get the email from request? where can I access the request object?
EDIT:
I should specify that I would like to check for auth token which I already have in my localStorage, then authenticate the external user directly. If the auth token is not present, I should still hit the django admin login page
EDIT2:
Created a custom page just to deal with Auth0 authentication. But I'm not sure what to do next. The request.user at this point is AnonymousUser which I can't really operate on. There is no way to identify who this is (but I can successfully check if this user has permission)
I plan to create a user and give it superuser permission? Is that the right approach?
EDIT3:
login(request, request.user, backend='django.contrib.auth.backends.RemoteUserBackend')
return HttpResponseRedirect("/my/url")
and i got
'AnonymousUser' object has no attribute '_meta'
Is it part of the auth problem?
You should not "bypass the login" you need to use authorized tokens... to identify that client whos is consuming the API is really you and not the anyone else
The process is really simple, once you send username and password to your backend (django) you will retorn one autorization token to your frontend (react) and every request from your frontend you will add it to header
Use django_rest_framework or something like that (as tastypie)
http://www.django-rest-framework.org/api-guide/authentication/

SECURITY_UNAUTHORIZED_VIEW did not redirect to login page

I am using flask security for authentication what i want is when user access to a specific url without login/access then it redirects to login page but it redirects to home page.
I know if i add
#login_required
decorator then it will redirect to login page but how to do without that decorator.
i.e
#app.route('/result')
#roles_accepted('admin')
def result():
//some code
I read from flask documentation to add this in app config file.
SECURITY_UNAUTHORIZED_VIEW = '/login'
but again it does not redirect to login page.
Can anyone guide me what i am doing wrong here.
Flask-Security integrates a number of other extensions into a neat package, so it is possible to utilize those packages independently of Flask-Security if necessary.
If you've installed Flask-Security, you should also have Flask-Login installed as a dependency. You can use the current_user class from Flask-Login to check for authentication and redirect manually:
from flask import redirect
from flask_login import current_user
#app.route('/result')
#roles_accepted('/admin')
def result():
if not current_user.is_authenticated:
return redirect(url_for('.login'))
else:
some code....
I'm not sure how this will play with #roles_accepted, but based on the source code it looks like this decorator will intervene prior to the result function if an inappropriate role is used and handle it with the security_unauthorized_callback.
This actually seems to be similar to what #login_required does, i.e. call the security_unauthorized_callback function when the specified conditions are not met, in this case, the proper roles.
If I understand the #roles_required decorator correctly, the above solution should prevent any authenticated users of the improper role from accessing the results page, then manually redirect any unauthenticated users who make it past that check, without using the #login_required decorator.
What is happening is correct.
SECURITY_UNAUTHORIZED_VIEW = '/login'
Redirects the user to the login view, however, what appears to be happening is you have an authenticated user who is not authorized to access the view. When you redirect to the login page, since the user is already authenticated, another redirect happens to the SECURITY_POST_LOGIN_VIEW which in your case is home page.
I have two suggestions.
1) If unauthorized user attempts to access the protected view, log them out and add a flash message that they need to login as authorized users (that is assuming your SECURITY_POST_LOGOUT_VIEW is /login). In this case, your configuration becomes
SECURITY_UNAUTHORIZED_VIEW = '/logout'
and will achieve your objective of having the user redirected to the login page. This happens even if the current user is not authenticated (ie is anonymous/ not logged in)
2) Instead of logging out the user, retain the redirect to home page and add a flash message asking the user to login as an authorized user to access the resource

Logging out in Django Facebook?

Using Django-facebook for the first time.
For some reason, if i log in with facebook, but later log out of my Facebook account. My application stays logged in with the default Django user, with an expired session token because "the user has logged out". If I then re-log in to facebook, the Django app stays "logged out" of Facebook.
In the case above, I have tried attaching #facebook_required_lazy to the top of my view function, but to no effect. What is the intended behavior of this decorator in this use case? The view contains a call to get_persistent_graph.
Your Django login session is completely independent from your Facebook login session. Facebook is used to authenticate only, that is at the time of the login. But the login sessions are independent, not connected. Thus, logging out from Facebook does not affect your Django session at all. It is normal that you are still logged in on Django.
To logout from Django you need to use the logout method of the Django framework, in module django.contrib.auth, for example with a custom logout method like this:
from django.contrib.auth import logout as django_logout
def logout(request):
django_logout(request)
return some_other_view(request)

Django Socail-Auth and My Auth

i tried to install django social auth,
which is located on
https://github.com/omab/django-social-auth
how can i associate a regular registration and social auth
for example a user doesn't have any account in twitter or facebook etc ..
how can i associate django.contrib.auth with social auth
by giving him the choice of choosing either to register normal registration or using his account in twitter or facebook
django-social-auth provides views for authenticated with a particular backend (such as Google, Facebook, or Twitter). Take a look at the code defined in social_auth's URLconf: https://github.com/omab/django-social-auth/blob/master/social_auth/urls.py
Once you've got social_auth installed, if you want to log in with Twitter, you'd visit the begin url specifying the appropriate backend (e.g. /login/twitter/). The social_auth app would then redirect your user to Twitter, at which point they'd authorize your app, then you'd get redirected back the complete url (e.g. /complete/twitter).
If you wanted to associate a Twitter account with an existing user (that is, a User created via the admin app, or something like django-registration), you'd visit the associate_begin url (e.g. "/associate/twitter/").
This all assumes that your root URLconf contains an entry like:
url(r'', include('social_auth.urls')),

Categories