Commit a3d225ab authored by 우지원's avatar 우지원
Browse files

userEmail저장까지

parent 8447fada
import React from 'react' import React from 'react'
import { Navbar, Nav, Button } from 'react-bootstrap'; import { Navbar, Nav, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom'; import { handleLogout, isAuthenticated } from '../utils/auth';
import { handleLogout } from '../utils/auth';
function Menu() { function Menu() {
const userName = "정연우"; const userName = "정연우";
const user = isAuthenticated()
return ( return (
<Navbar bg="dark" variant="dark"> <Navbar bg="dark" variant="dark">
<Navbar.Brand href="/home">YDK Messenger</Navbar.Brand> <Navbar.Brand href="/home">YDK Messenger</Navbar.Brand>
<div className='ml-1 mr-2' style={{ color: 'white' }}>{userName} 환영합니다</div>
<Nav className="mr-auto"> {user ?
<Nav.Link href="/home">Home</Nav.Link> <>
<Nav.Link href="/profile">Profile</Nav.Link> <div className='ml-1 mr-2' style={{ color: 'white' }}>{userName} 환영합니다</div>
<Nav.Link href="/hello">Hello</Nav.Link> <Nav className="mr-auto">
</Nav> <Nav.Link href="/home">Home</Nav.Link>
<Link to="./login"> <Nav.Link href="/profile">Profile</Nav.Link>
<Button onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button> <Nav.Link href="/hello">Hello</Nav.Link>
</Link> </Nav>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
</>
: <Nav className="ml-auto">
<Nav.Link href='/login'>로그인</Nav.Link>
<Nav.Link href='/signup'>회원가입</Nav.Link>
</Nav>}
</Navbar> </Navbar>
) )
} }
......
//로그인 한 사람만 route로 이동할 수 있도록 함
import React from 'react'
import { Redirect, Route } from 'react-router-dom'
import { isAuthenticated } from '../utils/auth'
function PrivateRoute({path, children}) {
if (isAuthenticated()) {
//로그인이 됬을 시 정상적으로 작동
return (
<Route path={path}>
{children}
</Route>
)
} else {
//로그인이 되지 않았을 시 로그인페이지로 이동
return (
<Redirect to='./login' />
)
}
}
export default PrivateRoute
...@@ -4,6 +4,7 @@ import { Button, Form, Container, Navbar, Spinner, Alert } from 'react-bootstrap ...@@ -4,6 +4,7 @@ import { Button, Form, Container, Navbar, Spinner, Alert } from 'react-bootstrap
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { Link, Redirect } from 'react-router-dom' import { Link, Redirect } from 'react-router-dom'
import { handleLogin } from '../utils/auth' import { handleLogin } from '../utils/auth'
import Menu from '../Components/Menu';
const INIT_USER = { const INIT_USER = {
email: '', email: '',
...@@ -46,9 +47,10 @@ function LogIn() { ...@@ -46,9 +47,10 @@ function LogIn() {
try { try {
setLoading(true) setLoading(true)
setError('') setError('')
await axios.post('/auth/login', user) const response = await axios.post('/auth/login', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음. // 알아서 stringify하기 때문에 따로 해줄 필요 없음.
handleLogin(user) console.log(user.email)
handleLogin(user.email)
setSucces(true) setSucces(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -69,9 +71,7 @@ function LogIn() { ...@@ -69,9 +71,7 @@ function LogIn() {
return ( return (
<> <>
{/* <Navbar bg="dark" variant="dark"> <Menu />
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar> */}
<Form noValidate validated={validated} onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'> <Form noValidate validated={validated} onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'>
<Container className="d-flex justify-content-center"> <Container className="d-flex justify-content-center">
......
...@@ -3,6 +3,7 @@ import axios from 'axios' ...@@ -3,6 +3,7 @@ import axios from 'axios'
import { Button, Form, Container, Navbar, Alert } from 'react-bootstrap'; import { Button, Form, Container, Navbar, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import Menu from '../Components/Menu';
const INIT_USER = { const INIT_USER = {
username: '', username: '',
...@@ -40,6 +41,7 @@ function SingUp() { ...@@ -40,6 +41,7 @@ function SingUp() {
if (form.checkValidity() === false) { if (form.checkValidity() === false) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
//event.stopPropagation() : 이벤트 캡쳐링과 버블링에 있어 현재 이벤트 이후의 전파를 막습니다.
} }
setValidated(true); setValidated(true);
// console.log(user) // console.log(user)
...@@ -78,9 +80,7 @@ function SingUp() { ...@@ -78,9 +80,7 @@ function SingUp() {
return ( return (
<> <>
{/* <Navbar bg="dark" variant="dark"> <Menu />
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar> */}
<Form noValidate validated={validated} onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'> <Form noValidate validated={validated} onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'>
<Container className="d-flex justify-content-center"> <Container className="d-flex justify-content-center">
......
import axios from "axios" import axios from "axios"
//자동으로 localstorage에 login이 생성됨 //자동으로 localstorage에 login이 생성됨
export function handleLogin(props) { export function handleLogin(userEmail) {
localStorage.setItem('user', JSON.stringify({email: props.email})) localStorage.setItem('user', userEmail)
// localStorage.setItem('user', JSON.stringify({email: props.email}))
} }
export async function handleLogout() { export async function handleLogout() {
localStorage.removeItem('user') localStorage.removeItem('user')
await axios.get('/auth/logout') await axios.get('/auth/logout')
//login페이지로 이동
window.location.href='/login'
}
//login이 됬는지 안됬는지 따질때 쓰임
export function isAuthenticated() {
const userEmail = localStorage.getItem('user')
if (userEmail) {
return userEmail
} else {
return false
}
} }
\ No newline at end of file
...@@ -25,7 +25,7 @@ const login = async (req, res) => { ...@@ -25,7 +25,7 @@ const login = async (req, res) => {
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장 // 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
if (passwordMatch) { if (passwordMatch) {
//토큰 생성 //토큰 생성
const token = jwt.sign({ userId: user._id }, config.jwtSecret, {expiresIn: '7d'}) const token = jwt.sign({ userEmail: user.email}, config.jwtSecret, {expiresIn: '7d'})
//jwtSecret : 노출되면 안됨. 문자열 //jwtSecret : 노출되면 안됨. 문자열
//expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기 //expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기
...@@ -39,7 +39,7 @@ const login = async (req, res) => { ...@@ -39,7 +39,7 @@ const login = async (req, res) => {
secure: config.env === 'production', secure: config.env === 'production',
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음. //secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
}) })
res.send('Login Successful') res.send({ userEmail: user.email})
} else { } else {
// 5) 비밀번호가 틀리면 에러 반환 // 5) 비밀번호가 틀리면 에러 반환
......
...@@ -68,9 +68,6 @@ const signup = async (req, res) => { ...@@ -68,9 +68,6 @@ const signup = async (req, res) => {
//res는 한번만 실행. 두번하면 에러 발생 //res는 한번만 실행. 두번하면 에러 발생
} }
const hello = (req, res) => {
res.send('Hello from users controller')
}
export default { signup, hello } export default { signup }
// {} : 객체로 return함 // {} : 객체로 return함
\ No newline at end of file
...@@ -6,8 +6,8 @@ const router = express.Router() ...@@ -6,8 +6,8 @@ const router = express.Router()
router.route('/users/signup') router.route('/users/signup')
.post(userCtrl.signup) .post(userCtrl.signup)
.get(userCtrl.hello)
// /api/users/signup로 들어오는 것을 post (method) 를 통해 useCtrl.signup 이것이 처리함 // /api/users/signup로 들어오는 것을 post (method) 를 통해 useCtrl.signup 이것이 처리함
//browser에서 주소창에 치고 들어가면 get (method) 을 타고 들어간것임 //browser에서 주소창에 치고 들어가면 get (method) 을 타고 들어간것임
//post를 띄우고 싶으면 앱에서 ARC실행해서 post를 실행하게 만들면됨. //post를 띄우고 싶으면 앱에서 ARC실행해서 post를 실행하게 만들면됨.
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment