django通过邮递员登录

时间:2018-07-06 11:14:17

标签: python django

我完成的操作是在请求中输入json

{ “ username”:“ nimish”, “ password”:“ mypassword” }

并在视图中

@csrf_exempt
def LoginView(request):
    if request.method == "GET":
        return HttpResponse(json.dumps({"status": "ERROR",
                                        "errors": ["GET Request not allowed"]
                                        }))
 request_json = json.loads(request.body.decode("utf-8"))
 login(request,authenticate(request,User.objects.get(username=request_json["username"]),request_json["password"]))

但这会导致错误

  

禁止(未设置CSRF cookie)

所以我应该如何继续进行邮递员登录。

当我检查身份验证时是否完成了工作,但登录功能失败

我的真实代码

forms.py

class CustomUserCreationForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = "__all__"


class LoginForm(forms.Form):
    username_email = forms.CharField(max_length=254, required=True)
    password = forms.CharField(max_length=254, required=True)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        self.authenticated_user = None
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        username_email = self.cleaned_data.get("username_email")
        password = self.cleaned_data.get("password")

        print("username is", username_email)
        print("password is", password)

        try:
            username_email = CustomUser.objects.get(email=username_email).username
        except ObjectDoesNotExist:
            pass

        self.authenticated_user = authenticate(request=self.request, username=username_email, password=password)
        print(self.authenticated_user)
        if self.authenticated_user:
            print("authenticated")
            print("user is ", self.request.user)
            print(self.request.COOKIES)
            # print(self.request.META.keys())
            # print("csrf token is ",self.request.META["csrftoken"])
            z = login(self.request, self.authenticated_user)
            print(type(z))
            #see help file
            print("user is", self.request.user)
        print("ok")

models.py

class CustomUser(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    email = models.EmailField(max_length=200, unique=True)
    username = models.CharField(max_length=200, unique=True)
    password = models.CharField(max_length=400)
    type = models.ForeignKey(Group, on_delete=models.CASCADE)
    email_verified = models.BooleanField(default=False)

    def __str__(self):
        return self.first_name

views.py

HOSTNAME = "http://127.0.0.1:8000/"
VERIFICATION_DOMAIN = HOSTNAME + "accounts/verifyEmail/?token_id="


def generate_activation_key(username):
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
    secret_key = get_random_string(30, chars)
    return hashlib.sha256((secret_key + username).encode('utf-8')).hexdigest()


def get_errors(errors, ob):
    for a in ob:
        if a.errors:
            errors.append({a.name: a.errors.as_text()})
    return errors


@csrf_exempt
def CreateCustomUserView(request):
    if request.method == "GET":
        return HttpResponse(json.dumps({"status": "ERROR",
                                        "errors": ["GET Request not allowed"]
                                        }))
    request_data = json.loads(request.body.decode("utf-8"))
    ob = CustomUserCreationForm(request_data)  # when postman
    # ob = CustomUserCreationForm(request.POST)  # when ajax

    errors = []
    try:
        errors = get_errors(errors, ob)
        if ob.non_field_errors():
            errors.append(ob.non_field_errors().as_json())

        custom_user = ob.save()
        data_dictionary = {
            "username": custom_user.username,
            "email": custom_user.email,
            "password": custom_user.password,
            "first_name": custom_user.first_name
        }
        if "last_name" in request_data:
            data_dictionary["last_name"] = custom_user.last_name

        original_user = "null"
        original_user = User.objects.create_user(**data_dictionary)
        print("original user is", original_user)

        #       HASH PASSWORD IN CUSTOM_USER
        custom_user.password = original_user.password
        custom_user.save()

        email_token = EmailVerificationLink.objects.create(user=custom_user,
                                                           activation_id=generate_activation_key(custom_user.username))

        email_verification_link = VERIFICATION_DOMAIN + email_token.activation_id

        #       SEND EMAIL TO USER
        email = EmailMessage('This is the subject',
                             "click the link to activate " + email_verification_link,
                             to=['your@email.com'])
        email.send()

        print("Message Sent")

        data = {
            "status": "Success",
            "data": {
                "first_name": custom_user.first_name,
                "id": custom_user.id,
                "email": custom_user.email,
                "username": custom_user.username,
                # "activation_link": email_verification_link
            }
        }

        response = HttpResponse(json.dumps(data))
        response['Content-Type'] = "application/json"
        return response

    except Exception as E:
        print("error is ", E)
        data = {
            "status": "ERROR",
            "errors": errors
        }

        response = HttpResponse(json.dumps(data))
        response['Content-Type'] = "application/json"
        return response





@ensure_csrf_cookie
def LoginView(request):
    print("user is", request.user)
    if request.method == "GET":
        return HttpResponse(json.dumps({"status": "ERROR",
                                        "errors": ["GET Request not allowed"]
                                        }))

    # ob = LoginForm(json.loads(request.body.decode("utf-8")), request=request)  # when postman
    ob = LoginForm(request.POST, request=request)  # when ajax
    # ob = LoginForm(request.POST, request=request)  # when ajax
    print("errors area")
    errors = []
    try:
        errors = get_errors(errors, ob)
        if ob.non_field_errors():
            errors.append(ob.non_field_errors().as_json())

        #       Clean of LoginForm called
        print('errors are', ob.non_field_errors())

        print("user is", ob.authenticated_user)

        if ob.authenticated_user:
            data = {
                "status": "Success",
                "Message": "Succesfully Logged in as " + ob.authenticated_user.first_name
            }

            response = HttpResponse(json.dumps(data))
            response['Content-Type'] = "application/json"
            return response

        else:
            data = {
                "status": "Failed",
                "Message": "Incoorect Credentials"
            }
            response = HttpResponse(json.dumps(data))
            response['Content-Type'] = "application/json"
            return response


    except Exception as E:
        print("error is ", E)
        data = {
            "status": "ERROR",
            "errors": errors
        }
        response = HttpResponse(json.dumps(data))
        response['Content-Type'] = "application/json"
        return response

和ajax调用就像

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});
$.ajax({
        url: "http://127.0.0.1:8000/accounts/loginq/",
        type: "POST",
        async: true,
        data: {
    "username_email":"my_username",
    "password":"rkewjrhkjwrhwejwkrnwjkr"
},
        error: function (e) {},
        success: function (data) {
                console.log(data);
            }
    });

简而言之,我要做的是代替继承抽象用户,我创建了一个自定义用户模型,并且没有一对一映射,而是创建了用户,密码和电子邮件,并将相同的详细信息传递给了django用户模型,登录时我所做的是如果用户提供用户名和密码,它将直接进行身份验证,否则,如果他通过电子邮件,我将找到与该电子邮件相对应的用户名,然后使用找到的用户名登录该用户。我必须以一点荒唐的方式做,因为不允许使用模板

1 个答案:

答案 0 :(得分:0)

是的,我的坏处是我实际使用的

from django.contrib.auth.views import login

代替

from django.contrib.auth import login

使用auth登录而不是auth.views解决了我的问题