Commit 984a1deb authored by 우지원's avatar 우지원
Browse files

Merge remote-tracking branch 'origin/young' into jiweon827

parents 0afa135b d80d2238
import React, { useEffect, useState } from 'react'; import React from 'react';
import { Form, Button, Row } from 'react-bootstrap'; import { Form, Button, Row } from 'react-bootstrap';
import axios from "axios";
function Chat(props) { function Chat(props) {
const [username, setUsername] = useState('') let defaultname = sessionStorage.getItem('name');
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
...@@ -16,23 +15,15 @@ function Chat(props) { ...@@ -16,23 +15,15 @@ function Chat(props) {
props.sendMsg(e) props.sendMsg(e)
} }
async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
const userid = sessionStorage.getItem('user')
const response = await axios.post(`/users/${userid}`, { '_id': userid })
setUsername(response.data.username)
}
useEffect(() => {
getLoginedUser()
console.log('Chat에서 useEffect', username)
})
return ( return (
<div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}> <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}>
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button> <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<h2>현재 {props.roomName} 입니다.</h2> <h2>현재 {props.roomName} 입니다.</h2>
{ props.chatmsg.map((value, index) => ( { props.chatmsg.map((value, index) => (
<Row key={index} className='ml-3'> <Row key={index} className='ml-3'>
{props.roomName}에서 {username}님이 보낸 메세지 : {value} {props.roomName}에서 {defaultname}님이 보낸 메세지 : {value}
</Row> </Row>
))} ))}
...@@ -40,15 +31,6 @@ function Chat(props) { ...@@ -40,15 +31,6 @@ function Chat(props) {
<Form.Control name='msg' type='text' onChange={handleChange} /> <Form.Control name='msg' type='text' onChange={handleChange} />
<Button variant="primary" type="submit">전송</Button> <Button variant="primary" type="submit">전송</Button>
</Form> </Form>
<Form>
<Form.Group>
<Form.Control type="text" />
</Form.Group>
<Button variant="primary" type="submit">
전송
</Button>
</Form>
</div> </div>
......
import axios from 'axios'; import React, { useState, useEffect } from 'react'
import React, { useState, useEffect } from 'react';
import { Navbar, Nav, Button } from 'react-bootstrap'; import { Navbar, Nav, Button } from 'react-bootstrap';
import { handleLogout, isAuthenticated } from '../utils/auth'; import { Link } from 'react-router-dom';
import { handleLogout } from '../utils/auth';
import axios from 'axios'
function Menu() {
const user = isAuthenticated()
const [userName, setUsername] = useState('')
async function getLoginedUser() {
const userid = sessionStorage.getItem('user')
const response = await axios.get(`/users/${userid}`, { '_id': userid })
console.log(response.data)
const resName = response.data
//const resName = JSON.stringify(response.data.username)
console.log(resName)
setUsername(resName)
}
console.log(userName.username)
useEffect((user) => { function Menu() {
if (sessionStorage.getItem('user')) {
getLoginedUser(user)
}
}, [])
const name = sessionStorage.getItem('name');
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' }}>{name} 환영합니다</div>
{user ? <Nav className="mr-auto">
<> <Nav.Link href="/home">Home</Nav.Link>
<div className='ml-1 mr-2' style={{ color: 'white' }}>{userName.username} 환영합니다</div> <Nav.Link href="/profile">Profile</Nav.Link>
<Nav className="mr-auto"> <Nav.Link href="/hello">Hello</Nav.Link>
<Nav.Link href="/home">Home</Nav.Link> </Nav>
<Nav.Link href="/profile">Profile</Nav.Link> <Link to="./login">
<Nav.Link href="/hello">Hello</Nav.Link> <Button onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
</Nav> </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> </Navbar>
) )
} }
......
import { Button, Navbar, Nav } from 'react-bootstrap';
import React from 'react'
const userName = "정연우";
function Hello(props) {
console.log(props)
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="/homepage">YDK Messenger</Navbar.Brand>
<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>
{/* <Form inline>
<FormControl type="text" placeholder="Search" className="mr-sm-2" />
<Button variant="outline-info">Search</Button>
</Form> */}
<Button variant="light" className="ml-3">Logout</Button>
</Navbar>
<h1>hello</h1>
<div>
안녕하세요.{props.name}
</div>
<input className="input" />
</>
)
}
export default Hello;
...@@ -6,30 +6,26 @@ import ClosedList from '../Components/ClosedList'; ...@@ -6,30 +6,26 @@ import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList'; import OpenList from '../Components/OpenList';
import Chat from '../Components/Chat'; import Chat from '../Components/Chat';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
// import styled from 'styled-components';
import { io } from "socket.io-client"; //모듈 가져오기 import { io } from "socket.io-client"; //모듈 가져오기
// const List = styled.div` // const userName = "정연우";
// background: #FFFAFA;
// `
const userName = "정연우";
const socket = io(); const socket = io();
function Home() { function Home() {
const [username, setUsername] = useState('defaultUser')
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
const [chat, setChat] = useState(false); const [chat, setChat] = useState(false);
const handleClose = () => setShow(false); const handleClose = () => setShow(false);
const handleShow = () => setShow(true); const handleShow = () => setShow(true);
const handleChato = () => setChat(true); const handleChato = () => setChat(true);
const handleChatc = () => setChat(false); const handleChatc = () => setChat(false);
// variant="pills"
const [inner, setInner] = useState(['']) const [inner, setInner] = useState(['']) //인풋값
console.log('sendMsg2222', inner) const [chatmsg, setChatmsg] = useState([inner]) // 전송된 채팅들 저장하는 배열
const [chatmsg, setChatmsg] = useState([inner])
const [roomName, setRoomName] = useState('dd') //방 선택이 방1을 눌럿다 방2를 누르면 전체로 전송됨 const [roomName, setRoomName] = useState('dd') //방 선택이 방1을 눌럿다 방2를 누르면 전체로 전송됨
function enterChatroom(roomName) { //방 입장하기 function enterChatroom(roomName) { //방 입장하기
...@@ -52,7 +48,6 @@ function Home() { ...@@ -52,7 +48,6 @@ function Home() {
} }
useEffect(() => { useEffect(() => {
console.log('useeffect1')
socket.on('broadcast', (msg) => { socket.on('broadcast', (msg) => {
console.log('msg', msg) console.log('msg', msg)
......
...@@ -12,9 +12,7 @@ const INIT_USER = { ...@@ -12,9 +12,7 @@ const INIT_USER = {
} }
function LogIn() { function LogIn() {
//const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
//로딩, 에러, diserved 상태 넣어야됨.
const [disabled, setDisabled] = useState(true) const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSucces] = useState(false) const [success, setSucces] = useState(false)
...@@ -22,35 +20,21 @@ function LogIn() { ...@@ -22,35 +20,21 @@ function LogIn() {
useEffect(() => { useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el)) const isUser = Object.values(user).every(el => Boolean(el))
//Boolean : 참거짓 판별
//every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
//empty string때만 false로 나옴.
isUser ? setDisabled(false) : setDisabled(true) isUser ? setDisabled(false) : setDisabled(true)
}, [user]) }, [user])
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
// console.log(name, value)
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
// const form = event.currentTarget;
// if (form.checkValidity() === false) {
// event.preventDefault();
// event.stopPropagation();
// }
// setValidated(true);
try { try {
setLoading(true) setLoading(true)
setError('') setError('')
const response = await axios.post('/auth/login', user) let res = await axios.post('/auth/login', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음. handleLogin(res.data)
console.log(response.data)
handleLogin(response.data.userId)
setSucces(true) setSucces(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -71,14 +55,13 @@ function LogIn() { ...@@ -71,14 +55,13 @@ function LogIn() {
return ( return (
<> <>
<Menu /> <Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar>
<Form onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'> <Form 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">
<div className="mt-5 p-5 shadow w-75"> <div className="mt-5 p-5 shadow w-75">
<h2 className="text-center">로그인</h2> <h2 className="text-center">로그인</h2>
<Form.Group controlId="formGroupEmail"> <Form.Group controlId="formGroupEmail">
<Form.Label>이메일</Form.Label> <Form.Label>이메일</Form.Label>
<Form.Control <Form.Control
......
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import { Image, Button, Container, Form, FormControl, Navbar, Nav, Row, Col, Dropdown, Carousel } from 'react-bootstrap'; import { Image, Button, Container, Form, Row, Col, Dropdown } from 'react-bootstrap';
import { BrowserRouter as Router, Route, Redirect, Switch, Link } from 'react-router-dom'; import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios' import axios from 'axios'
import userdefault from './KakaoTalk_20201230_153151693.png' import userdefault from '../Images/KakaoTalk_20201230_153151693.png'
import img1 from './img_1.png' import img1 from '../Images/img_1.png'
import img2 from './img_2.png' import img2 from '../Images/img_2.png'
import img3 from './img_3.jpg' import img3 from '../Images/img_3.jpg'
import DropdownItem from 'react-bootstrap/esm/DropdownItem'; import DropdownItem from 'react-bootstrap/esm/DropdownItem';
...@@ -39,13 +38,12 @@ function ProfilePage() { ...@@ -39,13 +38,12 @@ function ProfilePage() {
} else { } else {
setHidden(true) setHidden(true)
} }
console.log(document.cookie)
} }
function handleChange(e) { function handleChange(e) {
setUser({ ...user, 'nickname': e.target.value }) setUser({ ...user, 'nickname': e.target.value })
} }
async function handleNicksave() { async function handleNicksave() {
const userid = sessionStorage.getItem('user') const userid = sessionStorage.getItem('userId')
await axios.put(`/users/${userid}`, user) await axios.put(`/users/${userid}`, user)
} }
...@@ -82,39 +80,29 @@ function ProfilePage() { ...@@ -82,39 +80,29 @@ function ProfilePage() {
} }
} }
useEffect(() => { useEffect(() => {
if (sessionStorage.getItem('user')) { //id뿐만아니라 토큰같은거를 확인 못하나 + 이런식으로 확인해도 되는것도 맞나 getLoginedUser()
getLoginedUser()
}
else {
alert("로그인 후 이용하세요")
window.location.href = '/login'
}
}, []) }, [])
return ( return (
<div> <div>
<Menu /> <Menu />
<Container> <Container className='border' fluid>
<Row><h1>ProfilePage</h1></Row>
<Row><h2>{user.username} 환영합니다 !</h2></Row>
</Container>
<Container className="mt-5 shadow w-75">
<Row> <Row>
<Col sm={4}> <Col sm={4}>
<Row> <Row className='justify-content-center'>
<div className="d-flex justify-content-center mb-3" id="defaultImg"> <div className="d-flex ml-3 mt-3" id="defaultImg">
<Image src={userimg} width="300px" roundedCircle /> <Image src={userimg} width="300px" roundedCircle />
</div> </div>
</Row> </Row>
<Row> <Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex justify-content-center"> <Form className="d-flex">
<Form.Group> <Form.Group>
<div id="image_container"></div> <div id="image_container"></div>
<Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} /> <Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} />
</Form.Group> </Form.Group>
</Form> </Form>
</Row> </Row>
<Row className="d-flex justify-content-center"> <Row className="d-flex justify-content-center mb-3">
<Dropdown> <Dropdown>
<Dropdown.Toggle variant='success' id='dropdown-basic'> <Dropdown.Toggle variant='success' id='dropdown-basic'>
프로필 사진 선택 프로필 사진 선택
...@@ -128,34 +116,35 @@ function ProfilePage() { ...@@ -128,34 +116,35 @@ function ProfilePage() {
</Row> </Row>
</Col> </Col>
<Col sm={8}> <Col sm={8}>
<Row className='m-5 justify-content-center'>
<Row className="m-3 justify-content-flex-start" style={{ fontWeight: "bold", fontSize: "x-large" }}> <h2>{user.username}님의 프로필 정보</h2>
<Col sm={2.5}>이름 :</Col>
<Col sm={8}>{user.username}</Col>
</Row> </Row>
<Row className="m-3 justify-content-flex-start" id="nickname"> <Row className="m-3 justify-content-flex-start" style={{ fontWeight: "bold", fontSize: "large" }}>
<Form className="d-flex" onSubmit={handleSubmit} style={{ fontWeight: "bold", fontSize: "x-large" }}> <Col xs={3}>이름 :</Col>
<Col xs={6}>{user.username}</Col>
<Row> {/* <Col sm={4}></Col> */}
<Col>별명 :</Col>
<Col hidden={!hidden}>
{user.nickname}
</Col>
<Col hidden={hidden}>
<Form.Control defaultValue={user.nickname} style={{width : "110%"}} onChange={handleChange} />
</Col>
<Col>
<Button className="ml-3 d-flex justify-content-end" variant="outline-primary" size="sm" type='submit'>수정</Button>
</Col>
</Row>
</Form>
</Row> </Row>
<Row className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}> <Row className="m-3 justify-content-flex-start" id="nickname" style={{ fontWeight: "bold", fontSize: "large" }}>
<Col sm={2.5}>이메일 : </Col> <Col xs={3}>별명 :</Col>
<Col sm={8}>{user.email}</Col> <Col xs={6} hidden={!hidden}>
{user.nickname}
</Col>
<Col xs={6} hidden={hidden}>
<Form>
<Form.Control defaultValue={user.nickname} style={{ width: "110%" }} onChange={handleChange} />
</Form>
</Col>
<Col xs={3}>
<Form className="d-flex" onSubmit={handleSubmit}>
<Button className="ml-3 d-flex justify-content-end" variant="outline-primary" size="sm" type='submit'>수정</Button>
</Form>
</Col>
</Row> </Row>
<Row className='justify-content-center'> <Row className="m-3" style={{ fontWeight: "bold", fontSize: "large" }}>
<Col xs={3}>이메일 : </Col>
<Col xs={6}>{user.email}</Col>
</Row>
<Row className='m-3 justify-content-center'>
<Form> <Form>
<Button variant="outline-success" size="sm" className="mr-4" onClick={handleNicksave}>저장</Button> <Button variant="outline-success" size="sm" className="mr-4" onClick={handleNicksave}>저장</Button>
<Link to='/'> <Link to='/'>
...@@ -166,94 +155,6 @@ function ProfilePage() { ...@@ -166,94 +155,6 @@ function ProfilePage() {
</Col> </Col>
</Row> </Row>
</Container> </Container>
<Container className="d-flex justify-content-center">
<div className="mt-5 shadow w-75">
<h1 className="text-center mt-4 ml-5 mr-5 mb-3">Profile Page</h1>
<h4 className="text-center mb-5">{user.username} 환영합니다 !</h4>
<div className="d-flex justify-content-center mb-3" id="defaultImg">
<Image src={userimg} width="300px" roundedCircle />
</div>
<Row className="d-flex justify-content-center">
<Form className="d-flex justify-content-center">
<Form.Group>
<div id="image_container"></div>
<Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} />
</Form.Group>
</Form>
</Row>
<Row className="d-flex justify-content-center">
<Dropdown>
<Dropdown.Toggle variant='success' id='dropdown-basic'>
프로필 사진 선택
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item as='button'>홈으로</Dropdown.Item>
<Dropdown.Item href='/'>라이언</Dropdown.Item>
<Dropdown.Item href='/'>어피치</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Row>
{/* <Carousel className="d-flex justify-content-center" style={{ width: "300px", height: "300px" }}>
<Carousel.Item className="d-flex justify-content-center">
<Image
className="d-block w-100"
src={img1}
/>
<Carousel.Caption>
<p style={{color : 'black'}}>펭수입니다.</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image
className="d-block w-100"
src={img2}
/>
<Carousel.Caption>
<p>라이언입니다.</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<Image
className="d-block w-100"
src={img3}
/>
<Carousel.Caption>
<p>어피치 입니다.</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel> */}
<div className="text-center">
<div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이름 : {user.username}</div>
<div className="m-3" id="nickname">
<Form className="d-flex justify-content-center" onSubmit={handleSubmit} style={{ fontWeight: "bold", fontSize: "x-large" }}>
별명 :
<div hidden={!hidden}>
{user.nickname}
</div>
<Form.Control defaultValue={user.nickname} style={{ width: "40%" }} size="sm" onChange={handleChange} hidden={hidden} />
<Button className="ml-3" variant="outline-primary" size="sm" type='submit'>수정</Button>
</Form>
</div>
<div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이메일 : {user.email}</div>
</div>
<div className="text-center m-5">
<Form>
<Button variant="outline-success" size="sm" className="mr-4" onClick={handleNicksave}>저장</Button>
<Link to='/'>
<Button variant="outline-success" size="sm" className="ml-4" > 화면으로</Button>
</Link>
</Form>
</div>
</div>
</Container>
</div> </div>
) )
} }
......
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import axios from 'axios' import axios from 'axios'
import { Button, Form, Container, Navbar, Alert } from 'react-bootstrap'; import { Button, Form, Container, Alert, Navbar } 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'; import Menu from '../Components/Menu';
...@@ -21,15 +21,11 @@ function SingUp() { ...@@ -21,15 +21,11 @@ function SingUp() {
useEffect(() => { useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el)) const isUser = Object.values(user).every(el => Boolean(el))
//Boolean : 참거짓 판별
//every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
//empty string때만 false로 나옴.
isUser ? setDisabled(false) : setDisabled(true) isUser ? setDisabled(false) : setDisabled(true)
}, [user]) }, [user])
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
// console.log(name, value)
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
...@@ -48,23 +44,8 @@ function SingUp() { ...@@ -48,23 +44,8 @@ function SingUp() {
try { try {
setError('') setError('')
// const response = await fetch('/api/users/signup', {
// //post, get같은게 주어지지 않으면 기본적으로 fetch에 get요청함
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(user)
// })
// const data = await response.json()
await axios.post('/users/signup', user) await axios.post('/users/signup', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음. alert("회원가입이 완료되었습니다!")
// console.log(response.data)
console.log(user)
// ?????????hash 처리된 password가 저장되지 않았음
// setUser(INIT_USER)
setSucces(true) setSucces(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -80,7 +61,9 @@ function SingUp() { ...@@ -80,7 +61,9 @@ function SingUp() {
return ( return (
<> <>
<Menu /> <Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar>
<Form onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'> <Form 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">
......
...@@ -2,26 +2,30 @@ import React from 'react'; ...@@ -2,26 +2,30 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css'; import './index.css';
// import App from './App'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import reportWebVitals from './reportWebVitals';
import SignUpPage from './Pages/SignUpPage'; import SignUpPage from './Pages/SignUpPage';
import ProfilePage from './Pages/ProfilePage'; import ProfilePage from './Pages/ProfilePage';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.min.css';
import LogInPage from './Pages/LogInPage'; import LogInPage from './Pages/LogInPage';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import Hello from './Hello'
import HomePage from './Pages/HomePage' import HomePage from './Pages/HomePage'
import PrivateRoute from './Components/PrivateRoute';
ReactDOM.render( ReactDOM.render(
<Router> <Router>
<Switch> <Switch>
<Route exact path="/" component={HomePage} /> <PrivateRoute exact path="/">
<HomePage />
</PrivateRoute>
<Route path="/home" component={HomePage} />
<Route path="/login" component={LogInPage} /> <Route path="/login" component={LogInPage} />
<Route path="/signup" component={SignUpPage} /> <Route path="/signup" component={SignUpPage} />
<Route path="/profile" component={ProfilePage} /> <Route path="/profile" component={ProfilePage} />
<Route path="/hello" component={Hello} /> <PrivateRoute path="/profile">
<Route path="/home" component={HomePage} /> <ProfilePage />
<Redirect path='/hello' to='/hello' /> </PrivateRoute>
</Switch> </Switch>
</Router>, </Router>,
document.getElementById('root') document.getElementById('root')
......
import axios from "axios" import axios from "axios"
//자동으로 sessionStorage에 login이 생성됨 //자동으로 localstorage에 login이 생성됨
export function handleLogin(userId) { export function handleLogin(data) {
sessionStorage.setItem('user', userId) sessionStorage.setItem('userId', data.user._id)
sessionStorage.setItem('name', data.user.username)
} }
export async function handleLogout() { export async function handleLogout() {
sessionStorage.removeItem('user') sessionStorage.clear();
await axios.get('/auth/logout') await axios.get('/auth/logout')
//login페이지로 이동 //login페이지로 이동
window.location.href='/login' //window.location.href='/login'
} }
//login이 됬는지 안됬는지 따질때 쓰임
export function isAuthenticated() { export function isAuthenticated() {
const userId = sessionStorage.getItem('user') const userId = sessionStorage.getItem('userId')
if (userId) { if (userId) {
return userId return userId
} else { } else {
......
...@@ -21,6 +21,7 @@ ...@@ -21,6 +21,7 @@
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.9", "mongoose": "^5.11.9",
"nanoid": "^3.1.20", "nanoid": "^3.1.20",
"nodemon": "^2.0.6", "nodemon": "^2.0.6",
......
...@@ -7,22 +7,13 @@ import config from "../config.js" ...@@ -7,22 +7,13 @@ import config from "../config.js"
//sign validation해야됨 //sign validation해야됨
const login = async (req, res) => { const login = async (req, res) => {
const { email, password } = req.body const { email, password } = req.body
//req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
console.log(email, password)
try { try {
// 1) 사용자 확인
const user = await User.findOne({ email }).select('+password') const user = await User.findOne({ email }).select('+password')
// 2) 이메일 사용자가 없으면 에러 반환
if (!user) { if (!user) {
return res.status(404).send(`${email}을 사용하는 사용자가 없습니다`) return res.status(404).send(`${email}을 사용하는 사용자가 없습니다`)
} }
// 3) 비밀번호 일치 확인
const passwordMatch = await bcrypt.compare(password, user.password) const passwordMatch = await bcrypt.compare(password, user.password)
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
if (passwordMatch) { if (passwordMatch) {
//토큰 생성 //토큰 생성
const token = jwt.sign({ userId: user._id}, config.jwtSecret, {expiresIn: '7d'}) const token = jwt.sign({ userId: user._id}, config.jwtSecret, {expiresIn: '7d'})
...@@ -39,19 +30,19 @@ const login = async (req, res) => { ...@@ -39,19 +30,19 @@ const login = async (req, res) => {
secure: config.env === 'production', secure: config.env === 'production',
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음. //secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
}) })
res.send({ userId: user._id}) console.log('res.send.user', {user})
res.send({user})
} else { } else {
// 5) 비밀번호가 틀리면 에러 반환 // 5) 비밀번호가 틀리면 에러 반환
res.status(401).send('비밀번호가 일치하지 않습니다') res.status(401).send('비밀번호가 일치하지 않습니다')
} }
} catch (error) { } catch (error) {
//알수없는 모든 에러발생시 처리 //알수없는 모든 에러발생시 처리
console.log(error) console.log(error)
res.status(500).send('로그인 에러가 발생하였습니다') res.status(500).send('로그인 에러가 발생하였습니다')
} }
} }
const logout = (req, res) => { const logout = (req, res) => {
......
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