django authorization without using request.user.is_authenticated() - python

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

Related

How to block user from opening pages if user is not logged in

I have login and work page.
I want user to login first and then redirect to work page. This scenario is working fine for me.
However when I try hitting the work page it is giving me error, I am checking it through session variable which I know I am doing it wrong as I am not sure which user is trying to access the page if user tries to hit the work page directly as there will be many users in database. How can I restrict user to hit the work page directly and if user does it should redirect to login page
views.py file method is as follows:-
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
**<I have to check here if user session is active or not?>**
return render(request, template_name,context=context)
else:
return render(request,'' ,context=context)
after user login I am creating session and storing in below 2 variables:-
request.session['employee_name'] = employee.usrFirstName
request.session['employee_id'] = employee.id
Django provides login_required decorator for this:
from django.contrib.auth.decorators import login_required
#login_required
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
return render(request, template_name,context=context)

Django: don't let users view views/template if not logged in on admin

I'm new to django. I would like to know if is it possible for Anonymous users not to access my views/template page if they are not logged in to django admin?
Example:
localhost/myviews
localhost/admin
Anonymous user access localhost/myviews > authenticate if logged in to admin > if not, throw error
Use the decorator #login_required. See this.
from django.contrib.auth.decorators import login_required
#login_required(login_url='/login'/)
def secret(request):
return render(request,'after_login.html', {})

How do I redirect visitors to login page?

I have the following url handler in my main Django project urls.py:
url(r'^$', 'core.views.generic.index')
Instead of landing on the index page as above, I want users to land on the login page.
I have another urls.py in an app called core that sends visitors to the login page:
url(r'^/login$', private.MeLogin.as_view())
How can I send all the people visiting url(r'^$', ...) in my main app to private.MeLogin.as_view() in my core app?
EDIT:
I have tried the following,
def index(request):
return HttpResponseRedirect('/#/login')
but I get that this page has a redirect loop
The way to solve that be using a decorator, in this case login_required.
Django documentation
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
index view code in here
What this will do is redirect you to your login view.
As mention in the Documentation
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string.
If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.
You can also customize your decorator check the documentation for more information.
To login required, you must use a decorator indicating that:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
return render(request,'home.html')
In any view that the login is required, just use it.

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')

Django: do not allow users to see pages when they are not logged in

I created a very basic login application. The LOGIN_URL, LOGIN_REDIRECT_URL and the LOGOUT_URL work just fine.
The thing is that if i log in succesully and then i close the window (browser) and then i reopen the browser, i can perfectly search the url (the one i am supose to only see if i am logged in) and use the applcation without loggin in again. This is not where it ends: if i open 2 separate browsers: Chrome and Firefox at the same time and i only logged in in ONE, i can use the applicaction from the other browser without problems.
I dont want this to happend. I tried using login_required in the urls.conf for the index view (the page that you can only see if you are logged in) and in the class view, i tried using stronhold, and django-braces. Is ther any other way to do this?. If you want to see any of the code let me know. Im using the login and log out that django implements (auth).
Than you
I know this is an old post but maybe the answer will help others in the future.
if you workflow is class based views you have to use: LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
class CreateGroup(LoginRequiredMixin, generic.CreateView):
fields = ('name', 'description')
model = Group
The LoginRequired mixin
When using class-based views, you can archive the same behavior as with login_required by using the LoginRequiredMixin. This mixin should be at the leftmost position in the inheritance list.
https://docs.djangoproject.com/en/2.0/topics/auth/default/
It would seem like you need to wrap the 'private' views with Django's login_required decorator:
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
...
This will redirect to LOGIN_URL if the user is not logged in or authenticated.
in the view to the which your login redirects you can add:
def after_login(request,..):
if not request.user.is_authenticated():
redirect('some-non-existence-page-or-404',...)
#Your code
return

Categories