Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
students
messenger
Commits
e15228f3
Commit
e15228f3
authored
Jan 13, 2021
by
우지원
Browse files
0113
parent
a3d225ab
Changes
8
Show whitespace changes
Inline
Side-by-side
client/src/Components/Menu.js
View file @
e15228f3
import
React
from
'
react
'
// import axios from 'axios';
// import { response } from 'express';
import
React
,
{
useState
,
useEffect
}
from
'
react
'
;
import
{
Navbar
,
Nav
,
Button
}
from
'
react-bootstrap
'
;
import
{
handleLogout
,
isAuthenticated
}
from
'
../utils/auth
'
;
// const INIT_USER = {
// username: ''
// }
function
Menu
()
{
const
userName
=
"
정연우
"
;
const
user
=
isAuthenticated
()
// const [userName, setUsername] = useState(INIT_USER)
// async function getLoginedUser() {
// const userId = localStorage.getItem('user')
// const response = await axios.get(`/users/${userId}`)
// setUsername(response.data)
// }
// useEffect((user) => {
// if (localStorage.getItem('user')) {
// getLoginedUser(user)
// }
// }, [])
return
(
<
Navbar
bg
=
"
dark
"
variant
=
"
dark
"
>
...
...
@@ -12,7 +33,7 @@ function Menu() {
{
user
?
<>
<
div
className
=
'
ml-1 mr-2
'
style
=
{{
color
:
'
white
'
}}
>
{
userName
}
님
환영합니다
<
/div
>
<
div
className
=
'
ml-1 mr-2
'
style
=
{{
color
:
'
white
'
}}
>
{
response
.
data
}
님
환영합니다
<
/div
>
<
Nav
className
=
"
mr-auto
"
>
<
Nav
.
Link
href
=
"
/home
"
>
Home
<
/Nav.Link
>
<
Nav
.
Link
href
=
"
/profile
"
>
Profile
<
/Nav.Link
>
...
...
client/src/Pages/LogInPage.js
View file @
e15228f3
...
...
@@ -49,8 +49,8 @@ function LogIn() {
setError
(
''
)
const
response
=
await
axios
.
post
(
'
/auth/login
'
,
user
)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
console
.
log
(
user
.
email
)
handleLogin
(
user
.
email
)
console
.
log
(
response
.
data
)
handleLogin
(
response
.
data
.
userId
)
setSucces
(
true
)
}
catch
(
error
)
{
catchErrors
(
error
,
setError
)
...
...
client/src/Pages/ProfilePage.js
View file @
e15228f3
import
React
,
{
useState
}
from
'
react
'
;
import
ReactDOM
from
'
react-dom
'
;
import
Menu
from
'
../Components/Menu
'
;
import
{
Image
,
Button
,
Container
,
Form
}
from
'
react-bootstrap
'
;
import
{
Redirect
}
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
>
<
Menu
/>
{
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, useEffect } from 'react';
// import ReactDOM from 'react-dom';
// import Menu from '../Components/Menu';
// import { Image, Button, Container, Form, FormControl, Navbar, Nav, Row, Col, Dropdown, Carousel } from 'react-bootstrap';
// import { BrowserRouter as Router, Route, Redirect, Switch, Link } from 'react-router-dom';
// import axios from 'axios'
// // import userdefault from './KakaoTalk_20201230_153151693.png'
// import userimg from './KakaoTalk_20201230_153151693.png'
// // import img1 from './img_1.png'
// // import img2 from './img_2.png'
// // import img3 from './img_3.jpg'
// import DropdownItem from 'react-bootstrap/esm/DropdownItem';
// const INIT_USER = {
// username: '',
// email: '',
// nickname: ''
// }
// function ProfilePage() {
// const [user, setUser] = useState(INIT_USER)
// // const [userimg, setUserimg] = useState(img2)
// const [defaultImg, setDefaultImg] = useState(true)
// const [hidden, setHidden] = useState(true)
// async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
// const userid = localStorage.getItem('user')
// const response = await axios.post(`/users/${userid}`, { 'email': userid })
// setUser(response.data)
// }
// function handleSubmit(e) {
// e.preventDefault()
// if (hidden) {
// setHidden(false)
// } else {
// setHidden(true)
// }
// console.log(document.cookie)
// }
// function handleChange(e) {
// setUser({ ...user, 'nickname': e.target.value })
// }
// async function handleNicksave() {
// const userid = localStorage.getItem('user')
// await axios.put(`/users/${userid}`, user)
// }
// 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);
// };
// }
// }
// useEffect(() => {
// if (localStorage.getItem('user')) { //id뿐만아니라 토큰같은거를 확인 못하나 + 이런식으로 확인해도 되는것도 맞나
// getLoginedUser()
// }
// else {
// alert("로그인 후 이용하세요")
// window.location.href = '/login'
// }
// }, [])
// return (
// <div>
// <Menu />
// <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>
// )
// }
// export default ProfilePage
\ No newline at end of file
client/src/utils/auth.js
View file @
e15228f3
import
axios
from
"
axios
"
//자동으로 localstorage에 login이 생성됨
export
function
handleLogin
(
user
Email
)
{
localStorage
.
setItem
(
'
user
'
,
user
Email
)
export
function
handleLogin
(
user
Id
)
{
localStorage
.
setItem
(
'
user
'
,
user
Id
)
// localStorage.setItem('user', JSON.stringify({email: props.email}))
}
export
async
function
handleLogout
()
{
...
...
@@ -14,9 +14,9 @@ export async function handleLogout() {
//login이 됬는지 안됬는지 따질때 쓰임
export
function
isAuthenticated
()
{
const
user
Email
=
localStorage
.
getItem
(
'
user
'
)
if
(
user
Email
)
{
return
user
Email
const
user
Id
=
localStorage
.
getItem
(
'
user
'
)
if
(
user
Id
)
{
return
user
Id
}
else
{
return
false
}
...
...
package.json
View file @
e15228f3
...
...
@@ -18,6 +18,8 @@
"dependencies"
:
{
"
axios
"
:
"
^0.21.1
"
,
"
bcryptjs
"
:
"
^2.4.3
"
,
"
body-parser
"
:
"
^1.19.0
"
,
"
cors
"
:
"
^2.8.5
"
,
"
express
"
:
"
^4.17.1
"
,
"
jsonwebtoken
"
:
"
^8.5.1
"
,
"
mongoose
"
:
"
^5.11.9
"
,
...
...
server/controllers/auth.controller.js
View file @
e15228f3
...
...
@@ -25,7 +25,7 @@ const login = async (req, res) => {
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
if
(
passwordMatch
)
{
//토큰 생성
const
token
=
jwt
.
sign
({
user
Email
:
user
.
email
},
config
.
jwtSecret
,
{
expiresIn
:
'
7d
'
})
const
token
=
jwt
.
sign
({
user
Id
:
user
.
_id
},
config
.
jwtSecret
,
{
expiresIn
:
'
7d
'
})
//jwtSecret : 노출되면 안됨. 문자열
//expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기
...
...
@@ -39,7 +39,7 @@ const login = async (req, res) => {
secure
:
config
.
env
===
'
production
'
,
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
})
res
.
send
({
user
Email
:
user
.
email
})
res
.
send
({
user
Id
:
user
.
_id
})
}
else
{
// 5) 비밀번호가 틀리면 에러 반환
...
...
server/controllers/user.controller.js
View file @
e15228f3
...
...
@@ -68,6 +68,35 @@ const signup = async (req, res) => {
//res는 한번만 실행. 두번하면 에러 발생
}
const
loginNavbar
=
async
(
req
,
res
)
=>
{
try
{
let
user
=
await
User
.
findOne
(
req
.
body
).
select
(
'
username
'
).
exec
()
return
res
.
json
(
user
)
}
catch
(
error
)
{
alert
(
'
올바르지 못한 접근입니다.
'
)
}
}
// const loginNavbar = (req, res) => {
// res.json(req.login)
// }
// const userById = async (req, res, next, id) => {
// try {
// const user = await User.findById(id)
// if (!user) {
// res.status(404).send('사용자를 찾을 수 없습니다.')
// }
// req.login = user
// //req에 profile을 만들어서 user를 저장해줌
// next()
// //다음 middleware로 이동시킴 / 없으면 멈춤
// } catch (error) {
// console.log(error)
// res.status(500).send('사용자 아이디 검색 실패')
// }
// }
export
default
{
signup
}
export
default
{
signup
,
loginNavbar
}
// {} : 객체로 return함
\ No newline at end of file
server/routes/user.routes.js
View file @
e15228f3
...
...
@@ -7,6 +7,10 @@ const router = express.Router()
router
.
route
(
'
/users/signup
'
)
.
post
(
userCtrl
.
signup
)
router
.
route
(
'
/users/:userId
'
)
.
get
(
userCtrl
.
loginNavbar
)
// router.param('userId', userCtrl.userById)
// /api/users/signup로 들어오는 것을 post (method) 를 통해 useCtrl.signup 이것이 처리함
//browser에서 주소창에 치고 들어가면 get (method) 을 타고 들어간것임
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment