Commit 7d7cf27a authored by Choi Ga Young's avatar Choi Ga Young
Browse files

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

parents 1256d0d3 796349ba
......@@ -20,4 +20,4 @@ function Chat(props) {
);
}
export default Chat;
\ No newline at end of file
export default Chat;
......@@ -19,4 +19,4 @@ function OpenList() {
)
}
export default OpenList
\ No newline at end of file
export default OpenList
import { Button, Navbar, Nav, Form, FormControl } 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="/homepage">Home</Nav.Link>
<Nav.Link href="/profilepage">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;
import React, { useState } from 'react';
import { Row, Col, Modal, Button } from 'react-bootstrap';
import { Row, Col, Modal, Button, Navbar, Nav } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import ClosedList from '../Components/ClosedList';
......@@ -10,6 +10,8 @@ import Chat from '../Components/Chat';
// const List = styled.div`
// background: #FFFAFA;
// `
const userName = "정연우";
function Home() {
const [show, setShow] = useState(false);
......@@ -22,37 +24,53 @@ function Home() {
// variant="pills"
return (
<Row className="mr-0">
<Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick = {handleChato} >
<ClosedList />
</Tab>
<Tab eventKey="open" title="공개방" >
<OpenList />
</Tab>
</Tabs>
</Col>
<Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} /> : null}
<Button variant="primary" onClick={handleShow} style={{ position: "fixed", bottom: "10px", right: "10px" }} >
생성
<>
<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="/homepage">Home</Nav.Link>
<Nav.Link href="/profilepage">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>
<Row className="mr-0">
<Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList />
</Tab>
<Tab eventKey="open" title="공개방" >
<OpenList />
</Tab>
</Tabs>
</Col>
<Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} /> : null}
<Button variant="primary" onClick={handleShow} style={{ position: "fixed", bottom: "10px", right: "10px" }} >
생성
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title> 생성</Modal.Title>
</Modal.Header>
<Modal.Body>여기에 form 입력</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleClose}>
생성
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title> 생성</Modal.Title>
</Modal.Header>
<Modal.Body>여기에 form 입력</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleClose}>
생성
</Button>
</Modal.Footer>
</Modal>
</Col>
</Row>
</Modal.Footer>
</Modal>
</Col>
</Row>
</>
);
}
......
import React, { useState } from 'react';
import { Button, Form, Container, Navbar } from 'react-bootstrap';
import { Link } from 'react-router-dom';
function LogIn() {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Container className="d-flex justify-content-center">
<div className="mt-5 p-5 shadow w-75">
<h2 className="text-center ">로그인</h2>
<Form.Group controlId="formGroupEmail">
<Form.Label>이메일</Form.Label>
<Form.Control
required
type="text"
placeholder="이메일을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 이메일을 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="formGroupPassword">
<Form.Label>비밀번호</Form.Label>
<Form.Control
required
type="text"
placeholder="비밀번호를 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 비밀번호를 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Link to="./homepage">
<Button type="submit" variant="outline-success" size="lg" className="mr-4" block>로그인</Button>
</Link>
<Link to="./signuppage">
<h6 type="button" className="text-right mt-2" style={{ cursor: 'pointer' }}>회원가입</h6>
</Link>
</div>
</Container>
</Form>
</>
);
}
//render(<LogIn />);
export default LogIn
\ No newline at end of file
import React, { useState } from "react";
import Joi, { validate } from "joi-browser";
const LoginForm = () => {
const userSchema = {
username: Joi.string().required(),
password: Joi.string().required(),
};
const [userInfo, setUserInfo] = useState({
username: "",
password: "",
});
const handleSubmit = (e) => {
e.preventDefault(); // 기본 동작 방지
};
const handleChange = (e) => {
// e.target.id: 변경이 일어난 input 태그의 id
// e.target.value: 변경이 일어난 input 태그의 값
const { id, value } = e.target;
const errors = { ...userInfo.errors };
/* 입력받은 값 유효성 검증 */
const obj = { [id]: value }; // 입력받은 값에
const schema = { [id]: userSchema[id] }; // Joi 스키마를 적용하여
const { error } = validate(obj, schema); // 유효성 검증
if(error) errors[id] = error;
else delete errors[id];
/* 입력받은 username 및 password를 state에 저장 */
const data = userInfo;
data[id] = value; // 점(.) 표기법을 대괄호([]) 표기법으로 사용
setUserInfo({ ...data, errors });
};
const buttonValidate = () => {
const options = { abortEarly: false, allowUnknown:true };
const { error } = Joi.validate(userInfo, userSchema, options);
// 에러 미발생 시 null 반환
if (!error) return null;
// 에러 발생 시 에러 정보 반환
const errors = {};
for (let item of error.details) {
errors[item.path[0]] = item.message;
}
return errors;
}
const handleClick = (e) => {
e.preventDefault();
const validUsername = 'ingyeo';
const validPassword = '1234';
if(validUsername === userInfo.username && validPassword === userInfo.password)
alert('로그인 성공!')
else
alert('로그인 실패...');
}
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Username</label>{" "}
{/* 이 label 태그는 아래 input 태그를 참조함 */}
<input
onChange={handleChange}
id="username"
type="text"
className="form-control"
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
onChange={handleChange}
id="password"
type="password"
className="form-control"
/>
</div>
<button
disabled={buttonValidate()}
onClick={handleClick}
className="btn btn-primary">Login</button>
</form>
</div>
);
};
export default LoginForm;
\ No newline at end of file
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { Image, Button, Container, Form, FormControl, Navbar, Nav } from 'react-bootstrap';
import { BrowserRouter as Router, Route, Redirect, Switch, Link } from 'react-router-dom';
import userdefault from './KakaoTalk_20201230_153151693.png'
const userName = "정연우";
const userEmail = "dusdn8455@korea.ac.kr";
let userNickname = "가나다라마바사";
function editNickname1() { //수정버튼 누르면 재입력하게 함
const html = (
<Form>
<div className="d-flex justify-content-center">
별명 : <Form.Control className="" id="editBlock" style={{ width: "40%" }} size="sm" type="id" defaultValue={userNickname} />
<Button className="ml-3" variant="outline-primary" size="sm" onClick={editNickname2}>수정</Button>
</div>
{/*
<div>
<Image src={pic} width="300px" roundedCircle />
</div> */}
</Form>
)
ReactDOM.render(html, document.getElementById("nickname"))
}
function editNickname2() { //수정버튼 누르면 다시 원래대로 돌아가게 함
changeNickname()
const html = (
<div>
별명 : {userNickname}
<Button className="ml-3" variant="outline-primary" size="sm" onClick={editNickname1}>수정</Button>
</div>
)
ReactDOM.render(html, document.getElementById("nickname"))
}
function changeNickname() { //수정버튼 누르면 닉네임 변경해줌
let editedNickname = document.getElementById("editBlock")
userNickname = editedNickname.value
}
function ProfilePage() {
const [tohome, setTohome] = useState(false)
const [defaultImg, setDefaultImg] = useState(true)
function goHome() {
return (setTohome(true))
}
function setThumbnail(event) { //불러온 사진 <div id='image_container'>에 띄우기
let reader = new FileReader();
reader.onload = function (event) {
let img = document.createElement("img");
img.setAttribute("src", event.target.result);
img.setAttribute("id", "profileImg")
img.setAttribute("style",'height:300px; width:300px')
img.setAttribute("class","mb-3")
// img.setAttribute("class","d-flex justify-content-center mb-3")
document.querySelector("div#image_container").appendChild(img);
};
reader.readAsDataURL(event.target.files[0]);
if (defaultImg) { //첫 이미지 업로드(default이미지 지우고 유저가 올린걸로 업로드)
let del = document.getElementById("defaultImg")
del.remove()
setDefaultImg(false)
}
else { //기존에 올렸던 사진 지우고 재선택한 사진 업로드
let del2= document.getElementById('profileImg')
del2.remove()
reader.onload = function (event) {
let img = document.createElement("img");
img.setAttribute("src", event.target.result);
img.setAttribute("id", "profileImg")
img.setAttribute("style",'height:300px; width:300px')
document.querySelector("div#image_container").appendChild(img);
};
}
}
return (
<div>
<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="/homepage">Home</Nav.Link>
<Nav.Link href="/profilepage">Profile</Nav.Link>
<Nav.Link href="/hello">Hello</Nav.Link>
</Nav>
<Button variant="light" className="ml-3">Logout</Button>
</Navbar>
{tohome ? <Redirect to='/homepage' /> : ''}
<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">{userName} 환영합니다 !</h4>
<div className="d-flex justify-content-center mb-3" id="defaultImg">
<Image src={userdefault} width="300px" roundedCircle />
</div>
<div 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>
</div>
<div className="text-center">
<div className="m-3">이름 : {userName}</div>
<div className="m-3" id="nickname">별명 : {userNickname}
<Button className="ml-3" variant="outline-primary" size="sm" onClick={editNickname1}>수정</Button>
</div>
<div className="m-3">이메일 : {userEmail}</div>
</div>
<div className="text-center m-5">
<span>
<Button variant="outline-success" size="sm" className="mr-4">저장</Button>
<Button variant="outline-success" size="sm" className="ml-4" onClick={goHome}> 화면으로</Button>
</span>
</div>
</div>
</Container>
</div>
)
}
export default ProfilePage
import React, { useState } from 'react';
import { Button, Form, Container, Navbar } from 'react-bootstrap';
import { Link } from 'react-router-dom';
function SingUp() {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar>
<div>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Container className="d-flex justify-content-center">
<div className="mt-5 p-5 shadow w-75">
<h2 className="text-center ">회원가입</h2>
<Form.Group controlId="formGroupUsername">
<Form.Label>이름</Form.Label>
<Form.Control
required
type="text"
placeholder="이름을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 이름을 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="formGroupNickname">
<Form.Label>별명</Form.Label>
<Form.Control
required
type="text"
placeholder="별명을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 별명을 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="formGroupEmail">
<Form.Label>이메일</Form.Label>
<Form.Control
required
type="text"
placeholder="이메일을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 이메일을 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="formGroupPassword">
<Form.Label>비밀번호</Form.Label>
<Form.Control
required
type="text"
placeholder="비밀번호를 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 비밀번호를 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Link to="./">
<Button type="submit" variant="outline-success" size="lg" className="mr-4" block>가입</Button>
</Link>
</div>
</Container>
</Form>
</div >
</>
)
}
export default SingUp
\ No newline at end of file
client/src/Pages/user_default.png
\ No newline at end of file
client/src/Pages/user_default.svg
\ No newline at end of file
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import HomePage from './Pages/HomePage';
// import App from './App';
import SignUpPage from './Pages/SignUpPage';
import ProfilePage from './Pages/ProfilePage';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';
// import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import LogInPage from './Pages/LogInPage';
import LoginForm from './Pages/LoginForm';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import Hello from './Hello'
import HomePage from './Pages/HomePage'
ReactDOM.render(
<React.StrictMode>
<HomePage />
</React.StrictMode>,
<Router>
<Switch>
<Route exact path="/" component={LogInPage} />
<Route path="/signuppage" component={SignUpPage} />
<Route path="/profilepage" component={ProfilePage} />
<Route path="/hello" component={Hello} />
<Route path="/homepage" component={HomePage} />
<Redirect path='/hello' to='/hello' />
</Switch>
</Router>,
document.getElementById('root')
);
......
const config = {
env: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3030,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGODB_URI || 'mongodb://localhost/messenger'
}
export default config
\ No newline at end of file
import User from "../models/User.js"
import isLength from 'validator/lib/isLength.js'
import isEmail from 'validator/lib/isEmail.js'
//꼭 js붙여주기!!
//isEmail
//sign validation해야됨
const signup = async (req, res) => {
const { name, nickname, email, password } = req.body
//req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
console.log(name, nickname, email, password)
try {
if (!isLength(name, { min: 3, max: 10 })) {
//이범위를 벗어나면 error발생
return res.status(422).send('Name must be 3-10 characters')
//422 : 형식이 잘못되었다는 error발생
} else if (!isLength(nickname, { min: 3, max: 10 })) {
return res.status(422).send('Nickname must be 3-10 characters')
} else if (!isEmail(email, {
allow_display_name: true,
require_display_name: true,
allow_utf8_local_part: false,
})) {
return res.status(422).send('Email does not fit the format')
} else if (!isLength(password, { min: 6, max: 25 })) {
return res.status(422).send('Nickname must be 6-25 characters')
}
const newUser = await new User({
name,
nickname,
email,
password,
//required를 하였기 때문에 이중 하나라도 없으면 에러 발생
}).save()
//save시 user schema형식에 맞는지 확인후 틀리면 error발생 맞으면 mongooDb로 들어감
//save(promise)붙일 시 fuction 앞에 await 붙여주기 + async 함수 앞에 붙여주기
console.log(newUser)
res.json(newUser)
} catch (error) {
//알수없는 모든 에러발생시 처리
console.log(error)
res.status(500).send('User signup error')
}
//newUSer (객체)를 json형식으로 바꿔서 객체열로 보냄
//res : 응답하는 객체
//응답안할 시 browser에서 빙빙돌다 에러 발생 -> 꼭 붙여줘야됨!
//res는 한번만 실행. 두번하면 에러 발생
}
const hello = (req, res) => {
res.send('Hello from users controller')
}
export default { signup, hello }
// {} : 객체로 return함
\ No newline at end of file
//주고받는 형식을 정의함.
import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types
//원래 java의 string이 아니라 mongoose의 string을 쓰기 위해 불러옴.
//object의 id를 쓸때에도 추가시켜줘야됨.
//형식을 정의함.
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
nickname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
//unique: 같은 email을 두번넣으면 error발생함
},
password: {
type: String,
required: true,
select: false,
//정보를 찾을때 찾지 않게함
//플러스 옵션을 주면 찾을 수 있음(mongoose에서 용법찾아봐야됨)
},
// role: {
// type: String,
// required: true,
// default: 'user',
// enum: ['user', 'admin', 'root'],
// //열거, 배열 : role이라는 것이 'user', 'admin', 'root'중 하나를 쓰임
// //사용자에 역할을 줄 때 사용함.
//}
},{
//옵셥을 정의함.
timestamps: true
//기본이 false로 되어있음
//user가 추가될때마다 createdAt(만들어진 시간 저장)과 updatedAt(수정될때 시간이 변경되어 저장)가 추가되어 시간을 저장함.
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
//user라는 이름이 있으면 앞을 return하고 없으면 뒤를 실행함
\ No newline at end of file
import express from 'express'
import userCtrl from '../controllers/user.controller.js'
const router = express.Router()
//router의 역할 : './주소'부분을 처리하는 역할함.
router.route('/api/users/signup')
.post(userCtrl.signup)
.get(userCtrl.hello)
// /api/users/signup로 들어오는 것을 post (method) 를 통해 useCtrl.signup 이것이 처리함
//browser에서 주소창에 치고 들어가면 get (method) 을 타고 들어간것임
//post를 띄우고 싶으면 앱에서 ARC실행해서 post를 실행하게 만들면됨.
//객체에 접근할때는 .을 찍고 접근함/ ex) .hello
//express middleware : (req, res) => {}
//node(req(client의 정보), res)를 넘겨줌.
export default router
\ No newline at end of file
import express from 'express';
import express from 'express'
import connectDb from './utils/connectDb.js'
import userRouter from './routes/user.routes.js'
const app = express() //express 사용
connectDb()
app.use(express.static('../client/build'))
const app = express()
app.get('/', (req, res)=>{
res.send('Hello')
}) //get은 받는 부분 send는 보내는 부분.
app.use(express.json())
//이부분을 body 파싱함
//express가 req.body라는곳을 자동으로만들어서 json형식으로 보낸것을 객체형식으로 넣음
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음
app.get('/home', (req, res)=>{
res.send('Home')
})
app.use(userRouter)
//userRouter로 이동
app.put('/signin', (req, res)=>{
res.send('Sign in')
})
app.get('/', (req, res) => {
res.send('Hello World. 안녕하세요')
})
app.listen(3001,()=>{
console.log('Server is listening on port 3001')
}) //웹 서버가 구동이 되면 화살표 함수가 실행됨.
\ No newline at end of file
app.listen(3030, () => {
console.log('Listening on port 3030')
})
import mongoose from 'mongoose'
import config from '../config.js'
const connection = {}
async function connectDb() {
if (connection.isConnected) {
return
}
const db = await mongoose.connect(config.mongoDbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
connection.isConnected = db.connections[0].readyState
}
export default connectDb
\ No newline at end of file
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