logout by deleting cookies - python

I used this code to logout from a django web app. but if I add url manually, it easily redirect me to that page,but that shouldn't happen since I'm logged out.
def logout_view(request):
user = check_validation(request)
response = HttpResponseRedirect('/login/') #redirect to login page
stoken = SessionToken(user=user) #stoken is object for SessionToken
response.delete_cookie(stoken.session_token)
return response`
Please tell me any solution to this problem,or anything that i am missing in this code.
Thanks in advance :)

In Django, there is a built in logout function. Use it, instead of baking your own:
from django.contrib.auth import logout
def logout_page(request):
logout(request)
return HttpResponseRedirect('/login/')
Hope it helps!

Related

Preventing User from accessing login page while signed in using Flask-Login

In Flask, one can use the #login_required decorator in order to protect endpoints. However, I am encountering the opposite issue - how can I prevent my login page from being accessed whilst the user is signed in?
There isn't code that I can really attach, since I have no idea where to even start on this. Any help would be much appreciated! I have followed this tutorial so my code is very similar to this:
https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
Import current_user from flask_login and check if the user (current_user) is authenticated in your view (login view). If the user is authenticated, redirect it to the URL you want.
from flask_login import current_user
#app.route('/login', methods=['GET','POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
edit the parameters and:
def login_not_required(f):
#wraps(f)
def decorated_function(*args, **kwargs):
if "logged_in" in session:
return redirect(url_for("index"))
else:
return f(*args, **kwargs)
return decorated_function
how can I prevent my login page from being accessed whilst the user is signed in?
You might use flask-login get_id() and then check if what was returned is not None, which will mean user is logged in.

DJango user not logging out

I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out.
My Logout view is:
from django.contrib.auth import logout
from django.contrib.auth.models import User
class LogoutView(generic.View):
#staticmethod
def get(request):
if User.is_authenticated:
# Debug statement
print('if')
logout(request)
return redirect('login')
else:
return redirect('index')
My url is working fine because when i go to /logout/, My debug statement executes
but if User.is_authenticated: always returns an object(true).
How can I resolve this issue. Thanks
User.is_authenticated is not what you should do. User is class, show it will have objects which is shown on your request which is already there, and it has nothing to do with the user who is serfing. While, request is the object of the user which carry many things one of them is user.
It should be:
request.user.is_authenticated:

django authorization without using request.user.is_authenticated()

I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code.
def dashboard(request):
if request.user.is_authenticated():
return render(request, 'home/dashboard.py')
else:
return HttpResponse('User is not logged In')
That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent.
Yes, just use the login_required decorator or LoginRequiredMixin
from django.contrib.auth.decorators import login_required
#login_required
def dashboard(request):
return render(request, 'home/dashboard.py')
from django.contrib.auth.mixins import LoginRequiredMixin
class MyCBV(LoginRequiredMixin, GenericView):
What this will do is redirect anyone attempting to access the view back to the LOGIN_URL (which can be overridden here) with a next get parameter back to the view, so that they must login before continuing. This isn't the same as what you currently do, but its much friendlier
If your entire website needs to be logged in, then you can use a middleware to make this the default
You can use #login_required instead. See here

Redefining home in django

I'm working on a Django project in which I plan to make user profiles. My goal is to have a standard login page as seen here. After logging in, however, I want to redefine
url(r'^$', 'MyApp.views.home', name='home'),
to not show this page, but a user profile with the same url as home.
For example, www.example.com shows a login screen. After logging it, you're redirected to www.example.com, but you see your profile now.
How can I do this in Django?
You need simple check in view:
if request.user.is_authenticated():
return HttpResponseRedirect('/profileurl/')
An easy way to do it would be a redirect to another view:
MyApp.views
def home(request):
if request.user.is_authenticated():
redirect
else:
home page
If you want the actual url entry to load a different template than the home page, or a modified home page, you could just as easily render whatever template you wanted in response to the url request instead of issuing a redirect
This is generally how I would go about it. You can add context if needed.
views.py:
from django.shortcuts import render
def home(request):
if request.user.is_authenticated():
return user_home(request)
else:
return login_home(request)
def user_home(request)
return render(request, 'path/to/user_template.html')
def login_home(request)
return render(request, 'path/to/login_template.html')

How to Call default home url in django when i logged out

Please visit this link for getting whole idea behind this question
How to Call loggedin username in Django url
Here i have discussed my points in this link but i didnt got specific answer for my issue that , when user loggedin i wanted it to be displayed in my url as
" 127.0.0.1:8000/username " as i got the solution in above link as create user defind HomeRedirectView which calls initially when user logsin. and it works successfully, but i got an issue when i logged out and revisit the url as " 127.0.0.1:8000/ " then this url automatically becomes " 127.0.0.1:8000/AnonymousUser " and am getting the error as "NoReverseMatch", for that i have to specifically write it into url as " 127.0.0.1:8000/home/ " then it works. So can any one suggest me how to make url as " 127.0.0.1:8000/home/ ". To know about what i have done uptill now ,please visit above link and you will come to know from the discussion.
Please suggest.
The solution you got there is not the right solution, the right solution is to use the LOGIN_REDIRECT_URL setting and point it to a view function, a named URL pattern or a direct URL.
Once a user is logged in using the default authentication mechanism of django, the request will automatically be redirected to this page.
Your second problem is when you logout a user, you want to be redirected to a specific URL. If you use the correct solution above, then all you need to do is:
Set LOGOUT_URL in your settings.py.
Create your logout view, it can be as simple as this example from the documentation:
from django.shortcuts import redirect
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return redirect('/home/')
If you want to stick with your original solution, then modify it like this:
class HomeRedirectView(RedirectView):
pattern_name = 'home'
def get_redirect_url(self, *args, **kwargs):
if self.request.user.is_authenticated():
return "/user/{}/".format(self.request.user)
else:
return '/home/'
I think you are overcomplicating things a little, the following will allow you to redirect to a user home page if a user is logged in, or it will display an un-logged in view. I have made the assumption that the username in the URL is purely for display purposes (otherwise it could be a security issue for your application.
urls.py
urlpatterns = patterns('myapp.views',
url(r'^/$', 'home', name='home'),
url(r'^user/[-_.\w\d]+/$', 'user_home', name='user-home'),
)
views.py
from django.contrib.auth.models import User
from django.shortcuts import redirect, render, get_object_or_404
def home(request):
"""
Home page
"""
# If a user is authenticated then redirect them to the user page
if request.user.is_authenticated:
return redirect('user-home', request.user.username)
else:
return render(request, "myapp/home.html")
#login_required
def user_home(request):
"""
User specific home page, assume the username in URL is just for decoration.
"""
return render(request, "mpapp/home_user.html", {
"user": request.user
}

Categories