简体   繁体   中英

Django, successful login, but still anonymous user

Being anonymous user even after successful login, here is views.py:

class LoginView(views.APIView):
    def post(self, request):
        data = serializers.LoginSerializer(data=request.data)
        print(data.is_valid())
        print(data.errors)
        print(f" HEEERE::: {data}")
        if self.request.method == 'POST':
            if data.is_valid():
                auth = authenticate(
                    username=data.validated_data['email'], password=data.validated_data['password'])
                print(f" email check : {data.validated_data['email']}")
                print(f"auth:: {auth}")
                if auth is not None:
                        login(request, auth)
                        print("Hello World")
                        return redirect("/somelink")

                else:
                    return HttpResponse("Invalid Credentials")
            else:
                return HttpResponse("Data not being validated :O")


class LogoutView(views.APIView):
    def post(self, request):
        logout(request)

serializers.py

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)
    def validate(self, data):
        email = data.get("email")
        print(f" email here : {email}")
        password = data.get("password")
        user = authenticate(username=email, password=password)
        print(f"{user} username serializer ")
        print(f"this is data : {data}")
        if user is not None:
            return data
        raise serializers.ValidationError("Incorrect Credentials")

in frontend side (React): login component:

import React, { useState } from 'react';
import { Link , Redirect} from 'react-router-dom';
import { connect } from 'react-redux';
import { login } from '../actions/auth';
import axios from 'axios';
import Cookies from 'js-cookie';


function Login(){
    let [login,setLogin,isLoggedin] = useState({
        email: '',
        password:''

    });
    let cookie = Cookies.get('csrftoken');
    const { email, password } = login;
    function handleChange(e){
        console.log(e.target.value);
        setLogin({
            ...login,
            [e.target.name]: e.target.value
        });

    }
    function handleSubmit(e){
        e.preventDefault();
        axios.post(' http://127.0.0.1:8000/login/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*'}})
        .then(res => {
            console.log(res.data);
            setLogin({
                ...login,
            })
        })
    }

    
    return (
        <div className="container">
        <form method='post' onSubmit={handleSubmit}>
            <h1>Login</h1>
            <label>
                Email:
                <input type='text' name = 'email' value={email} onChange={e=>handleChange(e)} required/>

            </label>
            <label>
                Password:
                <input type='password' name = 'password' value={password} onChange={e=>handleChange(e)} required/>
            </label>
            {isLoggedin = true}
            <button type='submit'>Login</button>
        </form>
            <p className='mt-3'>
                Don't have an Account? <Link to='/signup'>Sign Up</Link>
            </p>
        </div>
    );
};

I am using sessions based authentication, which is implemented by default in django, I have sent a request of cookie as header to ensure the authentication process, yet i am viewed as anonymous user by django, everything in network tab is working fine though.

I don't know anything about react logic, but in Vue you can post the state in store/index.js so, you can store the Authentication state there as boolean set to False, when user logs in and server responds with code 200, it turns to True.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM