反应应用程序的登录身份验证

时间:2021-07-12 06:09:29

标签: reactjs django

我正在为我的单页应用程序使用基于 Django 会话的身份验证。我使用以下 API 来处理登录和注销功能。我已经使用 axios 从这些 API 获取响应。

url.py

from django.urls import path

from . import views

login.tsx

const authentication = {
    LoggedIn: false,
    onAuthentication(){
      this.LoggedIn= true;
    },
    getLogInStatus(){
      return this.LoggedIn;
    }
  }
  

const PrivateRoute = (props) => {
    return (
        <Route path= {props.path} render={data=>authentication.getLogInStatus()?(
        <props.component {...data}></props.component>):
        (<Redirect to = {{pathname: '/'}}></Redirect>)}> </Route>

    )
  }


class Login extends React.Component <any, any>{
    constructor(props:  any) {
        super(props)

        this.state = {
            username: '',
            password: '',
            isLoggenIn: false
        }
    }

    changeHandler = (e: any) => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = (e: any) => {
        e.preventDefault()
        console.log(this.state)
        axios
            .post('/api/login/', this.state)
            .then(response => {
                if(response.status === 200){
                    authentication.onAuthentication();
                    this.setState({ isLoggedIn: true });
                }
                else if (response.status === 204) {
                    this.props.showError("Username and password do not match");   
                }
                else {
                    this.props.showError("Username does not exists");
                }
            })
            .catch(error => {
                alert("Invalid credentials")
                console.log(error)
            })
    }


    render() {
        if (this.state.isLoggedIn) {
            // redirect to home if logged in
            return <Redirect to = {{ pathname: "/home" }} />;
          }
          
            const { username, password} = this.state

                return ()

urls.py

urlpatterns = [
    path('csrf/', views.get_csrf, name='api-csrf'),
    path('login/', views.login_view, name='api-login'),
    path('logout/', views.logout_view, name='api-logout'),
    path('session/', views.session_view, name='api-session'),
    path('whoami/', views.whoami_view, name='api-whoami'),
]

现在我想在我的反应应用程序中添加登录/身份验证逻辑,即如果用户有会话,则用户应重定向到主页,否则应重定向到登录页面。我如何实现相同的身份验证逻辑?

views.py

from django.http import JsonResponse
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView


class SessionView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    @staticmethod
    def get(request, format=None):
        return JsonResponse({'isAuthenticated': True})


class WhoAmIView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    @staticmethod
    def get(request, format=None):
        return JsonResponse({'username': request.user.username})

0 个答案:

没有答案