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

수정

parent 1e98d45b
...@@ -6,7 +6,9 @@ ...@@ -6,7 +6,9 @@
"@testing-library/jest-dom": "^5.11.6", "@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2", "@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.6.0", "@testing-library/user-event": "^12.6.0",
"axios": "^0.21.1",
"bootstrap": "^4.5.3", "bootstrap": "^4.5.3",
"nanoid": "^3.1.20",
"react": "^17.0.1", "react": "^17.0.1",
"react-bootstrap": "^1.4.0", "react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1", "react-dom": "^17.0.1",
......
import axios from 'axios';
import React, { useState } from 'react' import React, { useState } from 'react'
import { ListGroup, Row, Col } from 'react-bootstrap'; import { ListGroup, Row, Col } from 'react-bootstrap';
function ClosedList(props) { function ClosedList(props) {
const [list, setList] = useState([ const [list, setList] = useState([]);
{ room: '테스트 방1', memnum: 5, admin: '가영' },
{ room: '테스트 방2', memnum: 4, admin: '수현' }] // async function getClosedList() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
); // const member = sessionStorage.getItem('name')
// const response = await axios.put(`/room/${member}`, { 'member': member })
// setList(response.data)
// }
// console.log(list)
function enterChatroomCH(e) { function enterChatroomCH(e) {
console.log(e.target.name) console.log(e.target.name)
...@@ -16,12 +23,14 @@ function ClosedList(props) { ...@@ -16,12 +23,14 @@ function ClosedList(props) {
// props.clearChat() // props.clearChat()
} }
//user.hasOwnProperty('이름');
return ( return (
<div> <div>
{list.map((item, index) => {list.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatroomCH} name={item.room}> <ListGroup.Item action onClick={enterChatroomCH} name={item.room}>
{item.room} {item.room}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
)} )}
......
...@@ -14,11 +14,10 @@ function Menu() { ...@@ -14,11 +14,10 @@ function Menu() {
<Navbar.Brand href="/home">YDK Messenger</Navbar.Brand> <Navbar.Brand href="/home">YDK Messenger</Navbar.Brand>
{name ? {name ?
<> <>
<div className='ml-1 mr-2' style={{ color: 'white' }}>{name} 환영합니다</div> <div className='ml-1 mr-2' style={{ color: 'white' }}>{name} 환영합니다</div>
<Nav className="mr-auto"> <Nav className="mr-auto">
<Nav.Link href="/home">Home</Nav.Link> {/* <Nav.Link href="/home">Home</Nav.Link> */}
<Nav.Link href="/profile">Profile</Nav.Link> <Nav.Link href="/profile">Profile</Nav.Link>
<Nav.Link href="/hello">Hello</Nav.Link>
</Nav> </Nav>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button> <Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
</> </>
......
...@@ -9,13 +9,16 @@ import Menu from '../Components/Menu'; ...@@ -9,13 +9,16 @@ import Menu from '../Components/Menu';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { io } from "socket.io-client"; //모듈 가져오기 import { io } from "socket.io-client"; //모듈 가져오기
import Chat from "../Components/Chat"; import Chat from "../Components/Chat";
import { customAlphabet } from 'nanoid';
import { Redirect } from 'react-router-dom';
const socket = io(); const socket = io();
const INIT_ROOM = { const INIT_ROOM = {
roomName: '', roomName: '',
interest: '', interest: '',
isOpen: false isOpen: false,
moderator: '',
} }
function Home() { function Home() {
...@@ -28,6 +31,7 @@ function Home() { ...@@ -28,6 +31,7 @@ function Home() {
const [singleChat, setSingleChat] = useState('') const [singleChat, setSingleChat] = useState('')
const [roomName, setRoomName] = useState('') const [roomName, setRoomName] = useState('')
const [success, setSuccess] = useState(false)
const handleClose = () => setShow(false); const handleClose = () => setShow(false);
const handleShow = () => setShow(true); const handleShow = () => setShow(true);
...@@ -36,6 +40,10 @@ function Home() { ...@@ -36,6 +40,10 @@ function Home() {
const handleClose2 = () => setShow2(false); const handleClose2 = () => setShow2(false);
const handleShow2 = () => setShow2(true); const handleShow2 = () => setShow2(true);
const moderator = sessionStorage.getItem('userId');
const nanoid = customAlphabet('1234567890abcdef', 10)
const roomId = nanoid()
useEffect(() => { useEffect(() => {
const isRoom = Object.values(room).every(el => Boolean(el)) const isRoom = Object.values(room).every(el => Boolean(el))
isRoom ? setDisabled(false) : setDisabled(true) isRoom ? setDisabled(false) : setDisabled(true)
...@@ -43,23 +51,31 @@ function Home() { ...@@ -43,23 +51,31 @@ function Home() {
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setRoom({ ...room, [name]: value }) setRoom({ ...room, [name]: value, moderator, roomId })
console.log(room) //console.log(room)
} }
console.log(room)
console.log(room.roomId)
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
try { try {
setError('') setError('')
await axios.post('/room/makeRoom', room) await axios.post('/room/makeRoom', room)
setRoom(INIT_ROOM) // await axios.patch('/user/signup', { joinroom: `${room.roomId}`})
} catch (error){ // await axios.post(`/user/${moderator}`, room.roomId)
setSuccess(true)
// setRoom(INIT_ROOM)
setShow(false)
} catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
//SOCKET 관련 시작 //SOCKET 관련 시작
function enterChatroom(rName) { //방 입장하기 function enterChatroom(rName) { //방 입장하기
socket.emit('joinRoom', rName) socket.emit('joinRoom', rName)
console.log(`joinRoom : ${rName} 입장`) console.log(`joinRoom : ${rName} 입장`)
...@@ -80,6 +96,13 @@ function Home() { ...@@ -80,6 +96,13 @@ function Home() {
}) })
}, [singleChat]) }, [singleChat])
// console.log(room.roomId)
if (success) {
// console.log(room.roomId)
alert(`방암호는 ${room.roomId}입니다`)
// return <Redirect to='/home' />
}
return ( return (
<> <>
<Menu /> <Menu />
...@@ -87,15 +110,15 @@ function Home() { ...@@ -87,15 +110,15 @@ function Home() {
<Col className="list" md={5}> <Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example"> <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} > <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatroom={enterChatroom} setRoomName={setRoomName}/> <ClosedList enterChatroom={enterChatroom} setRoomName={setRoomName} />
</Tab> </Tab>
<Tab eventKey="open" title="공개방" > <Tab eventKey="open" title="공개방" >
<OpenList enterChatroom={enterChatroom} setRoomName={setRoomName}/> <OpenList enterChatroom={enterChatroom} setRoomName={setRoomName} />
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
<Col style={{ padding: "0" }}> <Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} setSingleChat={setSingleChat} roomName={roomName}/> : null} {chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} setSingleChat={setSingleChat} roomName={roomName} /> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}> <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShow} size="lg" block> <Button variant="primary" onClick={handleShow} size="lg" block>
...@@ -133,7 +156,6 @@ function Home() { ...@@ -133,7 +156,6 @@ function Home() {
<option>언어</option> <option>언어</option>
<option>취미</option> <option>취미</option>
</Form.Control> </Form.Control>
{/* <Form.Control type="text" /> */}
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="chatIsOpen"> <Form.Group as={Row} controlId="chatIsOpen">
...@@ -165,19 +187,19 @@ function Home() { ...@@ -165,19 +187,19 @@ function Home() {
<Modal.Title>참여 코드로 채팅 참가</Modal.Title> <Modal.Title>참여 코드로 채팅 참가</Modal.Title>
</Modal.Header> </Modal.Header>
<Modal.Body> <Modal.Body>
<Form onSubmit={() => { console.log('제출') }}> {/* <Form onSubmit={handleSubmit2}> */}
<Form.Group as={Row} controlId="formCodeE"> <Form.Group as={Row} controlId="formCodeE">
<Form.Label column sm={4}>참여 코드</Form.Label> <Form.Label column sm={4}>참여 코드</Form.Label>
<Col> <Col>
<Form.Control type="text" /> <Form.Control type="text" />
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row}> <Form.Group as={Row}>
<Col sm={{ span: 5, offset: 4 }}> <Col sm={{ span: 5, offset: 4 }}>
<Button type="submit">참가</Button> <Button type="submit">참가</Button>
</Col> </Col>
</Form.Group> </Form.Group>
</Form> {/* </Form> */}
</Modal.Body> </Modal.Body>
</Modal> </Modal>
</Col> </Col>
......
...@@ -25,7 +25,7 @@ function ProfilePage() { ...@@ -25,7 +25,7 @@ function ProfilePage() {
const [hidden, setHidden] = useState(true) const [hidden, setHidden] = useState(true)
async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ async function getLoginedUser() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
const response = await axios.post(`/users/${userid}`, { '_id': userid }) const response = await axios.post(`/users/${userid}`, { '_id': userid })
setUser(response.data) setUser(response.data)
......
...@@ -17,7 +17,7 @@ function SingUp() { ...@@ -17,7 +17,7 @@ function SingUp() {
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('') const [error, setError] = useState('')
const [disabled, setDisabled] = useState(true) const [disabled, setDisabled] = useState(true)
const [success, setSucces] = useState(false) const [success, setSuccess] = useState(false)
useEffect(() => { useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el)) const isUser = Object.values(user).every(el => Boolean(el))
...@@ -45,8 +45,7 @@ function SingUp() { ...@@ -45,8 +45,7 @@ function SingUp() {
try { try {
setError('') setError('')
await axios.post('/users/signup', user) await axios.post('/users/signup', user)
alert("회원가입이 완료되었습니다!") setSuccess(true)
setSucces(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
......
...@@ -4,7 +4,6 @@ import 'bootstrap/dist/css/bootstrap.min.css'; ...@@ -4,7 +4,6 @@ import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css'; import './index.css';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import reportWebVitals from './reportWebVitals'; 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 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.min.css';
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"axios": "^0.21.1", "axios": "^0.21.1",
"bcrypt": "^5.0.0",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"cors": "^2.8.5", "cors": "^2.8.5",
......
import Room from "../models/Room.js" import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid' // import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
const nanoid = customAlphabet('1234567890abcdef', 10) // const nanoid = customAlphabet('1234567890abcdef', 10)
const makeRoom = async (req, res) => { const makeRoom = async (req, res) => {
console.log(req.body) console.log(req.body)
const { roomName, interest, isOpen } = req.body; const { roomName, interest, isOpen, moderator, roomId } = req.body;
console.log(roomName, interest, isOpen) console.log(roomName, interest, isOpen, moderator, roomId)
const roomId = nanoid() // const roomId = nanoid()
const room = await Room.findOne({ roomId }) // const room = await Room.findOne({ roomId })
while (room) { // while (room) {
roomId = nanoid() // roomId = nanoid()
room = await Room.findOne({ roomId }) // room = await Room.findOne({ roomId })
} // }
try { try {
if (!isLength(roomName, { min: 3, max: 20 })) { if (!isLength(roomName, { min: 3, max: 20 })) {
...@@ -23,10 +23,11 @@ const makeRoom = async (req, res) => { ...@@ -23,10 +23,11 @@ const makeRoom = async (req, res) => {
return res.status(422).send('분야를 반드시 선택하여야 합니다.') return res.status(422).send('분야를 반드시 선택하여야 합니다.')
} }
const newRoom = await new Room({ const newRoom = await new Room({
roomId,
roomName, roomName,
interest, interest,
isOpen isOpen,
moderator,
roomId,
}).save() }).save()
console.log(newRoom) console.log(newRoom)
res.json(newRoom) res.json(newRoom)
...@@ -36,4 +37,14 @@ const makeRoom = async (req, res) => { ...@@ -36,4 +37,14 @@ const makeRoom = async (req, res) => {
} }
} }
// const checkmember = async (req, res) => {
// try {
// let user = await Room.findOne(req.body).select('roomName').exec()
// console.log(user)
// return res.json(user)
// } catch (error) {
// alert('올바르지 못한 접근입니다.')
// }
// }
export default { makeRoom } export default { makeRoom }
\ No newline at end of file
...@@ -33,7 +33,7 @@ const signup = async (req, res) => { ...@@ -33,7 +33,7 @@ const signup = async (req, res) => {
email, email,
password: hash, password: hash,
}).save() }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
...@@ -71,5 +71,12 @@ const loginNavbar = async (req, res) => { ...@@ -71,5 +71,12 @@ const loginNavbar = async (req, res) => {
} }
} }
export default { signup, logineduser, changenick, loginNavbar } const saveroom = async (req, res) => {
// {} : 객체로 return함 const roomId = room.roomId
\ No newline at end of file if (!isLength(roomId, { min: 11 })) {
return res.status(422).send('방아이디 저장에 오류가 발생하였습니다.')
}
}
export default { signup, logineduser, changenick, loginNavbar, saveroom }
// {} : 객체로 return 함
\ No newline at end of file
...@@ -18,4 +18,4 @@ const ChatSchema = new mongoose.Schema({ ...@@ -18,4 +18,4 @@ const ChatSchema = new mongoose.Schema({
timestamps: true timestamps: true
}) })
export default mongoose.models.ChatSchema || mongoose.model('Chat', ChatSchema) export default mongoose.models.Chat || mongoose.model('Chat', ChatSchema)
\ No newline at end of file \ No newline at end of file
...@@ -3,11 +3,6 @@ import mongoose from 'mongoose' ...@@ -3,11 +3,6 @@ import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types const {String} = mongoose.Schema.Types
const RoomSchema = new mongoose.Schema({ const RoomSchema = new mongoose.Schema({
roomId: {
type: String,
// default:() => nanoid(),
unique: true
},
roomName: { roomName: {
type: String, type: String,
required: true, required: true,
...@@ -21,8 +16,17 @@ const RoomSchema = new mongoose.Schema({ ...@@ -21,8 +16,17 @@ const RoomSchema = new mongoose.Schema({
type: String, type: String,
required: true, required: true,
default: 'user', default: 'user',
enum: ['user', 'admin', 'root'] enum: ['true', 'false']
} },
moderator: {
type: String,
required: true,
},
roomId: {
type: String,
// default:() => nanoid(),
unique: true
},
}, { }, {
timestamps: true timestamps: true
}) })
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import mongoose from 'mongoose' import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types const { String } = mongoose.Schema.Types
// const { Array } = mongoose.Schema.Types
//원래 java의 string이 아니라 mongoose의 string을 쓰기 위해 불러옴. //원래 java의 string이 아니라 mongoose의 string을 쓰기 위해 불러옴.
//object의 id를 쓸때에도 추가시켜줘야됨. //object의 id를 쓸때에도 추가시켜줘야됨.
......
...@@ -5,4 +5,8 @@ const router = express.Router() ...@@ -5,4 +5,8 @@ const router = express.Router()
router.route('/room/makeRoom') router.route('/room/makeRoom')
.post(roomCtrl.makeRoom) .post(roomCtrl.makeRoom)
// router.route(`/room/:member`)
// .put(userCtrl.checkmember)
export default router export default router
\ No newline at end of file
...@@ -12,6 +12,9 @@ router.route(`/users/:userId`) ...@@ -12,6 +12,9 @@ router.route(`/users/:userId`)
.put(userCtrl.changenick) .put(userCtrl.changenick)
.get(userCtrl.loginNavbar) .get(userCtrl.loginNavbar)
router.route(`users/:name`)
.post(userCtrl.saveroom)
// router.param('userId', userCtrl.userById) // router.param('userId', userCtrl.userById)
// router.route('/api/users/signup/:userId') //로그인한 사람의 정보만 가져오도록 // router.route('/api/users/signup/:userId') //로그인한 사람의 정보만 가져오도록
......
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