How to authenticate a user in Django? - django

I want to authenticate a user such that when he logs into his account and then wants to go back to the login page, he/she should be automatically redirected to the dashboard page. How can I do that?
#login_required
#csrf_exempt
def dashboard(request):
users = GrabhaloUser.objects.exclude(user_id = request.user.id)
if request.is_ajax():
if request.POST.has_key('message'):
selected_users = request.POST.getlist('selected_users[]')
message = request.POST['message']
send_query(request,selected_users,message)
ctx = { 'users' : users }
return render_to_response('dashboard/dashboard.html',ctx, context_instance = RequestContext(request))
login URLS
urlpatterns = patterns('',
url(r'login/',login,kwargs = {'template_name' : 'auth/login.html'}, name = 'grabhalo_login'),
url(r'logout/', logout,kwargs = {'template_name' : 'auth/logout.html'}, name = 'grabhalo_logout'),
url(r'register/','apps.auth.views.register', name = 'grabhalo_register'),
)

Make a function login_page , check the authentication of the user there, if authenticated, redirect it to dashboard, else return to the login page.
Map this function to the login url in urls.py
def login_page(request):
if request.user.is_authenticated():
return redirect('/dashboard/')
else:
return login(request)
And then map this function to the login url.
url(r'login', 'modules.energy.login.views.login_page', name = 'cilantro_login'),

You may try this:
Whenever the user clicks the login page link, the view for the login page is executed. In that view, check if the user is logged in. If the user is logged in,, then redirect him to the dashboard, else display the login page. It is as simple as it is. The sample code:
if request.user.is_authenticated():
#load dashboard
else:
#load login page

Related

Programmatic login succeeds, but not recognized

I have a magnet link feature where my web app sends a login URL with a username & one-time token encrypted. When clicking the link on the email, the user is sent to an authentication where I programmatically log in and then redirect to the member page.
Authentication and login are successful, but when I redirect to the main page, Django sends the user back to the login page. However, when I click the logo, the main page shows.
authentication & login code
def magnet_link_login(request, *args, **kwargs):
if request.user and request.user.id != None:
return redirect('stream:home')
magnet_token = request.GET['key'] if 'key' in request.GET else ''
decrypted_token = decrypt_text(magnet_token)
split_texts = decrypted_token.split('&')
if len(split_texts)<2:
#invalid and redirect to an invalid magnet link page
pass
uname = split_texts[0].split('=')[1]
auth_token = split_texts[1].split('=')[1]
#fetch the user record
acc = Account.objects.get(slug=uname)
if not acc:
#error and redirect to an invalid account name page
pass
#validate and login
try:
logged_user = authenticate(username=acc.username,password=auth_token)
if logged_user is not None:
login(request, logged_user)
return redirect('stream:home')
else:
return redirect('invalid-link')
except Exception as e:
print(e)
return redirect('invalid-link')
My member page (stream:home) is a CBV.
class Home(LoginRequiredMixin, ListView):
paginate_by = 6
context_object_name = 'content_list'
***SOME STUFF HERE***
def get_queryset(self):
*** SOME STUFF HERE***
def get_context_data(self, **kwargs):
*** SOME STUFF HERE***
return context
Except for LoginRequiredMixin at the CBV, I do not check login explicitly and redirect to the login page (the login page is defined at the settings.py). I have already checked handful of threads dealing with similar issues, but my issue is not resolved.
What am I doing wrong here?

DJANGO ALL AUTHEMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL

I am trying to have two different redirects...one for normal login and another for redirect after email confirmation
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/profile'
LOGIN_REDIRECT_URL = '/'
But when I enable login, AUTHENTICATED REDIRECT goes to LOGIN_REDIRECT but when I disable Login it goes to the EMAIL_CONFIRMATION_REDIRECT route.
When I try printing the adapter settings for email_confirmation redirect url below it shows only the LOGIN_REDIRECT
def get_email_confirmation_redirect_url(self, request):
""" The URL to return to after successful e-mail confirmation. """
if request.user.is_authenticated:
if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
return \
app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
else:
return self.get_login_redirect_url(request)
else:
return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL
I tried overriding this get_email_confirmation_redirect_url in the adapter but still wont work. It is not picking the REDIRECT before I login and reverify.
Since ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/profile' was not working if the user is not logged in, I decided to override DefaultAccountAdapter in Django Allauth. My login was that if the time the user joined the app and the time logged in exceeds a certain threshold, then the redirection would be different. So I created an adapter in my users app as below:
class AccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
expiry = 90 #seconds
assert request.user.is_authenticated
if (request.user.last_login - request.user.date_joined).seconds < expiry:
url = 'profile/'
else:
url = settings.LOGIN_REDIRECT_URL
return resolve_url(url)
I then passed this adapter in my settings.py

moving back to web pages after logout is callled

In login, the key to the department is stored in secession and is redirected to the desired department of the user
in login_validation
check = models.user.authenticate(password_entered, username_entered)
if check:
print('valid login')
# check the type of user
request.session['department'] = check['department']
request.session.modified = True
and at logout the the department key is deleted
def logout(request):
if request.session.has_key('department'):
del request.session['department']
request.session.modified = True
return render(request, 'login.html', {'login_form': forms.login_form})
and each page inside the website is checked if department key present if not the user is redirected to the login page
def parts_home(request):
try:
department= request.session['department']
if department != 'parts':
raise Exception
except:
return HttpResponseRedirect(reverse('main:login_page'))
this works fine while hard-coding the URL of the department in the address bar but after pressing back button after logout is called the department key is not checked and the department page is loaded instead of login page. what is the solution?
Try decorator login_required
Add this decorator before your view function.
For example,
from django.contrib.auth.decorators import login_required
#login_required(login_url='/login')
def my_view(request):
....
....
Reference:
the-login-required-decorator

Login required always render to home page

when I am using login_required it does not rendering to appropriate url it always render to home page only
login view
def login_view(request):
print(request.user.is_authenticated())
w="Welcome"
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, "Successfully Logged In. Welcome Back!")
return HttpResponseRedirect("/")
return render(request, "registration/login.html", {"form":form, "title":title})
settings.py file
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
I applied login required on contact us but when i am logging in then it is rendering to home page.
contact us view
#login_required
def contactformview(request):
form = ContactForms(request.POST or None)
if form.is_valid():
form.save()
return HttpResponse(' Thanks For Contacting WIth Us We Will Get Back To You Within 24 Hours')
return render(request, 'contact-us.html', {'form':form})
When Django redirects to the login page, it includes the next url in the querystring, e.g.
/login/?next=contact
Your login_view ignores the querystring and always returns HttpResponseRedirect("/"), so you will always be redirected to the homepage.
It would be better to use Django's login view instead of your own, because it handles the redirect for you. If you must use your own login view, you can look at the source code to see how Django handles the redirect, and adjust your view.

Django register

I am trying to get a user register in Django and then redirects him to his home page ie 'dashboard'. Though, it gets register but due to the authentication provided(#login_required), the user is not redirected to his home page. The user again has to submit his username and password to get login into the page.
Here is my views.py
def register(request):
form = RegisterForm(request.POST or None)
if(form.is_valid()):
user = form.save()
login(request,user)
return redirect('/dashboard/')
ctx = {
'form' : form
}
return render_to_response('home/register.html',ctx, context_instance = RequestContext(request))
#login_required
def dashboard(request):
HttpResponse("HELLO")
You need to use authenticate() first, before calling login().
from django.contrib.auth import authenticate, login
if(form.is_valid()):
form.save()
new_user = authenticate(username=form.cleaned_data.get('username'),
password= form.cleaned_data.get('password'))
login(request,new_user)
return redirect('/dashboard/')
From Django docs:
When you’re manually logging a user in, you must call authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.