Commit 94549472 authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

profile Page

parent 706ed28d
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import Menu from '../Components/Menu';
import { Image, Button, Container, Form, FormControl, Navbar, Nav } from 'react-bootstrap';
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 img1 from './img_1.png'
import img2 from './img_2.png'
import img3 from './img_3.jpg'
import DropdownItem from 'react-bootstrap/esm/DropdownItem';
//localStorage에 아이디? 가있는걸로 db에서 그 사람꺼 찾은(findOne 이런걸로) 다음에 닉네임도 불러오고 여기서 수정할 수 있는 기능을 만들자!
////////////////////////////////////////////////////////////////////////////////
// async function sending() {
// const info = await fetch(`/api/users/signup`, {
// method: "POST",
// headers: {
// "Content-type": 'application/json'
// },
// body: JSON.stringify({
// name: userName,
// email: userEmail,
// password: "123123123",
// nickname: userNickname
// })
// })
// const data = await info.json()
// console.log(data)
// }
////////////////////////////////////////////////////////////////////////////////
const INIT_USER = {
name: '',
username: '',
email: '',
nickname: ''
}
......@@ -39,59 +21,32 @@ const INIT_USER = {
function ProfilePage() {
const [user, setUser] = useState(INIT_USER)
const [userimg, setUserimg] = useState(img2)
const [defaultImg, setDefaultImg] = useState(true)
const [hidden, setHidden] = useState(true)
function setlocal() {
localStorage.setItem('_id', '5ff77d56da609732c001b392')
}
async function loginedinfo() {
const userid = localStorage.getItem('_id')
const response = await axios.post(`/api/users/${userid}`, user)
setUser(response.data[1])
console.log(user)
}
async function getInfo() { //db에서 로그인 정보 가져옴
const response = await axios.get('/api/users')
console.log(response.data)
setUser(response.data[1])
console.log(user)
}
async function makeLogin() { //로그인 상태로 만들어줌
const info = await axios.get('/api/users')
console.log('info', info.data)
setUser(info.data[1])
await axios.post(`/api/users/`, user)
localStorage.setItem('loginStatus', 'true')
localStorage.setItem('_id', user._id)
console.log(user)
}
async function authinfo() { //id로 db에서 찾아오기
const userid = { '_id': localStorage.getItem('_id') }
const response = await axios.post(`/api/users/${userid._id}`, userid)
console.log(response.data)
async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
const userid = localStorage.getItem('user')
const response = await axios.post(`/users/${userid}`, { 'email': userid })
setUser(response.data)
}
//@@그다음에 찾아온걸로 다시 띄우기
//@@닉네임 수정하기
function handleEditnick() {
function handleSubmit(e) {
e.preventDefault()
if (hidden) {
setHidden(false)
} else {
setUser({ ...user, 'nickname': document.getElementById("inputNick").value })
setHidden(true)
}
console.log(document.cookie)
}
async function handleNicksave(){
const userid = { '_id': localStorage.getItem('_id') }
await axios.put(`/api/users/${userid._id}`, user)
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'>에 띄우기
......@@ -126,59 +81,99 @@ function ProfilePage() {
};
}
}
useEffect(() => {
if (localStorage.getItem('user')) { //id뿐만아니라 토큰같은거를 확인 못하나 + 이런식으로 확인해도 되는것도 맞나
getLoginedUser()
}
else {
alert("로그인 후 이용하세요")
window.location.href = '/login'
}
}, [])
return (
<div>
<Menu />
<Button onClick={setlocal}>로컬에 추가</Button>
<Button onClick={loginedinfo}>로그인된 정보 불러오기</Button>
<Button onClick={getInfo}>불러오기</Button>
<Button onClick={makeLogin}>로그인 상태로 만들기</Button>
<Button onClick={authinfo}>로그인 유저 불러오기</Button>
{/* <Button onClick={sending}>보내기</Button> */}
<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.name} 환영합니다 !</h4>
<h4 className="text-center mb-5">{user.username} 환영합니다 !</h4>
<div className="d-flex justify-content-center mb-3" id="defaultImg">
<Image src={userdefault} width="300px" roundedCircle />
<Image src={userimg} width="300px" roundedCircle />
</div>
<div className="d-flex justify-content-center">
<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>
</div>
</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.name}</div>
<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" style={{ fontWeight: "bold", fontSize: "x-large" }}>
<Form className="d-flex justify-content-center" onSubmit={handleSubmit} style={{ fontWeight: "bold", fontSize: "x-large" }}>
별명 :
<div id="mainNick" hidden={!hidden}>
<div hidden={!hidden}>
{user.nickname}
</div>
<Form.Control id="inputNick" type="name" defaultValue={user.nickname} style={{ width: "40%" }} size="sm" hidden={hidden} />
<Button className="ml-3" variant="outline-primary" size="sm" onClick={handleEditnick}>수정</Button>
<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">
<span>
<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>
</span>
</Form>
</div>
</div>
</Container>
......
......@@ -2,7 +2,7 @@ import axios from "axios"
//자동으로 localstorage에 login이 생성됨
export function handleLogin(props) {
localStorage.setItem('user', JSON.stringify({email: props.email}))
localStorage.setItem('user', props.email)
}
......
......@@ -3,41 +3,19 @@ import bcrypt from "bcryptjs";
import jwt from 'jsonwebtoken'
import config from "../config.js"
const mklogin = async (req, res) => {
const { email } = req.body
console.log(email)
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){
console.log(error)
res.send(500).send('로그인에러')
}
}
const getinfo = (req, res) => {
const getimage = (req, res) => {
// 1) 로그인 된 사용자 정보를 가져오기
// 일단 1명으로 해놓고 설정
// let users = await User.find().select('name nickname email password').exec()
// return res.json(users)
res.send('여기가 프로필이다.')
console.log("ddd")
//try catch로 오류잡는거 추가해야함
}
export default { mklogin , getinfo }
\ No newline at end of file
export default { getimage }
\ No newline at end of file
......@@ -13,67 +13,18 @@ const signup = async (req, res) => {
//req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
console.log(username, 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 hash = await bcrypt.hash(password, 10)
// const newUser = await new User({
// name,
// 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.status(500).send('User signup error')
// }
// //newUSer (객체)를 json형식으로 바꿔서 객체열로 보냄
// //res : 응답하는 객체
// //응답안할 시 browser에서 빙빙돌다 에러 발생 -> 꼭 붙여줘야됨!
// //res는 한번만 실행. 두번하면 에러 발생
const { email } = req.body
console.log(email, 'ddd')
try {
if (!isLength(username, {min: 3, max: 10})){
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})) {
} else if (!isLength(nickname, { min: 2, max: 10 })) {
return res.status(422).send('별명은 2-10자 사이입니다.')
} else if (!isLength(password, {min: 6})) {
} 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, {
......@@ -87,8 +38,8 @@ const signup = async (req, res) => {
// }
// 기존의 email이 있으면 나오는 error (unique)
const user = await User.findOne({email})
if(user) {
const user = await User.findOne({ email })
if (user) {
return res.status(422).send(`${email}이 이미 사용중입니다.`)
}
......@@ -112,33 +63,31 @@ const signup = async (req, res) => {
console.log(error)
res.status(500).send('회원가입 에러발생하였습니다.')
}
}
// const list=async(req, res)=>{
// let users = await User.find().select('name nickname email password').exec()
// return res.json(users)
// }
const hello = async (req, res) => {
let users = await User.find().select('name nickname email _id').exec()
return res.json(users)
}
const authuser = async (req, res) => {
let user = await User.findOne( req.body ).select('name email nickname').exec()
console.log(user)
return res.json(user)
}
const chnick = async (req, res) =>{
let user = {"dusdn":"ddd"}
console.log("변경~")
return res.json(user)
const logineduser = async (req, res) => {
try {
let user = await User.findOne(req.body).select('username email nickname').exec()
return res.json(user)
} catch (error) {
alert('올바르지 못한 접근입니다.')
}
}
const changenick = async (req, res) => {
try {
const newnick = req.body.nickname
await User.update({ 'username': req.body.username }, { 'nickname': newnick })
} catch (error) {
alert('올바르지 못한 접근입니다.')
}
}
export default { signup, hello, authuser, chnick }
export default { signup, hello, logineduser, changenick }
// {} : 객체로 return함
\ No newline at end of file
import mongoose from 'mongoose'
const { Image } = mongoose.Schema.Types
const ChatSchema = new mongoose.Schema({
defaultImg: {
type: Image,
required: true,
},
}, {
timestamps: true
})
export default mongoose.models.User || mongoose.model('chat', ChatSchema)
\ No newline at end of file
......@@ -4,9 +4,8 @@ import profileCtrl from "../controllers/profile.controller.js";
const router = express.Router()
router.route('/api/profile')
.post(profileCtrl.mklogin)
.get(profileCtrl.getinfo)
router.route('/profile')
.get(profileCtrl.getimage)
......
......@@ -8,14 +8,10 @@ router.route('/users/signup')
.post(userCtrl.signup)
.get(userCtrl.hello)
router.route('api/users/')
.post(userCtrl.signup)
.get(userCtrl.hello)
router.route(`/users/:userId`)
.post(userCtrl.logineduser)
.put(userCtrl.changenick)
router.route(`/api/users/:userId`)
.post(userCtrl.authuser)
.put(userCtrl.chnick)
// router.route('/api/users/signup/:userId') //로그인한 사람의 정보만 가져오도록
......
......@@ -2,6 +2,7 @@ import express from 'express'
import connectDb from './utils/connectDb.js'
import userRouter from './routes/user.routes.js'
import authRouter from './routes/auth.routes.js'
import profileRouter from './routes/profile.routes.js'
connectDb()
......@@ -14,6 +15,7 @@ app.use(express.json())
app.use(userRouter)
app.use(authRouter)
app.use(profileRouter)
//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