본문 바로가기
Study/Node&React_basic

[노드/리액트 기초] #33~34. 인증 체크 // 완강★

by 이지이즤 2022. 2. 10.

**본 포스팅은 유튜브&인프런 John Ahn님의 노드 리액트 기초 강의를 참고하여 작성하였습니다.**

 

 

Authentication Check

 

 

HOC (Higher Order Component)

다른 component를 받아서 새로운 component를 return하는 function 이다.
2022.02.05 - [Study/Node&React_basic] - [노드/리액트 기초] #18~20. CRA 구조, Boilerplate, React Router Dom

backend에 request를 날려서 그 사람의 현재 상태를 가져온다.
해당 유저가 해당 페이지에 들어갈 자격이 되는지 체크한 후 component로 보내준다.

로그인 전
로그인 후

// auth.js
export default function (SpecificComponent, option, adminRoute = null){
    /*
    option
        null : 아무나 출입이 가능한 페이지
        true : 로그인한 유저만 출입이 가능한 페이지
        false: 로그인한 유저는 출입 불가능한 페이지
    */


    function AuthenticationCheck(props){

        const dispatch = useDispatch();
        const navigate = useNavigate();

        useEffect(() => {

            dispatch(auth()).then(response => {
                console.log(response)

                //로그인 하지 않은 상태
                if(!response.payload.isAuth){
                    if(option){ 
                        navigate("/login");
                    }
                }else{
                    //로그인 한 상태
                    if(adminRoute && !response.payload.isAdmin){
                        navigate('/');
                    }else{
                        if(option === false)
                            navigate('/');
                    }
                }
            })
        }, [])

        return(
            <SpecificComponent />
        )

    }
    return AuthenticationCheck
}

댓글