0

I want user to be logged in each time once he logs in first time. Steps:

  1. User register first and redirected to the login page
  2. User loges in and enters in the application.

Now for the next time user is already registerd and I do not want to ask him for the username and password again, because he is already registerd and logged in. So at this time when he clicks on login button he should directly be redirect to the application without entering username and password.

My login views.py is

from datetime import datetime
from django.contrib import auth
from django.core import serializers
from django.core.exceptions import ValidationError
@csrf_exempt
def login_android(request):
    print "i am in view"
    if request.method == "POST":
        print "you are in method"
        username = request.POST['name']
        password = request.POST['password']
        #user = auth.authenticate(username=username,password=password)
        print username
        login_api(request,username,password)
        user = auth.authenticate(username=username,password=password)
        print user
        if user==None:
            print "user is not available"
            dict = {'username': 'Wrong username or password'}
            response = json.dumps(dict)
            return HttpResponse(response, mimetype="application/json")
        else:
            response = json.dumps((model_to_dict(user)), cls=DjangoJSONEncoder)
            return HttpResponse(response, mimetype="application/json")

my login api.py file is

def login_api(request,username,password):
    print "you are in login api"
    user = auth.authenticate(username=username,password=password)
    print user
    if user:

        if user.is_authenticated():
            print "user aunticated"
            auth.login(request,user)
        else:
            raise ValidationError
    return user

my log in .html page

$(function()
                {
                localStorage['domain'] = "http://122.171.89.190";
                var domain = localStorage['domain'];
                $('#fac1').on('click', function () {
                        var username = $("#username").val();
                        var password = $("#pwd").val();
                        data = {
                            name: username,
                            password: password
                            };
                        $.ajax({
                            url: domain + "/login/login_android_here/",
                            type: "POST",
                            data: data,
                            success: function (response) {
                                                dat=response.username;
                                                if (dat==username){
                                                window.location = 'file:///android_asset/www/posts.html';
                                                }
                                                else{
                                                    $("#danger").html(dat);
                                                    $("#danger").css("color","red");    
                                                }
                                            },
                                        error: function () {
                                        }
                            });
                                return false;
                            });
                    });

I want user to directly redirect to the application once he click on login button if he is already registered and loged in.

GorillaPatch
  • 5,007
  • 1
  • 39
  • 56
Wagh
  • 4,202
  • 5
  • 39
  • 62
  • 1
    One remark: I would NOT switch off cross site request forgery protection for such an important view as a login view. It is just dangerous. When making AJAX queries it can be easier to include the custom X-CSRFToken HTML header to pass back the token to the originating view. The CSRF token can be acquired from a special cookie as described here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax – GorillaPatch Jul 17 '14 at 06:10
  • if i add csrf_token its not going to the view because i am getting the valus from input text box in html and sending that values to view through ajax. So i don't know how to use csrf there. For normal django form i know how to do that. – Wagh Jul 17 '14 at 06:33
  • 1
    As I said. Get the CSRF token value from the cookie and then set the custom X-CSRFtoken HTTP header on your AJAX request. Take a look at the accepted answer of this question: http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request – GorillaPatch Jul 17 '14 at 08:54

2 Answers2

1

Which view is called when the user clicks the login button? Is the login_android view called when the user clicks the login button? If yes, add these lines at the beginning of the view:

from django.conf import settings
def login_android(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        #if the redirect URL is not part of the Django app and you do not know where auth.login(request, user) redirects to, then try
        #user = request.user
        #auth.login(request, user)

This checks if the user is already logged in, and if he is, it will redirect him to whatever

auth.login(request, user)

redirects to. Just change up the

return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)

line to redirect to the URL of the application (I'm not sure what you made the URL of the application to be).

SilentDev
  • 20,997
  • 28
  • 111
  • 214
  • where should i add this lines from django.conf import settings def login_android(request): if request.user.is_authenticated(): return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) – Wagh Jul 17 '14 at 06:39
  • @GauravWagh which view is called when the login button is clicked? – SilentDev Jul 17 '14 at 06:41
  • login_android view after he clicks on login view – Wagh Jul 17 '14 at 06:42
  • @GauravWagh add 'from django.conf import settings' at the beginning of your views.py and add "if request.user.is_authenticated(): return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)" at the beginning of the login_android view (right before the "print 'i am in view'" line) – SilentDev Jul 17 '14 at 06:44
  • but it will not work. because in ajax success function i am redirecting to the one seprate html page which is not is not included in django application. its in android application. – Wagh Jul 17 '14 at 06:48
  • @GauravWagh what does auth.login(request,user) redirect to? – SilentDev Jul 17 '14 at 06:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57466/discussion-between-user2719875-and-gaurav-wagh). – SilentDev Jul 17 '14 at 06:50
0

Here you can do one thing while registering you can redirect the user to main application page. So user will automatically get log in. try this

if request.method == "POST":
        print "you are in method"
        username = request.POST['name']
        password = request.POST['password']
        login_api(request,username,password)
        user = auth.authenticate(username=username,password=password)

        if user==None:

            dict = {'username': 'Wrong username or password'}
            response = json.dumps(dict)
            return HttpResponse(response, mimetype="application/json")
        else:
            response = json.dumps((model_to_dict(user)), cls=DjangoJSONEncoder)
            return HttpResponse(response, mimetype="application/json")

And do required changes in ajax request.

Wagh
  • 4,202
  • 5
  • 39
  • 62