Skip to content
Snippets Groups Projects
Commit 3426f203 authored by Hyun Woo Jeong's avatar Hyun Woo Jeong
Browse files

FINAL commit

parent decfccfb
Branches main
No related tags found
No related merge requests found
Showing
with 75 additions and 155 deletions
......@@ -25,10 +25,10 @@ const upload = multer({
router.post("/", upload.array("img"), async function (req, res, next) {
if (!req.session.sessionid) {
console.log("No session error");
res.status(403).send('No Session!')
return;
}
console.log("POST /article");
const inputTitle = req.body.title
const inputContent = req.body.content
......@@ -51,23 +51,18 @@ router.post("/", upload.array("img"), async function (req, res, next) {
likes: [],
});
console.log('saved.')
res.send();
});
router.get("/", async (req, res) => {
console.log(path.join(process.cwd(), '/public'))
if (!req.session.sessionid) {
console.log("No session");
}
const articles = await articleService.findArticles(req.query.keyword ? req.query.keyword : null, req.query.criteria);
articles.forEach((article) => {
article.imageUrls.forEach(
(urls) => {
try {
//res.sendFile(path.join(__dirname, urls));
}
catch (err) {
console.log(err)
......@@ -79,7 +74,8 @@ router.get("/", async (req, res) => {
router.get("/:id", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session");
res.status(403).send('No Session!')
return;
}
const articles = await articleService.findArticleById(req.params.id);
res.send(JSON.stringify(articles));
......@@ -87,7 +83,8 @@ router.get("/:id", async (req, res) => {
router.delete("/:id", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session - del");
res.status(403).send('No Session!')
return;
}
const articles = await articleService.deleteArticle(req.params.id);
res.send(JSON.stringify(articles));
......@@ -95,7 +92,8 @@ router.delete("/:id", async (req, res) => {
router.get("/user/:id", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session");
res.status(403).send('No Session!')
return;
}
const articles = await articleService.findArticlesByAuthor(req.params.id);
res.send(JSON.stringify(articles));
......@@ -103,7 +101,8 @@ router.get("/user/:id", async (req, res) => {
router.post("/:id/comment", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session");
res.status(403).send('No Session!')
return;
}
const user = await userService.findUserByEmail(req.session.sessionid.email);
const data = {
......@@ -116,7 +115,8 @@ router.post("/:id/comment", async (req, res) => {
router.delete("/:articleid/comment/:commentid", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session");
res.status(403).send('No Session!')
return;
}
const articles = await articleService.deleteComment(req.params.articleid, req.params.commentid);
res.send(JSON.stringify(articles));
......@@ -124,7 +124,8 @@ router.delete("/:articleid/comment/:commentid", async (req, res) => {
router.put("/:id/like", async (req, res) => {
if (!req.session.sessionid) {
console.log("No session");
res.status(403).send('No Session!')
return;
}
const user = await userService.findUserByEmail(req.session.sessionid.email);
const articles = await articleService.setLike(req.params.id, user._id)
......
......@@ -127,10 +127,8 @@ const articleService = {
}
}
else {
console.log("invalid criteria.");
return;
}
},
async findArticleById(articleId) {
......
import express from 'express';
import moment from 'moment';
import userService from '../user/userService.js';
import userService from '../user/userService.js';
export const router = express.Router();
const sessionTime = 60; // 세션시간(임시)
// 세션시간(60분)
const sessionTime = 60;
router.post('/login', async (req, res) => {
/*
TODO: 토큰의 무결성 체크
토큰이 이상이 없다면, 로그인/회원가입 로직을 수행 후 jwt 쿠키를 보낸다.
*/
const expires = moment().add(sessionTime.toString(), 'm').toDate();
// 정보가 없다면 회원 가입 (강제?)
const user = await userService.findUserByEmail(req.body.email);
let userId = null;
if (!user) { // 유저가 없다면 회원 가입 후 세션 생성
......@@ -27,19 +23,15 @@ router.post('/login', async (req, res) => {
profileUrl: userProfilePicture,
},
}).then((user) => user._id);
console.log('new user saved!');
}
else {
userId = user._id;
}
console.log('login done');
req.session.sessionid = req.body; //프론트에서 건네받은 JWT로 세션 생성
res.cookie('name', JSON.stringify({ name: req.body.name, email: req.body.email, id: userId }), { expires }); //사용자 이름 쿠키
res.send(req.body.name); // 이름 보내서 뭐하게?
res.cookie('name', JSON.stringify({ name: req.body.name, email: req.body.email, id: userId }), { expires });
res.send(req.body.name);
});
router.get("/logout", (req, res) => {
......
import express from 'express';
import cors from 'cors';
import path from 'path';
import process from 'process';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import auth from './auth/authController.js';
import article from './article/articleController.js';
import connectDB from './db.js';
const app = express();
const PORT = 8080;
const sessionTime = 60; // 세션시간(임시)
// 세션시간(60분)
const sessionTime = 60;
connectDB();
......@@ -35,19 +30,17 @@ app.use(
origin: 'http://localhost:3000',
credentials: true,
})
); //cors 설정을 한다..
// app.use(express.static(path.join(process.cwd(), '../public')));
);
app.use(express.static('public'));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
console.log("hello")
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
}); // 서버 실행
});
app.use('/auth', auth);
......
import multer from 'multer';
// diskStorage를 사용할 경우
// const diskStorage = multer.diskStorage({
// destination: __dirname + '/uploads/',
// filename: (req, file, cb) => {
// cb(null, Buffer.from(file.originalname, 'latin1').toString('utf8'));
// },
// });
// memoryStorage를 사용할 경우
const multerStorage = multer.memoryStorage();
const upload = multer({ storage: multerStorage });
......@@ -16,8 +8,8 @@ const upload = multer({ storage: multerStorage });
// Parser 함수를 따로 구현하여 사용하도록 한다.
export const fileNameParser = fileName => Buffer.from(fileName, 'latin1').toString('utf8');
// 해당 예제에서는 파일 데이터 여러개, JSON으로 된 텍스트 데이터 하나를 받는 폼을 가정한다.
// 파일 5개, JSON으로 된 텍스트 데이터 하나를 받는 폼
export const articleFormDataHandler = upload.fields([
{ name: 'files', maxCount: 10 },
{ name: 'files', maxCount: 5 },
{ name: 'data', maxCount: 1 },
]);
\ No newline at end of file
......@@ -4,7 +4,6 @@ const GoogleProviderSchema = new mongoose.Schema({
id: {
type: String,
required: true,
//unique: true,
},
profileUrl: {
type: String,
......@@ -17,7 +16,6 @@ const UserSchema = new mongoose.Schema({
},
email: {
type: String,
//unique: true,
},
google: {
type: GoogleProviderSchema,
......
import "./css/App.css";
import { Routes, Route, Link, useNavigate, Navigate } from 'react-router-dom';
import React, { useEffect, useState, useContext } from 'react';
import React, { useState } from 'react';
import cookie from 'react-cookies';
import { Routes, Route, useNavigate } from 'react-router-dom';
import { UserContext } from './Context.js';
import Main from "./pages/Main.js";
import Login from "./pages/Login.js";
import Search from "./pages/Search.js";
import PostWrite from "./pages/PostWrite.js"
import PostRead from "./pages/PostRead.js"
import Header from "./components/Header.js";
import MyPage from "./pages/MyPage.js";
import axios from 'axios';
import MyPage from "./pages/MyPage.js";
axios.defaults.withCredentials = true;
function App() {
const [isloggedIn, SetIsloggedIn] = useState(false);
const [userName, setUserName] = useState(null);
const navigate = useNavigate();
......@@ -27,33 +26,22 @@ function App() {
}
const userinfo = cookie.load('name')
// 헤더 업데이트
const LogIn = (name) => {
// API 로그아웃 요청
// 로그아웃 성공시 헤더 반영
SetIsloggedIn(true)
setUserName(name)
console.log("Usercontext:LogIn")
console.log(isloggedIn)
};
const LogOut = () => {
// API 로그아웃 요청
requestLogout().then(
(response) => {
// 로그아웃 성공시 헤더 반영
SetIsloggedIn(false)
setUserName(null)
console.log("Usercontext:LogOut")
console.log(userName)
alert("정상적으로 로그아웃 되었습니다.")
MoveTo('/')
}
)
.catch((response) => {
console.log("error!:LogOut")
console.log(response)
.catch((err) => {
console.log(err)
})
};
......@@ -61,7 +49,6 @@ function App() {
return requestCheckSession();
};
return (
<div className="App">
<UserContext.Provider value={{ isloggedIn, userName, LogIn, LogOut, CheckSession }}>
......@@ -75,7 +62,6 @@ function App() {
<Route path="/mypage" element={<MyPage />}></Route>
</Routes>
</UserContext.Provider>
{/* <Footer/> */}
</div>
);
}
......@@ -83,7 +69,7 @@ function App() {
async function requestLogout() {
const response = await axios({
url: 'http://localhost:8080/auth/logout', // 통신할 웹문서
method: 'get', // 통신할 방식
method: 'get',
});
return response;
}
......@@ -91,7 +77,7 @@ async function requestLogout() {
async function requestCheckSession() {
const response = await axios({
url: 'http://localhost:8080/auth/session', // 통신할 웹문서
method: 'get', // 통신할 방식
method: 'get',
});
return response;
}
......
import React, { useEffect, useState } from "react";
import '../css/Article.css';
import { Routes, Route, Link, useNavigate, Navigate } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import React from "react";
import { useNavigate } from 'react-router-dom';
import { DateTime } from 'luxon';
import '../css/Article.css';
function Article({ data }) {
const {
_id, title, content, imageUrls, author,
......@@ -15,9 +14,9 @@ function Article({ data }) {
function MoveTo(link) {
navigate(link)
}
let listItem = []
listItem = imageUrls.map((el) => {
// http://localhost:8080/uploads/21701487062905.png
return (
<img
src={`http://localhost:8080/${el.replaceAll("\\", "/").substring(7)}`}
......@@ -29,7 +28,7 @@ function Article({ data }) {
const date = DateTime.fromISO(createdAt).toFormat('yyyy-MM-dd HH:mm');
return (
<div className="article" onClick={() => { console.log(_id); MoveTo(`/post/${_id}`) }}>
<div className="article" onClick={() => { MoveTo(`/post/${_id}`) }}>
<p className="keyword">#{keyword}</p>
<h1>{title}</h1>
<h3>{author.nickname} {date}</h3>
......
......@@ -39,7 +39,7 @@ function Comments({ data }) {
});
};
if (userinfo.id === author.google.id) {
if (userinfo.id === author._id) {
return (
<div class="comment" style={{ display: 'flex' }}>
<p>{author.nickname}</p>
......
import { GoogleLogin } from "@react-oauth/google";
import { GoogleOAuthProvider } from "@react-oauth/google";
import { useNavigate, Navigate } from "react-router-dom";
import { useCookies } from 'react-cookie'
import React, { useEffect, useState, useContext } from 'react';
import { useNavigate } from "react-router-dom";
import React, { useContext } from 'react';
import { UserContext } from '../Context.js';
// 안써도 자동으로 한국 시간을 불러온다. 명확하게 하기 위해 import
import moment from 'moment';
import 'moment/locale/ko';
import base64 from 'base-64';
import axios from 'axios';
......@@ -18,7 +15,6 @@ axios.defaults.withCredentials = true;
const GoogleLoginButton = () => {
const userContext = useContext(UserContext);
const [cookies, setCookie, removeCookie] = useCookies();
const clientId = '716858812522-rb0pfisq317unkh4so5hvbu16p19kqp8.apps.googleusercontent.com'
const navigate = useNavigate();
......@@ -38,14 +34,12 @@ const GoogleLoginButton = () => {
requestLogin(obj).then(
(response) => {
console.log(response);
userContext.LogIn(response.data);
goMain();
}
)
}}
onFailure={(err) => {
console.log("Login Failed");
console.log(err);
}}
/>
......@@ -53,8 +47,6 @@ const GoogleLoginButton = () => {
<br></br>
</div>
</GoogleOAuthProvider>
);
};
......@@ -68,8 +60,8 @@ function b64DecodeUnicode(str) {
async function requestLogin(payloadObj) {
const response = await axios({
url: 'http://localhost:8080/auth/login', // 통신할 웹문서
method: 'post', // 통신할 방식
url: 'http://localhost:8080/auth/login',
method: 'post',
data: payloadObj
});
return response;
......
import React, { useContext } from 'react';
import { Link, useNavigate } from "react-router-dom";
import logo from '../logo.png';
import '../css/Header.css';
import { UserContext } from '../Context.js';
import React, { useEffect, useState, useContext } from 'react';
import { Link, useNavigate, Navigate } from "react-router-dom";
function ButtonLink({ link, status, children }) {
const userContext = useContext(UserContext);
......@@ -23,7 +21,6 @@ function ButtonLink({ link, status, children }) {
{children}
</button>
</div>
)
}
else {
......@@ -36,11 +33,9 @@ function ButtonLink({ link, status, children }) {
</div>
)
}
}
function Header({ cookie }) {
return (
<div className="header">
<ButtonLink link='/'>
......@@ -53,16 +48,10 @@ function Header({ cookie }) {
<li><ButtonLink link='/search'>검색</ButtonLink></li>
<li><ButtonLink link='/postwrite'>포스트 작성</ButtonLink></li>
<li><ButtonLink link={cookie ? '/' : '/login'} status={cookie ? true : false}>{cookie ? '로그아웃' : '로그인'}</ButtonLink></li> {/*로그인 여부 로직 구현 필요*/}
{/* { Object.keys(user).length != 0 ?
<li><Link to={`/profile/${getUserId()}`}>profile</Link>/<span onClick={logout}>logout</span></li> :
<li><Link to="/login">login</Link></li>
} */}
</ul>
</ul>
</div>
);
}
export default Header;
import { Map, MapMarker } from "react-kakao-maps-sdk";
import React, { useRef, useState, useEffect, useContext } from 'react';
import React, { useState } from 'react';
const { kakao } = window;
function MapLocator({ loc, keyword }) {
// 아주대학교를 기본 위치로 설정
const [info, setInfo] = useState()
const [markers, setMarkers] = useState([])
const [pagination, setPagination] = useState()
// const [info, setInfo] = useState()
// const [markers, setMarkers] = useState([])
// const [pagination, setPagination] = useState()
const [map, setMap] = useState()
const defaultCenter = { lat: loc.lat, lng: loc.lng }
return (
<div className="UserInput">
<div style={{ display: 'flex' }}>
<Map // 지도를 표시할 Container
<Map
center={defaultCenter}
style={{
// 지도의 크기
width: "450px",
height: "450px"
}}
......
......@@ -6,9 +6,7 @@ import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
// <React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
// </React.StrictMode>
);
......@@ -32,7 +32,6 @@ function Main() {
useEffect(() => {
requestSortArticle("time")
.then((response) => {
console.log(response)
setArticleList(response.data)
});
}, []);
......@@ -40,7 +39,6 @@ function Main() {
const handleSortChange = (event) => {
requestSortArticle(event.target.value)
.then((response) => {
console.log(response)
setArticleList(response.data)
})
};
......@@ -63,8 +61,8 @@ function Main() {
async function requestSortArticle(crit) {
const response = await axios({
url: `http://localhost:8080/article/?criteria=${crit}`, // 통신할 웹문서
method: 'get', // 통신할 방식
url: `http://localhost:8080/article/?criteria=${crit}`,
method: 'get',
});
return response;
}
......
......@@ -43,8 +43,8 @@ function MyPage() {
async function requestArticles(id) {
const response = await axios({
url: `http://localhost:8080/article/user/${id}`, // 통신할 웹문서
method: 'get', // 통신할 방식
url: `http://localhost:8080/article/user/${id}`,
method: 'get',
});
return response;
}
......
......@@ -22,7 +22,6 @@ function PostRead() {
navigate(link)
}
useEffect(() => {
console.log(userinfo);
userContext.CheckSession()
.then((response) => {
if (!response.data) {
......@@ -34,12 +33,10 @@ function PostRead() {
}
})
.then((response) => {
console.log(response)
setArticle(response.data)
})
.catch((response) => {
console.log("error!:LogOut")
console.log(response)
.catch((err) => {
console.log(err)
})
}, []);
......@@ -86,7 +83,6 @@ function PostRead() {
function DelButton({ isThatYou, target }) {
function deleteArticle() {
console.log(target._id)
requestDeleteArticleById(target._id).then(res => {
alert("게시글이 삭제되었습니다");
MoveTo('/')
......@@ -102,8 +98,8 @@ function PostRead() {
else {
return null
}
}
if (article) {
return (
<>
......@@ -146,16 +142,16 @@ function PostRead() {
async function requestLoadArticleById(id) {
const response = await axios({
url: `http://localhost:8080/article/${id}`, // 통신할 웹문서
method: 'get', // 통신할 방식
url: `http://localhost:8080/article/${id}`,
method: 'get',
});
return response;
}
async function requestDeleteArticleById(id) {
const response = await axios({
url: `http://localhost:8080/article/${id}`, // 통신할 웹문서
method: 'delete', // 통신할 방식
url: `http://localhost:8080/article/${id}`,
method: 'delete',
});
return response;
}
......
......@@ -26,9 +26,8 @@ function PostWrite() {
MoveTo('/login');
}
})
.catch((response) => {
console.log("error!:LogOut")
console.log(response)
.catch((err) => {
console.log(err)
})
});
......@@ -62,7 +61,6 @@ function PostWrite() {
Array.from(e.target.files).forEach((file) => {
const reader = new FileReader();
console.log(file)
reader.readAsDataURL(file);
reader.onloadend = () => {
previewImg.imageUrls.push(reader.result);
......@@ -174,8 +172,4 @@ function PostWrite() {
)
}
/*
*/
export default PostWrite;
\ No newline at end of file
......@@ -30,9 +30,8 @@ function Search(props) {
MoveTo('/login');
}
})
.catch((response) => {
console.log("error!:LogOut")
console.log(response)
.catch((err) => {
console.log(err)
})
}, []);
......@@ -42,7 +41,6 @@ function Search(props) {
}
requestLoadArticleByKeyword(location.keyword)
.then((response) => {
console.log(response);
setArticleList(response.data);
});
}, [location.keyword]);
......@@ -65,7 +63,6 @@ function Search(props) {
}
requestLoadArticleByKeyword(location.keyword)
.then((response) => {
console.log(response);
setArticleList(response.data);
});
};
......@@ -87,8 +84,8 @@ function Search(props) {
async function requestLoadArticleByKeyword(keyword) {
const response = await axios({
url: `http://localhost:8080/article/?keyword=${keyword}`, // 통신할 웹문서
method: 'get', // 통신할 방식
url: `http://localhost:8080/article/?keyword=${keyword}`,
method: 'get',
});
return response;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment