Commit 706ed28d authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

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

parents 289b3608 b84511b5
......@@ -13,7 +13,6 @@
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"styled-components": "^5.2.1",
"web-vitals": "^0.2.4"
},
"scripts": {
......
import { BrowserRouter as Router, Route, Redirect, Switch, BrowserRouter } from 'react-router-dom';
import Hello from './Hello.js'
import HomePage from './Pages/HomePage.js';
import ProfilePage from './Pages/ProfilePage.js';
import logo from './logo.svg';
import './App.css';
import Hello from './Hello';
function App() {
console.log()
return (
<HomePage />
)
<Hello name='대기'/>
);
}
export default App;
import React from 'react'
import { Navbar, Nav, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { handleLogout } from '../utils/auth';
function Menu() {
const userName = "정연우";
......@@ -13,7 +15,9 @@ function Menu() {
<Nav.Link href="/profile">Profile</Nav.Link>
<Nav.Link href="/hello">Hello</Nav.Link>
</Nav>
<Button variant="light" className="ml-3">Logout</Button>
<Link to="./login">
<Button onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
</Link>
</Navbar>
)
}
......
import { Button, Navbar, Nav, Form, FormControl } from 'react-bootstrap';
import { Button, Navbar, Nav } from 'react-bootstrap';
import React from 'react'
const userName = "정연우";
......
import React, { useState } from 'react';
import { Button, Form, Container, Navbar } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import axios from 'axios'
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'
const INIT_USER = {
email: '',
password: '',
}
function LogIn() {
const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER)
//로딩, 에러, diserved 상태 넣어야됨.
const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('')
const [success, setSucces] = useState(false)
const [loading, setLoading] = useState(false)
useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el))
//Boolean : 참거짓 판별
//every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
//empty string때만 false로 나옴.
isUser ? setDisabled(false) : setDisabled(true)
}, [user])
function handleChange(event) {
const { name, value } = event.target
// console.log(name, value)
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault()
// const form = event.currentTarget;
// if (form.checkValidity() === false) {
// event.preventDefault();
// event.stopPropagation();
// }
// setValidated(true);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
try {
setLoading(true)
setError('')
await axios.post('/auth/login', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
handleLogin(user)
setSucces(true)
} catch (error) {
catchErrors(error, setError)
//setError(error.response.data)
//error객체가 들어감.
} finally {
setLoading(false)
}
//server쪽에서 json형식으로 보낼것임
}
setValidated(true);
};
//success시 링크이동
if (success) {
console.log('success', success)
return <Redirect to='/' />
}
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar>
{/* <Navbar bg="dark" variant="dark">
<Navbar.Brand>YDK Messenger</Navbar.Brand>
</Navbar> */}
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<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">
<div className="mt-5 p-5 shadow w-75">
<h2 className="text-center ">로그인</h2>
<h2 className="text-center">로그인</h2>
<Form.Group controlId="formGroupEmail">
<Form.Label>이메일</Form.Label>
<Form.Control
required
type="text"
type="email"
name="email"
onChange={handleChange}
value={user.email}
placeholder="이메일을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 이메일을 입력해주세요!
......@@ -44,20 +96,32 @@ function LogIn() {
<Form.Label>비밀번호</Form.Label>
<Form.Control
required
type="text"
type="password"
name="password"
onChange={handleChange}
value={user.password}
placeholder="비밀번호를 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 비밀번호를 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Link to="./home">
<Button type="submit" variant="outline-success" size="lg" className="mr-4" block>로그인</Button>
</Link>
<Button
disabled={disabled || loading}
type="submit"
variant="outline-success"
size="lg"
className="mr-4"
block>
{loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />} {' '} 로그인
</Button>
<Link to="./signup">
<h6 type="button" className="text-right mt-2" style={{ cursor: 'pointer' }}>회원가입</h6>
</Link>
{error && <Alert variant='danger'>
{error}
</Alert>}
</div>
</Container>
</Form>
......@@ -65,7 +129,4 @@ function LogIn() {
);
}
//render(<LogIn />);
export default LogIn
\ No newline at end of file
import React, { useState } from 'react';
import { Button, Form, Container, Navbar } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { Button, Form, Container, Navbar, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom';
const INIT_USER = {
username: '',
nickname: '',
email: '',
password: '',
}
function SingUp() {
const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('')
const [disabled, setDisabled] = useState(true)
const [success, setSucces] = useState(false)
useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el))
//Boolean : 참거짓 판별
//every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
//empty string때만 false로 나옴.
isUser ? setDisabled(false) : setDisabled(true)
}, [user])
function handleChange(event) {
const { name, value } = event.target
// console.log(name, value)
setUser({ ...user, [name]: value })
}
const handleSubmit = (event) => {
async function handleSubmit(event) {
event.preventDefault();
//빈문자열 입력 시 오류 문자 출력
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
// console.log(user)
try {
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)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
// console.log(response.data)
console.log(user)
// ?????????hash 처리된 password가 저장되지 않았음
// setUser(INIT_USER)
setSucces(true)
} catch (error) {
catchErrors(error, setError)
}
}
if (success) {
console.log('success', success)
return <Redirect to='/login' />
}
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">
필수 정보입니다! 이름을 입력해주세요!
{/* <Navbar bg="dark" variant="dark">
<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'>
<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"
name="username"
onChange={handleChange}
value={user.username}
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.Group>
<Form.Group controlId="formGroupNickname">
<Form.Label>별명</Form.Label>
<Form.Control
required
type="text"
name="nickname"
onChange={handleChange}
value={user.nickname}
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.Group>
<Form.Group controlId="formGroupEmail">
<Form.Label>이메일</Form.Label>
<Form.Control
required
type="email"
name="email"
onChange={handleChange}
value={user.email}
placeholder="이메일을 입력해주세요" />
<Form.Control.Feedback type="invalid">
필수 정보입니다! 이메일을 입력해주세요!
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="formGroupPassword">
<Form.Label>비밀번호</Form.Label>
<Form.Control
required
type="password"
name="password"
onChange={handleChange}
value={user.password}
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 >
</Form.Group>
<Button
disabled={disabled}
type='submit'
variant="outline-success"
size="lg"
className="mr-4"
block>가입</Button>
{error && <Alert variant='danger'>
{error}
</Alert>}
</div>
</Container>
</Form>
</>
)
}
......
......@@ -8,7 +8,6 @@ import ProfilePage from './Pages/ProfilePage';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';
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'
......
import React, { useState } from 'react';
function randCode(){
// const [ranNumArr,setRanNumArr] = useState([]);
const min = 1;
const max = 99999;
let newNum = Math.floor((Math.random()*max)+min);
// for (let i=0;i<ranNumArr.length;i++){
// if (ranNumArr[i]==newNum){
// newNum = Math.floor((Math.random()*max)+min);
// }
// }
let zeroSize = "";
for (let j=0;j<5-newNum.toString().length;j++){
zeroSize += "0";
}
// setRanNumArr(zeroSize+newNum);
return (zeroSize+newNum.toString());
}
export default randCode;
\ No newline at end of file
import axios from "axios"
//자동으로 localstorage에 login이 생성됨
export function handleLogin(props) {
localStorage.setItem('user', JSON.stringify({email: props.email}))
}
export async function handleLogout() {
localStorage.removeItem('user')
await axios.get('/auth/logout')
}
\ No newline at end of file
function catchErrors(error, displayError) {
let errorMsg
if (error.response) {
errorMsg = error.response.data
console.log(errorMsg)
} else if (error.request) {
errorMsg = error.request
console.log(errorMsg)
} else {
errorMsg = error.message
console.log(errorMsg)
}
displayError(errorMsg)
}
export default catchErrors
\ No newline at end of file
......@@ -3,7 +3,8 @@ const config = {
port: process.env.PORT || 3030,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGODB_URI || 'mongodb://localhost/messenger',
cookieMaxAge: 60 * 60 * 24 * 7 * 1000,
cookieMaxAge: 60 * 60 * 24 * 7 * 1000
//1000이 1초 이므로 7일
}
export default config
\ No newline at end of file
import User from "../models/User.js"
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import config from "../config.js"
//server부분에는 꼭 js붙여주기!!
//sign validation해야됨
const login = async (req, res) => {
const { email, password } = req.body
//req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
console.log(email, password)
try {
// 1) 사용자 확인
const user = await User.findOne({ email }).select('+password')
// 2) 이메일 사용자가 없으면 에러 반환
if (!user) {
return res.status(404).send(`${email}을 사용하는 사용자가 없습니다`)
}
// 3) 비밀번호 일치 확인
const passwordMatch = await bcrypt.compare(password, user.password)
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
if (passwordMatch) {
//토큰 생성
const token = jwt.sign({ userId: user._id }, config.jwtSecret, {expiresIn: '7d'})
//jwtSecret : 노출되면 안됨. 문자열
//expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기
//쿠키에 저장
//res : client로 넘어가는 객체 cookie('이름', value)
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
//생성일로부터 어느정도까지 살아있을 것인가
httpOnly: true,
//client에서 javascript로 접근할 수 없음
secure: config.env === 'production',
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
})
res.send('Login Successful')
} else {
// 5) 비밀번호가 틀리면 에러 반환
res.status(401).send('비밀번호가 일치하지 않습니다')
}
} catch (error) {
//알수없는 모든 에러발생시 처리
console.log(error)
res.status(500).send('로그인 에러가 발생하였습니다')
}
}
const logout = (req, res) => {
res.clearCookie('token')
res.send('로그아웃 되었습니다')
}
export default { login, logout }
// {} : 객체로 return함
......@@ -5,13 +5,13 @@ import bcrypt from "bcryptjs";
import jwt from 'jsonwebtoken'
import config from "../config.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)
const { username, nickname, email, password } = req.body
//req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
console.log(username, nickname, email, password)
// try {
......@@ -63,22 +63,54 @@ const signup = async (req, res) => {
const { email } = req.body
console.log(email, 'ddd')
try {
const user = await User.findOne({ email }).select('+name')
console.log(user.name, user.nickname, user.email)
const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
expiresIn: '7d'
})
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
httpOnly: true,
secure: config.env === 'production'
})
res.send('login successful')
}
catch (error) {
if (!isLength(username, {min: 3, max: 10})){
//이범위를 벗어나면 error발생
return res.status(422).send('이름은 3-10자 사이입니다')
//422 : 형식이 잘못되었다는 error발생
} else if (!isLength(nickname, {min: 2, max: 10})) {
return res.status(422).send('별명은 2-10자 사이입니다.')
} else if (!isLength(password, {min: 6})) {
return res.status(422).send('비밀번호는 6자 이상입니다.')
} else if (!isEmail(email)) {
return res.status(422).send('유효하지 않은 이메일 형식입니다')
}
// 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')
// }
// 기존의 email이 있으면 나오는 error (unique)
const user = await User.findOne({email})
if(user) {
return res.status(422).send(`${email}이 이미 사용중입니다.`)
}
const hash = await bcrypt.hash(password, 10)
//promise이므로 await사용함
const newUser = await new User({
username,
nickname,
email,
password: hash,
//required를 하였기 때문에 이중 하나라도 없으면 에러 발생
}).save()
//save시 user schema형식에 맞는지 확인후 틀리면 error발생 맞으면 mongooDb로 들어감
//save(promise)붙일 시 fuction 앞에 await 붙여주기 + async 함수 앞에 붙여주기
console.log(newUser)
res.json(newUser)
} catch (error) {
//알수없는 모든 에러발생시 처리
console.log(error)
res.send(500).send('로그인에러')
res.status(500).send('회원가입 에러발생하였습니다.')
}
}
......
......@@ -2,13 +2,13 @@
import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types
const { String } = mongoose.Schema.Types
//원래 java의 string이 아니라 mongoose의 string을 쓰기 위해 불러옴.
//object의 id를 쓸때에도 추가시켜줘야됨.
//형식을 정의함.
const UserSchema = new mongoose.Schema({
name: {
username: {
type: String,
required: true,
},
......@@ -29,14 +29,6 @@ const UserSchema = new mongoose.Schema({
//정보를 찾을때 찾지 않게함
//플러스 옵션을 주면 찾을 수 있음(mongoose에서 용법찾아봐야됨)
},
// role: {
// type: String,
// required: true,
// default: 'user',
// enum: ['user', 'admin', 'root'],
// //열거, 배열 : role이라는 것이 'user', 'admin', 'root'중 하나를 쓰임
// //사용자에 역할을 줄 때 사용함.
//}
},{
//옵셥을 정의함.
timestamps: true
......@@ -45,4 +37,4 @@ const UserSchema = new mongoose.Schema({
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
//user라는 이름이 있으면 앞을 return하고 없으면 뒤를 실행함
\ No newline at end of file
//user라는 이름이 있으면 앞을 return하고 없으면 뒤를 실행함
import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types
const ChatSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
interest: {
type: String,
required: true,
select: false
},
isOpen: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
}
}, {
timestamps: true
})
export default mongoose.models.User || mongoose.model('chat', ChatSchema)
\ No newline at end of file
import express from 'express'
import authCtrl from '../controllers/auth.controller.js'
const router = express.Router()
//router의 역할 : './주소'부분을 처리하는 역할함.
router.route('/auth/login')
.post(authCtrl.login)
.get(authCtrl.login)
router.route('/auth/logout')
.get(authCtrl.logout)
// /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
......@@ -4,16 +4,20 @@ import userCtrl from '../controllers/user.controller.js'
const router = express.Router()
//router의 역할 : './주소'부분을 처리하는 역할함.
router.route('/api/users/')
router.route('/users/signup')
.post(userCtrl.signup)
.get(userCtrl.hello)
router.route('api/users/')
.post(userCtrl.signup)
.get(userCtrl.hello)
router.route(`/api/users/:userId`)
.post(userCtrl.authuser)
.put(userCtrl.chnick)
// router.route('/api/users/signup/:userId') //로그인한 사람의 정보만 가져오도록
// .get
......
import express from 'express'
import connectDb from './utils/connectDb.js'
import userRouter from './routes/user.routes.js'
import authRouter from './routes/auth.routes.js'
connectDb()
......@@ -12,6 +13,7 @@ app.use(express.json())
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음
app.use(userRouter)
app.use(authRouter)
//userRouter로 이동
app.get('/', (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