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

userEmail저장까지

parent 8447fada
import React from 'react'
import { Navbar, Nav, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { handleLogout } from '../utils/auth';
import { handleLogout, isAuthenticated } from '../utils/auth';
function Menu() {
const userName = "정연우";
const user = isAuthenticated()
return (
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="/home">YDK Messenger</Navbar.Brand>
{user ?
<>
<div className='ml-1 mr-2' style={{ color: 'white' }}>{userName} 환영합니다</div>
<Nav className="mr-auto">
<Nav.Link href="/home">Home</Nav.Link>
<Nav.Link href="/profile">Profile</Nav.Link>
<Nav.Link href="/hello">Hello</Nav.Link>
</Nav>
<Link to="./login">
<Button onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
</Link>
<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>
)
}
......
//로그인 한 사람만 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
import catchErrors from '../utils/catchErrors'
import { Link, Redirect } from 'react-router-dom'
import { handleLogin } from '../utils/auth'
import Menu from '../Components/Menu';
const INIT_USER = {
email: '',
......@@ -46,9 +47,10 @@ function LogIn() {
try {
setLoading(true)
setError('')
await axios.post('/auth/login', user)
const response = await axios.post('/auth/login', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
handleLogin(user)
console.log(user.email)
handleLogin(user.email)
setSucces(true)
} catch (error) {
catchErrors(error, setError)
......@@ -69,9 +71,7 @@ function LogIn() {
return (
<>
{/* <Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar> */}
<Menu />
<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">
......
......@@ -3,6 +3,7 @@ import axios from 'axios'
import { Button, Form, Container, Navbar, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom';
import Menu from '../Components/Menu';
const INIT_USER = {
username: '',
......@@ -40,6 +41,7 @@ function SingUp() {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
//event.stopPropagation() : 이벤트 캡쳐링과 버블링에 있어 현재 이벤트 이후의 전파를 막습니다.
}
setValidated(true);
// console.log(user)
......@@ -78,9 +80,7 @@ function SingUp() {
return (
<>
{/* <Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar> */}
<Menu />
<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">
......
import axios from "axios"
//자동으로 localstorage에 login이 생성됨
export function handleLogin(props) {
localStorage.setItem('user', JSON.stringify({email: props.email}))
export function handleLogin(userEmail) {
localStorage.setItem('user', userEmail)
// localStorage.setItem('user', JSON.stringify({email: props.email}))
}
export async function handleLogout() {
localStorage.removeItem('user')
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) => {
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
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 : 노출되면 안됨. 문자열
//expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기
......@@ -39,7 +39,7 @@ const login = async (req, res) => {
secure: config.env === 'production',
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
})
res.send('Login Successful')
res.send({ userEmail: user.email})
} else {
// 5) 비밀번호가 틀리면 에러 반환
......
......@@ -68,9 +68,6 @@ const signup = async (req, res) => {
//res는 한번만 실행. 두번하면 에러 발생
}
const hello = (req, res) => {
res.send('Hello from users controller')
}
export default { signup, hello }
export default { signup }
// {} : 객체로 return함
\ No newline at end of file
......@@ -6,7 +6,7 @@ const router = express.Router()
router.route('/users/signup')
.post(userCtrl.signup)
.get(userCtrl.hello)
// /api/users/signup로 들어오는 것을 post (method) 를 통해 useCtrl.signup 이것이 처리함
//browser에서 주소창에 치고 들어가면 get (method) 을 타고 들어간것임
......
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