ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [HOC] - 인증체크
    React/프로젝트 2022. 1. 26. 22:58
    HOC?
    Higher Order Component

    다른 컴포넌트를 받아 새로운 컴포넌트 리턴한다.

    const EnhancedComponent = 
        higherOrderComponent(WrappedComponent);

    HOC 예시

    => 서버에 auth 요청 후 유저의 상태 확인 후

    로그인 유저인지, 비로그인 유저인지, 어드민 유저인지..등 판별

    => 접근 자격이 된다면 해당 페이지로 이동하고

    아니라면 다른 페이지로 보내버린다. 

     

    auth logic
    // auth.js
    
    import React, { useEffect } from "react";
    import { useDispatch, useSelector } from "react-redux";
    import { auth } from "../_actions/user_actions";
    
    export default function (SpecifiComponent, option, adminRoute = null ) {
    // App.js에서 전달하는 값 확인
    // option
    // null => 아무나 출입이 가능한 페이지
    // true => 로그인한 유저만 출입이 가능
    // false => 로그인한 유저는 출입 불가능
    
        function AuthenticationCheck(props) {
            let user = userSelector((state) => state.user);
            const dispatch = useDispatch();
            
            useEffect(() => {
            
                const dispatch(auth()).then((response) => {  // action 전달 (auth)
                    // login하지 않은 상태
                    if(!resopnse.payload.isAuth) {
                        // option이 true인 페이지에 접근 시
                        if(option) {
                            props.history.push("./login");
                        }
                    } else {
                    // login한 상태
                        if(adminRoute && !response.payload.isAdmin) {
                            props.history.push("/");
                        } else {
                            // option이 false인 페이지에 접근 시
                            if(option === false) props.history.push("/");
                        }
                    }
                });
            }, []);
            
            return <SpecifiComponent {...props} user={user} />
        }
        
        return AuthenticationCheck;
    }
    // auth.js
    
    export function auth() {
        const request = axios
             .get("/api/users/auth")  // 서버 요청
             .then((response) => response.data);  // auth.js에 전달(response)
             
         return {
             type: AUTH_USER,
             payload: request  // 서버 응답 결과 => reducer 전달
         }
     }
    // user_reducer.js
    
    export default function (state = {}, action ) {
        switch(action.type) {
            case LOGIN_USER:
                return {
                    ...state,
                    loginSuccess: action.payload,
                }
                break;
            
            // REGISTER_USER
            //...
            
            
            case AUTH_USER:
                return {
                    ...state,
                    userData: action.payload,  // store 저장
                };
                break;
                
           default:
               return state;
           }
       }
    // auth component로 다른 컴포넌트 감싸기
    // hoc(wrappedComponent)
    
    // app.js
    
    import React from "react";
    import { Switch, Route } from "react-router-dom";
    import  Auth from "../hoc/auth";
    
    function App() {
        return (
            <div>
                <Switch>
                    <Route exact path="/" component={Auth(LandingPage, null)} />
                    <Route path="/login" component={Auth(LoginPage, false)} />
                    <Route path="/register" component={Auth(RegisterPage, false)} />
                    ...
                </Switch>
            </div>
        );
    }
    
    export default App;

    'React > 프로젝트' 카테고리의 다른 글

    event.target vs event.currentTarget 차이  (0) 2022.02.10
    [react-dropzone] - 비디오 업로드  (0) 2022.02.04
    [redux 활용] - LOGIN  (0) 2022.01.26
    [redux] - store 생성  (0) 2022.01.26
    [Redux]  (0) 2022.01.26
Designed by Tistory.