Commit cb575cad authored by Choi Ga Young's avatar Choi Ga Young
Browse files

aa

parent 1c9e6868
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } 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('') // const [username, setUsername] = useState('')
const username = localStorage.getItem('name'); let defaultname = sessionStorage.getItem('name');
// const [newName, setNewName] = useState({ username: '' });
// const [state, setState] = useState(false);
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
...@@ -17,26 +18,30 @@ function Chat(props) { ...@@ -17,26 +18,30 @@ function Chat(props) {
props.sendMsg(e) props.sendMsg(e)
} }
// async function getLoginedUser() { //email로 db에서 찾아오기 // const saveChange = (e) => {
// const { name, value } = e.target
// setNewName({ ...newName, [name]: value })
// }
// const userid = localStorage.getItem('user') // const handleSubmit = (e) => {
// const response = await axios.post(`/users/${userid}`, { 'email': userid }) // e.preventDefault()
// setUsername(response.data.username) // setState(true)
// } // }
// 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>
<Form onSubmit={handleSubmit}>
<Form.Control name='newname' type='text' onChange={saveChange} />
<Button variant="primary" type="submit">전송</Button>
</Form>
<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>
))} ))}
......
...@@ -6,7 +6,7 @@ import { handleLogout } from '../utils/auth'; ...@@ -6,7 +6,7 @@ import { handleLogout } from '../utils/auth';
function Menu() { function Menu() {
const name = localStorage.getItem('name'); const name = sessionStorage.getItem('name');
return ( return (
<Navbar bg="dark" variant="dark"> <Navbar bg="dark" variant="dark">
......
...@@ -4,7 +4,6 @@ import { Button, Form, Container, Navbar, Spinner, Alert } from 'react-bootstrap ...@@ -4,7 +4,6 @@ import { Button, Form, Container, Navbar, Spinner, Alert } from 'react-bootstrap
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { Link, Redirect } from 'react-router-dom' import { Link, Redirect } from 'react-router-dom'
import { handleLogin } from '../utils/auth' import { handleLogin } from '../utils/auth'
// import Menu from '../Components/Menu';
const INIT_USER = { const INIT_USER = {
email: '', email: '',
......
...@@ -2,18 +2,18 @@ import axios from "axios" ...@@ -2,18 +2,18 @@ import axios from "axios"
//자동으로 localstorage에 login이 생성됨 //자동으로 localstorage에 login이 생성됨
export function handleLogin(data) { export function handleLogin(data) {
localStorage.setItem('userId', data.user._id) sessionStorage.setItem('userId', data.user._id)
localStorage.setItem('name', data.user.username) sessionStorage.setItem('name', data.user.username)
} }
export async function handleLogout() { export async function handleLogout() {
localStorage.clear(); sessionStorage.clear();
await axios.get('/auth/logout') await axios.get('/auth/logout')
} }
export function isAuthenticated() { export function isAuthenticated() {
const userId = localStorage.getItem('userId') const userId = sessionStorage.getItem('userId')
if (userId) { if (userId) {
return userId return userId
} else { } else {
......
...@@ -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'})
...@@ -46,13 +37,12 @@ const login = async (req, res) => { ...@@ -46,13 +37,12 @@ const login = async (req, res) => {
// 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) => {
......
import mongoose from 'mongoose' import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types const { String } = mongoose.Schema.Types
const ChatSchema = new mongoose.Schema({ const ChatSchema = new mongoose.Schema({
name: { room: {
type: String, type: ObjectId,
required: true, required: true,
ref: 'Room',
}, },
interest: { username: {
type: String, type: String,
required: true, required: true,
select: false ref: 'User',
}, },
isOpen: { message: String,
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
}
}, { }, {
timestamps: true timestamps: true
}) })
export default mongoose.models.ChatSchema || mongoose.model('chat', ChatSchema) export default mongoose.models.ChatSchema || mongoose.model('Chat', ChatSchema)
\ No newline at end of file \ No newline at end of file
import mongoose from 'mongoose'
const {String} = mongoose.Schema.Types
const RoomSchema = 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.RoomSchema || mongoose.model('Room', RoomSchema)
\ No newline at end of file
import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types
const ProfileSchema = new mongoose.Schema({
defaultImg: {
type: String,
required: true,
},
}, {
timestamps: true
})
export default mongoose.models.ProfileSchema || mongoose.model('profile', ProfileSchema)
\ 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