개발자를 향해...
[노드 리액트 강의 기초] #32 로그아웃 ~ #34 인증 체크 (2) 강의 마무리. 본문
웹 자바스크립트 공부/ReactJS + node.js
[노드 리액트 강의 기초] #32 로그아웃 ~ #34 인증 체크 (2) 강의 마무리.
eugeneHwang1124 2021. 2. 21. 04:53728x90
반응형
#32 로그아웃
랜딩 페이지에 로그아웃 버튼을 추가한다.
import React, { useEffect } from 'react'
import axios from 'axios';
import { withRouter } from 'react-router-dom';
function LandingPage(props) {
useEffect(() => {
axios.get('/api/hello')
.then(response => { console.log(response) })
}, [])
const onClickHandler = () => {
axios.get(`/api/users/logout`)
.then(response => {
if (response.data.success) {
props.history.push("/login")
} else {
alert('로그아웃 하는데 실패 했습니다.')
}
})
}
return (
<div style={{
display: 'flex', justifyContent: 'center', alignItems: 'center'
, width: '100%', height: '100vh'
}}>
<h2>시작 페이지</h2>
<button onClick={onClickHandler}>
로그아웃
</button>
</div>
)
}
export default withRouter(LandingPage)
#33
페이지들에 권한이 있는 회원만 접근 가능하도록 컨트롤한다.
import React, { useEffect } from 'react';
import Axios from 'axios';
import { useDispatch } from 'react-redux';
import { auth } from '../_actions/user_action';
export default function (SpecificComponent, option, adminRoute = null) {
//null => 아무나 출입이 가능한 페이지
//true => 로그인한 유저만 출입이 가능한 페이지
//false => 로그인한 유저는 출입 불가능한 페이지
function AuthenticationCheck(props) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(auth()).then(response => {
console.log(response)
//로그인 하지 않은 상태
if (!response.payload.isAuth) {
if (option) {
props.history.push('/login')
}
} else {
//로그인 한 상태
if (adminRoute && !response.payload.isAdmin) {
props.history.push('/')
} else {
if (option === false)
props.history.push('/')
}
}
})
}, [])
return (
<SpecificComponent />
)
}
return AuthenticationCheck
}
index에서 auth로 요청을 보내면 여기로 오게 된다.
//null => 아무나 출입이 가능한 페이지 |
//true => 로그인한 유저만 출입이 가능한 페이지 |
//false => 로그인한 유저는 출입 불가능한 페이지 |
import './App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import LandingPage from './components/views/LandingPage/LandingPage'
import LoginPage from './components/views/LoginPage/LoginPage'
import RegisterPage from './components/views/RegisterPage/RegisterPage'
import Auth from './hoc/auth'
function App() {
return (
<div className="App">
<Router>
<div>
<Switch>
<Route exact path="/" component={Auth(LandingPage, null ) } />
<Route exact path="/login" component={Auth(LoginPage, false) } />
<Route exact path="/register" component={Auth(RegisterPage, false)} />
</Switch>
</div>
</Router>
</div>
);
}
export default App;
#34 인증 체크 (2) 강의 마무리.
LoginPagedhk RegisterPage 에서 마지막 export 부분을
export default withRouter(LoginPage) 이런 형식으로 수정한다.
auth.js도 다음 부분을 추ㅏ한다.
//로그인 하지 않은 상태
if (!response.payload.isAuth) {
if (option) {
props.history.push('/login')
}
} else {
//로그인 한 상태
if (adminRoute && !response.payload.isAdmin) {
props.history.push('/')
} else {
if (option === false)
props.history.push('/')
}
}
반응형