Logging out in Django Facebook? - python

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)

Related

Can we track currently active sessions in Python Flask

In my Flask Web-app, a new session is created whenever a new user logs in.
At the server-end, is there a way to track the currently active sessions?
If you are using Flask-Login for your user session management then is_authenticated property of Flask-login tells you if the user is logged in or not:
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
If you want to protect your views you can use #login_required decorator. By default, when a user attempts to access a login_required view without being logged in, Flask-Login will flash a message and redirect them to the login view. (If the login view is not set, it will abort with a 401 error.)
#app.route("/settings")
#login_required
def settings():
pass
See the documentation

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

Re-Authenticate / Confirm credentials of User

I understand how to log a user in/out as well as authenticate within django, but one thing that is mission critical to a new project of mine.
I would like to have the user logged in (which I have), and I would like to then ask the user for their credentials again on certain pages.
I have one method through a EmployeeAuthenticatedMixin that I have made, which checks the POST data for the credentials. The main problem is the Mixin does not redirect, it merely serves up a page. So a user can hit the refresh button and resubmit the form, giving them access again.
Is there any way to ask for the user credentials and allow them access to the next page? Maybe an internal Django thing? Sessions? Messages?
You can log them out forcing them to log back in, using request(logout)
pseudo-coded
def confirm_crednetials(request)
logout(request)
render 'form'
or First prompt the user with a form if they do not have a cookie, you can check and set the cookie with this built in django method resp.set_cookie(foo, cookie) but after you authenticate the user.
if 'id' in request.COOKIES:
**render page
else:
authenticate_user(username=foo, password=bar)
resp.set_cookie(foo, cookie)
I wrote a signal that would fire after login:
from django.contrib.auth.signals import user_logged_in
import datetime
def reauthentication(sender, user, request, **kwargs):
request.session['last_login_time'] = str(datetime.datetime.now())
request.session.save()
user_logged_in.connect(reauthentication)
Then I wrote middleware to catch views that require reauthentication if the sessions last_login_time is older than 3 minutes.

Logout with python-social-auth

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.

Categories