Commit 519d8e15 authored by Kim, Subin's avatar Kim, Subin
Browse files

context

parent 617ce4d0
...@@ -10,38 +10,38 @@ import StudyPlanPage from "./pages/StudyPlanPage"; ...@@ -10,38 +10,38 @@ import StudyPlanPage from "./pages/StudyPlanPage";
import StudyPlanEditPage from "./pages/StudyPlanEditPage"; import StudyPlanEditPage from "./pages/StudyPlanEditPage";
import SubjectEditPage from "./pages/SubjectEditPage"; import SubjectEditPage from "./pages/SubjectEditPage";
import AdminPage from "./pages/Admin/AdminPage"; import AdminPage from "./pages/Admin/AdminPage";
import { AuthProvider } from "./utils/context.js"; import { AuthProvider } from "./utils/context";
import PrivateRoute from "./components/PrivateRoute"; import PrivateRoute from "./components/PrivateRoute";
import ErrorPage from "./pages/ErrorPage"; import ErrorPage from "./pages/ErrorPage";
function App() { function App() {
return ( return (
<AuthProvider >
<Router basename={process.env.PUBLIC_URL}> <Router basename={process.env.PUBLIC_URL}>
<AuthProvider>
<div id="box" className="container position-relative vh-100 mx-sm-auto"> <div id="box" className="container position-relative vh-100 mx-sm-auto">
<Switch> <Switch>
<Route exact path="/" component={LoginPage} /> <Route exact path="/" component={LoginPage} />
<Route path="/login" component={LoginPage} /> <Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignupPage} /> <Route path="/signup" component={SignupPage} />
<Route path="/home" component={HomePage} /> <PrivateRoute path="/home" component={HomePage} />
<Route path="/schedule/edit" component={ScheduleEditPage} /> <PrivateRoute path="/schedule/edit/:scheduleId" component={ScheduleEditPage} />
<Route path="/schedule/:date" component={SchedulePage} /> <PrivateRoute path="/schedule/edit" component={ScheduleEditPage} />
<Route path="/todo/:date" component={ToDoPage} /> <PrivateRoute path="/schedule/:date" component={SchedulePage} />
<Route path="/studyplan/edit" component={StudyPlanEditPage} /> <PrivateRoute path="/todo/:date" component={ToDoPage} />
<Route path="/studyplan/:" component={StudyPlanPage} /> <PrivateRoute path="/studyplan/edit" component={StudyPlanEditPage} />
<Route path="/studyplan" component={StudyPlanListPage} /> <PrivateRoute path="/studyplan/:" component={StudyPlanPage} />
<Route path="/subject/edit/:subjectId" component={SubjectEditPage} /> <PrivateRoute path="/studyplan" component={StudyPlanListPage} />
<Route path="/subject/edit" component={SubjectEditPage} /> <PrivateRoute path="/subject/edit/:subjectId" component={SubjectEditPage} />
<Route path="/admin/edit/:scheduleId" component={ScheduleEditPage} /> <PrivateRoute path="/subject/edit" component={SubjectEditPage} />
<Route path="/admin/edit" component={ScheduleEditPage} /> <PrivateRoute path="/admin/edit/:scheduleId" component={ScheduleEditPage} role="admin" />
<Route path="/admin" component={AdminPage} /> <PrivateRoute path="/admin/edit" component={ScheduleEditPage} role="admin" />
{/* <PrivateRoute path="/admin" component={AdminPage} role="admin" /> */} <PrivateRoute path="/admin" component={AdminPage} role="admin" />
<Route component={ErrorPage} /> <Route component={ErrorPage} />
</Switch> </Switch>
</div> </div>
</Router>
</AuthProvider> </AuthProvider>
</Router>
); );
} }
......
...@@ -2,15 +2,15 @@ import axios from "axios"; ...@@ -2,15 +2,15 @@ import axios from "axios";
import baseUrl from "../utils/baseUrl.js"; import baseUrl from "../utils/baseUrl.js";
const getUser = async () => { const getUser = async () => {
const url = `${baseUrl}/api/auth/user` const url = `${baseUrl}/api/auth`
const { data } = await axios.get(url) const { data } = await axios.get(url)
return data return data
} }
const signup = async (user) => { const signup = async (user) => {
const url = `${baseUrl}/api/auth/signup`; const url = `${baseUrl}/api/auth/signup`;
const { data } = await axios.post(url, user); const { data, status } = await axios.post(url, user);
return data return { data, status }
} }
const login = async (user) => { const login = async (user) => {
......
...@@ -2,6 +2,9 @@ import { useState, useEffect, useRef } from "react"; ...@@ -2,6 +2,9 @@ import { useState, useEffect, useRef } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import CalendarBtn from "../Buttons/CalendarBtn.js"; import CalendarBtn from "../Buttons/CalendarBtn.js";
import DatePickerModal from "../Modal/DatePickerModal.js"; import DatePickerModal from "../Modal/DatePickerModal.js";
import scheduleApi from "../../apis/schedule.api";
import { useAuth } from "../../utils/context.js";
import catchErrors from "../../utils/catchErrors.js";
import moment from 'moment'; import moment from 'moment';
import FullCalendar from '@fullcalendar/react'; import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid'; import dayGridPlugin from '@fullcalendar/daygrid';
...@@ -10,9 +13,13 @@ import bootstrapPlugin from '@fullcalendar/bootstrap'; ...@@ -10,9 +13,13 @@ import bootstrapPlugin from '@fullcalendar/bootstrap';
import '@fortawesome/fontawesome-free/css/all.css'; import '@fortawesome/fontawesome-free/css/all.css';
const Monthly = () => { const Monthly = () => {
const { user } = useAuth()
console.log("msds==",user)
const [initialDate, setInitialDate] = useState(moment().format('YYYY-MM-DD')) const [initialDate, setInitialDate] = useState(moment().format('YYYY-MM-DD'))
const [changeDate, setChangeDate] = useState(moment().format('YYYY-MM-DD')) const [changeDate, setChangeDate] = useState(moment().format('YYYY-MM-DD'))
const [show, setShow] = useState(false) const [show, setShow] = useState(false)
const [scheduleList, setScheduleList] = useState([])
const [error, setError] = useState("")
const calendarRef = useRef(null) const calendarRef = useRef(null)
const calenIconRef = useRef(null) const calenIconRef = useRef(null)
let calendar = null let calendar = null
...@@ -45,10 +52,27 @@ const Monthly = () => { ...@@ -45,10 +52,27 @@ const Monthly = () => {
useEffect(() => { useEffect(() => {
calendar.gotoDate(changeDate) calendar.gotoDate(changeDate)
getAll()
}, [changeDate]) }, [changeDate])
useEffect(() => {
calendar.addEventSource(scheduleList)
}, [scheduleList])
async function getAll() {
try {
setError("")
console.log("home user",user)
const resList = await scheduleApi.getbyMonth(changeDate, user.id)
setScheduleList(resList)
} catch (error) {
catchErrors(error, setError)
}
}
return ( return (
<> <>
{console.log("user scheduleList==",scheduleList)}
<div ref={calenIconRef} className="position-absolute" style={{ top: "9px", right: "8px" }}> <div ref={calenIconRef} className="position-absolute" style={{ top: "9px", right: "8px" }}>
<CalendarBtn date={moment(initialDate).format('DD')} /> <CalendarBtn date={moment(initialDate).format('DD')} />
</div> </div>
...@@ -98,7 +122,7 @@ const Monthly = () => { ...@@ -98,7 +122,7 @@ const Monthly = () => {
dateClick={({ dateStr }) => history.push(`/schedule/${dateStr}`)} dateClick={({ dateStr }) => history.push(`/schedule/${dateStr}`)}
timeZone="local" timeZone="local"
themeSystem='bootstrap' themeSystem='bootstrap'
// eventLimit="true" eventLimit="3"
height='80vh' height='80vh'
/> />
<DatePickerModal initialDate={initialDate} changeDate={changeDate} setChangeDate={setChangeDate} show={show} setShow={setShow} /> <DatePickerModal initialDate={initialDate} changeDate={changeDate} setChangeDate={setChangeDate} show={show} setShow={setShow} />
......
...@@ -2,17 +2,19 @@ import { useState, useEffect } from "react"; ...@@ -2,17 +2,19 @@ import { useState, useEffect } from "react";
import { Redirect, useParams } from "react-router-dom"; import { Redirect, useParams } from "react-router-dom";
import BtnGroup from "../Buttons/BtnGroup.js"; import BtnGroup from "../Buttons/BtnGroup.js";
import scheduleApi from "../../apis/schedule.api"; import scheduleApi from "../../apis/schedule.api";
import { useAuth } from "../../utils/context.js";
import catchErrors from "../../utils/catchErrors.js"; import catchErrors from "../../utils/catchErrors.js";
import styles from "./form.module.scss"; import styles from "./form.module.scss";
const ScheduleForm = () => { const ScheduleForm = () => {
const { user } = useAuth()
const [schedule, setSchedule] = useState({ const [schedule, setSchedule] = useState({
title: "", title: "",
startDate: "", startDate: "",
endDate: "", endDate: "",
startTime: "", startTime: "",
endTime: "", endTime: "",
allDay: "", allDay: user.role === "admin" ? "on" : "",
location: "", location: "",
memo: "" memo: ""
}) })
...@@ -47,7 +49,7 @@ const ScheduleForm = () => { ...@@ -47,7 +49,7 @@ const ScheduleForm = () => {
async function getOne(id) { async function getOne(id) {
try { try {
setError("") setError("")
const resSchedule = await scheduleApi.getOne(id) const resSchedule = await scheduleApi.getOne(id, user.id)
setSchedule({ ...schedule, ...resSchedule }) setSchedule({ ...schedule, ...resSchedule })
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -70,11 +72,11 @@ const ScheduleForm = () => { ...@@ -70,11 +72,11 @@ const ScheduleForm = () => {
try { try {
setError("") setError("")
if (scheduleId) { if (scheduleId) {
await scheduleApi.edit(scheduleId, schedule) await scheduleApi.edit(scheduleId, schedule, user.id)
alert('해당 일정이 성공적으로 수정되었습니다.') alert('해당 일정이 성공적으로 수정되었습니다.')
} }
else { else {
await scheduleApi.submit(schedule) await scheduleApi.submit(schedule, user.id)
alert('해당 일정이 성공적으로 등록되었습니다.') alert('해당 일정이 성공적으로 등록되었습니다.')
} }
setSuccess(true) setSuccess(true)
...@@ -84,9 +86,8 @@ const ScheduleForm = () => { ...@@ -84,9 +86,8 @@ const ScheduleForm = () => {
} }
if (success) { if (success) {
// if () return <Redirect to="/admin" /> if (user.role === "admin") return <Redirect to="/admin" />
// else return <Redirect to="/home" /> else return <Redirect to="/home" />
return <Redirect to="/admin" />
} }
return ( return (
...@@ -96,27 +97,27 @@ const ScheduleForm = () => { ...@@ -96,27 +97,27 @@ const ScheduleForm = () => {
</div> </div>
<div className="d-flex mb-4"> <div className="d-flex mb-4">
<label className="col col-form-label align-self-center py-0">시작</label> <label className="col col-form-label align-self-center py-0">시작</label>
<div className={schedule.allDay === "on" ? "col-7" : "col-5"}> <div className={(user.role === "admin" || schedule.allDay === "on") ? "col-7" : "col-5"}>
<input className={`form-control shadow-none ${styles.dateInput}`} type="date" name="startDate" value={schedule.startDate} aria-label="startDate" onChange={handleChange} /> <input className={`form-control shadow-none ${styles.dateInput}`} type="date" name="startDate" value={schedule.startDate} aria-label="startDate" onChange={handleChange} />
</div> </div>
<div className={"col-5 " + (schedule.allDay === "on" ? "d-none" : "d-block")}> <div className={"col-5 " + ((user.role === "admin" || schedule.allDay === "on") ? "d-none" : "d-block")}>
<input className={`form-control shadow-none ${styles.dateInput}`} type="time" name="startTime" aria-label="startTime" onChange={handleChange} /> <input className={`form-control shadow-none ${styles.dateInput}`} type="time" name="startTime" aria-label="startTime" onChange={handleChange} />
</div> </div>
</div> </div>
<div className="d-flex mb-3"> <div className={"d-flex " + (user.role === "admin" ? "mb-5" : "mb-3")}>
<label className="col col-form-label align-self-center py-0">종료</label> <label className="col col-form-label align-self-center py-0">종료</label>
<div className={schedule.allDay === "on" ? "col-7" : "col-5"}> <div className={(user.role === "admin" || schedule.allDay === "on") ? "col-7" : "col-5"}>
<input className={`form-control shadow-none ${styles.dateInput}`} type="date" name="endDate" value={schedule.endDate} aria-label="endDate" onChange={handleChange} /> <input className={`form-control shadow-none ${styles.dateInput}`} type="date" name="endDate" value={schedule.endDate} aria-label="endDate" onChange={handleChange} />
</div> </div>
<div className={"col-5 " + (schedule.allDay === "on" ? "d-none" : "d-block")}> <div className={"col-5 " + ((user.role === "admin" || schedule.allDay === "on") ? "d-none" : "d-block")}>
<input className={`form-control shadow-none ${styles.dateInput}`} type="time" name="endTime" value={schedule.endTime} aria-label="endTime" onChange={handleChange} /> <input className={`form-control shadow-none ${styles.dateInput}`} type="time" name="endTime" value={schedule.endTime} aria-label="endTime" onChange={handleChange} />
</div> </div>
</div> </div>
<div className="d-flex justify-content-end form-check mb-4"> <div className={"d-flex justify-content-end form-check mb-4 " + (user.role === "admin" ? "d-none" : "d-block")}>
<input className={`form-check-input shadow-none ${styles.checkBox}`} type="checkbox" id="allDay" name="allDay" onChange={handleChange} /> <input className={`form-check-input shadow-none ${styles.checkBox}`} type="checkbox" id="allDay" name="allDay" onChange={handleChange} checked={schedule.allDay === "on" ? true : false} />
<label className="form-check-label ms-2" htmlFor="allDay">하루 종일</label> <label className="form-check-label ms-2" htmlFor="allDay">하루 종일</label>
</div> </div>52
<div className="d-flex justify-content-between align-items-center mb-4"> <div className={"d-flex justify-content-between align-items-center mb-4 " + (user.role === "admin" ? "d-none" : "d-block")}>
<i className="col bi bi-geo-alt fs-3"></i> <i className="col bi bi-geo-alt fs-3"></i>
<div className="col-10"> <div className="col-10">
<input className={`form-control shadow-none rounded-0 px-1 ${styles.textInput}`} type="text" name="location" placeholder="장소" aria-label="location" onChange={handleChange} /> <input className={`form-control shadow-none rounded-0 px-1 ${styles.textInput}`} type="text" name="location" placeholder="장소" aria-label="location" onChange={handleChange} />
......
...@@ -4,7 +4,7 @@ import moment from "moment"; ...@@ -4,7 +4,7 @@ import moment from "moment";
import styles from "./menu.module.scss"; import styles from "./menu.module.scss";
const Menu = () => { const Menu = () => {
const { logout } = useAuth(); const { user, logout } = useAuth();
return ( return (
<> <>
...@@ -15,7 +15,7 @@ const Menu = () => { ...@@ -15,7 +15,7 @@ const Menu = () => {
<div className="d-flex flex-column" style={{ transition: ".15s ease", height: "inherit" }}> <div className="d-flex flex-column" style={{ transition: ".15s ease", height: "inherit" }}>
<button type="button" className={`btn-close btn-close-white btn-lg position-absolute ${styles.close}`} data-bs-toggle="collapse" data-bs-target="#menuContent" aria-controls="menuContent" aria-expanded="true" aria-label="menu"></button> <button type="button" className={`btn-close btn-close-white btn-lg position-absolute ${styles.close}`} data-bs-toggle="collapse" data-bs-target="#menuContent" aria-controls="menuContent" aria-expanded="true" aria-label="menu"></button>
<div className="d-flex flex-column align-items-center text-white py-5" style={{ backgroundColor: "crimson" }}> <div className="d-flex flex-column align-items-center text-white py-5" style={{ backgroundColor: "crimson" }}>
<h1 className="my-3">김수빈 </h1> <h1 className="my-3">{user.name} </h1>
<h2 className="my-2">오늘의 목표 95% 달성!</h2> <h2 className="my-2">오늘의 목표 95% 달성!</h2>
</div> </div>
<div className="d-flex flex-column justify-content-between flex-grow-1 py-4 ps-3 text-dark" > <div className="d-flex flex-column justify-content-between flex-grow-1 py-4 ps-3 text-dark" >
......
...@@ -4,29 +4,26 @@ import ErrorPage from "../pages/ErrorPage"; ...@@ -4,29 +4,26 @@ import ErrorPage from "../pages/ErrorPage";
const PrivateRoute = ({ component: Component, ...rest }) => { const PrivateRoute = ({ component: Component, ...rest }) => {
const { user } = useAuth(); const { user } = useAuth();
// return (
// <Route
// {...rest}
// render={(props) => {
// if (user) {
// if (rest.role) {
// if (rest.role === user.role) {
// return <Component {...props} />;
// } else {
// return <ErrorPage />
// }
// } else {
// return <Component {...props} />
// }
// } else {
// return <Redirect to="/login" />;
// }
// }}
// />
// );
return ( return (
<Route {...rest} render={(props) => <Component {...props} />} /> <Route
) {...rest}
render={(props) => {
if (user) {
if (rest.role) {
if (rest.role === user.role) {
return <Component {...props} />;
} else {
return <ErrorPage />
}
} else {
return <Component {...props} />
}
} else {
return <Redirect to="/login" />;
}
}}
/>
);
}; };
export default PrivateRoute; export default PrivateRoute;
\ No newline at end of file
import { useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import catchErrors from "../../utils/catchErrors.js";
import styles from "./schedule.module.scss"; import styles from "./schedule.module.scss";
const ScheduleItem = () => { const ScheduleItem = ({ schedule, handleClick }) => {
const [error, setError] = useState("")
async function delSchedule() {
try {
setError("")
alert("해당 일정을 성공적으로 삭제하였습니다.")
window.location.reload()
} catch (error) {
catchErrors(error, setError)
}
}
return ( return (
<div className="accordion-item border-bottom-0"> <div className="accordion-item border-bottom-0">
<button className={`d-flex flex-column align-items-start accordion-button collapsed bg-white shadow-none px-0 ${styles.activeBtn}`} type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"> <button className={`d-flex flex-column align-items-start accordion-button collapsed bg-white shadow-none px-0 ${styles.activeBtn}`} type="button" data-bs-toggle="collapse" data-bs-target={schedule.id} aria-expanded="false" aria-controls={schedule.id}>
<h5 className={`accordion-header ${styles.title}`} id="flush-headingOne"> <h5 className={`accordion-header ${styles.title}`} id={"heading" + schedule.id}>{schedule.title}</h5>
Accordion0 Item#1 sadsadsadasdsadsadasa sadsadsadasdsadsada
</h5>
<p className={`text-secondary mb-0 ${styles.time}`}>sadsadsdsadsadsaf</p> <p className={`text-secondary mb-0 ${styles.time}`}>sadsadsdsadsadsaf</p>
<p className={`mb-0 ${styles.period}`}>2021.01.151 ~ 2021.09.35</p> <p className={`mb-0 ${styles.period}`}>2021.01.151 ~ 2021.09.35</p>
</button> </button>
<div id="flush-collapseOne" className="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#scheduleList"> <div id={schedule.id} className="accordion-collapse collapse" aria-labelledby={"heading" + schedule.id} data-bs-parent="#scheduleList">
<div className={`accordion-body px-0 pt-2 pb-0 mb-3 ${styles.textBox}`}> <div className={`accordion-body px-0 pt-2 pb-0 mb-3 ${styles.textBox}`}>
<div className="d-flex align-items-start"> {schedule.location ? <div className="d-flex align-items-start">
<i className="col bi bi-geo-alt fs-5"></i> <i className="col bi bi-geo-alt fs-5"></i>
<div className="col-11"> <div className="col-11">{schedule.location}</div>
sadsadsadsa </div> : null}
</div> {schedule.memo}
</div>
dlkasjflsajflasjflsakfjlsajflalsafjsask<br />fjlakdjflajflaksj lksajdlksajs dslkafjlsakflksjflasjflksjslakjflsakjflsajflsakjlasjflksajlfsja
<div className="d-flex justify-content-end mt-3"> <div className="d-flex justify-content-end mt-3">
<Link className="btn btn-light btn-sm border-dark" to="/schedule/edit">수정</Link> <Link className="btn btn-light btn-sm border-dark" to={`/schedule/edit/${schedule.id}`}>수정</Link>
<button type="button" className="btn btn-crimson btn-sm ms-2" onClick={delSchedule}>삭제</button> <button type="button" className="btn btn-crimson btn-sm ms-2" onClick={handleClick}>삭제</button>
</div> </div>
</div> </div>
</div> </div>
......
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Item from "./ScheduleItem.js"; import Item from "./ScheduleItem.js";
import scheduleApi from "../../apis/schedule.api";
import { useAuth } from "../../utils/context.js";
import catchErrors from "../../utils/catchErrors.js";
import styles from "./schedule.module.scss"; import styles from "./schedule.module.scss";
const ScheduleList = () => { const ScheduleList = () => {
const [scheduleList, setScheduleList] = useState([])
const [error, setError] = useState("")
const { date } = useParams()
const { user } = useAuth()
useEffect(() => {
getAll(date)
return () => {
getAll(date)
}
}, [])
useEffect(() => {
getAll(date)
return () => {
getAll(date)
}
}, [date])
async function getAll(date) {
try {
setError("")
const resList = await scheduleApi.getbyDate(date, user.id)
setScheduleList(resList)
} catch (error) {
catchErrors(error, setError)
}
}
async function delSchedule(id) {
try {
setError("")
await scheduleApi.remove(id, user.id)
alert("해당 일정을 성공적으로 삭제하였습니다.")
getAll(date)
} catch (error) {
catchErrors(error, setError)
}
}
return ( return (
<div className={styles.list}> <div className={styles.list}>
<div className="accordion accordion-flush" id="scheduleList"> <div className="accordion accordion-flush" id="scheduleList">
<Item /> {scheduleList.length !== 0 ?
<Item /> scheduleList.map((schedule, idx) => <Item key={idx} schedule={schedule} handleClick={delSchedule} />)
<Item /> : <div className="text-center text-secondary">오늘 등록된 일정이 없습니다.</div>}
</div> </div>
</div> </div>
) )
......
import Monthly from "../../components/Calendar/AdminMonthly.js"; import Monthly from "../../components/Calendar/AdminMonthly.js";
import Footer from "../../components/Footer.js"; import Footer from "../../components/Footer.js";
import { useAuth } from "../../utils/context.js";
import styles from "./admin.module.scss"; import styles from "./admin.module.scss";
const AdminPage = () => { const AdminPage = () => {
const { logout } = useAuth()
return ( return (
<> <>
<p className={`position-absolute user-select-none ${styles.status}`}>관리자님, 환영합니다. | <span className={styles.cursor}>로그아웃</span></p> <p className={`position-absolute user-select-none ${styles.status}`}>관리자님, 환영합니다. | <span className={styles.cursor} onClick={logout}>로그아웃</span></p>
<div className={styles.body}> <div className={styles.body}>
<Monthly /> <Monthly />
</div> </div>
......
import { Link } from 'react-router-dom';
import LoginForm from '../components/Form/LoginForm'; import LoginForm from '../components/Form/LoginForm';
import { useAuth } from "../utils/context";
function LoginPage() { function LoginPage() {
const { user } = useAuth()
console.log("LoginPage",user)
return ( return (
<> <>
<div className="py-5"> <div className="py-5">
...@@ -8,6 +12,7 @@ function LoginPage() { ...@@ -8,6 +12,7 @@ function LoginPage() {
<p className="ms-4">-일정관리앱</p> <p className="ms-4">-일정관리앱</p>
</div> </div>
<LoginForm /> <LoginForm />
<Link to="/home">asda</Link>
</> </>
); );
} }
......
import BackBtn from "../components/Buttons/BackBtn.js"; import BackBtn from "../components/Buttons/BackBtn.js";
import SignupForm from '../components/Form/SignupForm'; import SignupForm from '../components/Form/SignupForm';
import { useAuth } from "../utils/context";
function SingupPage() { function SingupPage() {
const { user } = useAuth()
console.log("Signup user",user)
return ( return (
<> <>
<BackBtn /> <BackBtn />
......
export function getLoggedIn() {
const loggedData = localStorage.getItem("login");
let loggedIn = null;
if (loggedData) {
// loggedIn = JSON.parse(loggedData);
loggedIn = loggedData
}
return loggedIn;
}
\ No newline at end of file
import { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom'; import { useHistory, useLocation } from "react-router-dom";
import authApi from "../apis/auth.api"; import authApi from "../apis/auth.api";
import catchErrors from './catchErrors'; import catchErrors from './catchErrors';
...@@ -13,13 +13,21 @@ const AuthContext = createContext({ ...@@ -13,13 +13,21 @@ const AuthContext = createContext({
}); });
const AuthProvider = ({ children }) => { const AuthProvider = ({ children }) => {
const [error, setError] = useState("");
const [user, setUser] = useState({ id: "", role: "user", name: "" }); const [user, setUser] = useState({ id: "", role: "user", name: "" });
const [error, setError] = useState("");
const history = useHistory()
const { pathname } = useLocation()
const getUser = async () => { const getUser = async () => {
const { id, role, userName } = await authApi.getUser(); try {
const user = { id: id, role: role, name: userName }; const resUser = await authApi.getUser();
setUser(user); setUser({ ...user, ...resUser });
// console.log("context use")
// if (pathname === "/admin" && user.role !== "admin") history.push('/home')
} catch (error) {
catchErrorAuth(error, setError);
}
} }
useEffect(() => { useEffect(() => {
getUser(); getUser();
}, []); }, []);
...@@ -84,4 +92,3 @@ const AuthProvider = ({ children }) => { ...@@ -84,4 +92,3 @@ const AuthProvider = ({ children }) => {
const useAuth = () => useContext(AuthContext); const useAuth = () => useContext(AuthContext);
export { AuthProvider, useAuth }; export { AuthProvider, useAuth };
\ No newline at end of file
...@@ -6,14 +6,31 @@ const { Op } = sequelize ...@@ -6,14 +6,31 @@ const { Op } = sequelize
const findbyId = async (req, res, next) => { const findbyId = async (req, res, next) => {
try { try {
const id = req.scheduleId const id = req.scheduleId
if (id) { const userId = req.userId
const findSchedule = await KU.findOne({ where: { id: id } }) let findSchedule = null
let startDate = null
let endDate = null
if (id && userId) {
if (userId === "ku") {
findSchedule = await KU.findOne({ where: { id: id } })
if (!findSchedule) throw new Error("해당 일정을 찾지 못했습니다.") if (!findSchedule) throw new Error("해당 일정을 찾지 못했습니다.")
else { else {
const { title, start, end, memo } = findSchedule const { id, title, start, end, memo } = findSchedule
const startDate = dateToString(start, "full") startDate = dateToString(start, "full")
const endDate = dateToString(end, "full") endDate = dateToString(end, "full")
req.schedule = { title, startDate: startDate, endDate: endDate, memo } req.schedule = { id, title, startDate: startDate, endDate: endDate, memo }
}
} else {
findSchedule = await Schedule.findOne({ where: { [Op.and]: [{ id: id }, { userId: userId }] } })
if (!findSchedule) throw new Error("해당 일정을 찾지 못했습니다.")
else {
const { id, title, start, end, location, memo } = findSchedule
startDate = dateToString(start, "full")
endDate = dateToString(end, "full")
const startTime = dateToString(start, "time")
const endTime = dateToString(end, "time")
req.schedule = { id, title, startDate, endDate, startTime, endTime, location, memo }
}
} }
next() next()
} else next() } else next()
...@@ -26,9 +43,10 @@ const findbyDate = async (req, res, next) => { ...@@ -26,9 +43,10 @@ const findbyDate = async (req, res, next) => {
try { try {
if (req.date || req.month) { if (req.date || req.month) {
let date = "" let date = ""
let findList = [] let findList = null
if (req.date) { if (req.date) {
date = new Date(req.date) date = new Date(req.date)
if (req.userId === "ku") {
findList = await KU.findAll({ findList = await KU.findAll({
where: { where: {
[Op.and]: [ [Op.and]: [
...@@ -48,11 +66,28 @@ const findbyDate = async (req, res, next) => { ...@@ -48,11 +66,28 @@ const findbyDate = async (req, res, next) => {
schedule.dataValues.start = dateToString(schedule.start, "twoYear") schedule.dataValues.start = dateToString(schedule.start, "twoYear")
schedule.dataValues.end = dateToString(schedule.end, "twoYear") schedule.dataValues.end = dateToString(schedule.end, "twoYear")
}) })
} else {
findList = await Schedule.findAll({
where: {
[Op.and]: [
{
start: {
[Op.lte]: date
}
}, {
end: {
[Op.gte]: date
}
}
]
}, order: [['updatedAt', 'DESC']]
})
}
} else { } else {
date = new Date(req.month) date = new Date(req.month)
const year = dateToString(date, "year") const year = dateToString(date, "year")
const month = dateToString(date, "month") const month = dateToString(date, "month")
findList = await KU.findAll({ const findKUList = await KU.findAll({
where: { where: {
[Op.or]: [ [Op.or]: [
{ {
...@@ -70,8 +105,9 @@ const findbyDate = async (req, res, next) => { ...@@ -70,8 +105,9 @@ const findbyDate = async (req, res, next) => {
}, attributes: ['id', 'title', 'start', 'end'] }, attributes: ['id', 'title', 'start', 'end']
, order: [['start']] , order: [['start']]
}) })
if (req.userId === "ku") {
// console.log("list==",findList) // console.log("list==",findList)
findList.forEach(schedule => { findKUList.forEach(schedule => {
// const find = findList.find(el => { // const find = findList.find(el => {
// if (el.dataValues.start <= schedule.dataValues.start) { // if (el.dataValues.start <= schedule.dataValues.start) {
// if (el.dataValues.end >= schedule.dataValues.start) return el // if (el.dataValues.end >= schedule.dataValues.start) return el
...@@ -82,6 +118,29 @@ const findbyDate = async (req, res, next) => { ...@@ -82,6 +118,29 @@ const findbyDate = async (req, res, next) => {
schedule.dataValues.allDay = true schedule.dataValues.allDay = true
schedule.dataValues.className = 'text' schedule.dataValues.className = 'text'
}) })
findList = findKUList
} else {
const findIndividualList = await Schedule.findAll({
where: {
[Op.or]: [
{
[Op.and]: [
sequelize.where(sequelize.fn('date_part', 'year', sequelize.col('start')), year),
sequelize.where(sequelize.fn('date_part', 'month', sequelize.col('start')), month)
]
}, {
[Op.and]: [
sequelize.where(sequelize.fn('date_part', 'year', sequelize.col('end')), year),
sequelize.where(sequelize.fn('date_part', 'month', sequelize.col('end')), month)
]
}
]
}, attributes: ['id', 'title', 'start', 'end']
, order: [['start']]
})
console.log("개인 일정 찾기", findIndividualList)
findList = { KU: findKUList, individual: findIndividualList }
}
} }
req.scheduleList = findList req.scheduleList = findList
next() next()
...@@ -94,15 +153,24 @@ const findbyDate = async (req, res, next) => { ...@@ -94,15 +153,24 @@ const findbyDate = async (req, res, next) => {
const create = async (req, res) => { const create = async (req, res) => {
try { try {
let newSchedule = null let newSchedule = null
let start = null
let end = null
const userId = req.userId const userId = req.userId
if (userId === "ku") { if (userId === "ku") {
const { title, startDate, endDate, memo } = req.body const { title, startDate, endDate, memo } = req.body
const start = new Date(startDate) start = new Date(startDate)
const end = new Date(endDate) end = new Date(endDate)
newSchedule = await KU.create({ title: title, start: start, end: end, memo: memo }) newSchedule = await KU.create({ title: title, start: start, end: end, memo: memo })
} else { } else {
const { title, startDate, endDate, startTime, endTime, allDay, location, memo } = req.body const { title, startDate, endDate, startTime, endTime, allDay, location, memo } = req.body
newSchedule = await Schedule.create({ title: title, location: location, memo: memo }) if (allDay === "on") {
start = new Date(startDate)
end = new Date(endDate)
} else {
start = new Date(startDate + " " + startTime)
end = new Date(endDate + " " + endTime)
}
newSchedule = await Schedule.create({ title: title, start: start, end: end, location: location, memo: memo, userId: userId })
} }
return res.json(newSchedule) return res.json(newSchedule)
} catch (error) { } catch (error) {
...@@ -113,14 +181,26 @@ const create = async (req, res) => { ...@@ -113,14 +181,26 @@ const create = async (req, res) => {
const edit = async (req, res) => { const edit = async (req, res) => {
try { try {
let updated = null let updated = null
let start = null
let end = null
const userId = req.userId const userId = req.userId
const { scheduleId } = req.query const { scheduleId } = req.query
if (userId === "ku") { if (userId === "ku") {
const { title, startDate, endDate, memo } = req.body const { title, startDate, endDate, memo } = req.body
updated = await KU.update({ title: title, start: startDate, end: endDate, memo: memo }, { where: { id: scheduleId } }) start = new Date(startDate)
end = new Date(endDate)
updated = await KU.update({ title: title, start: start, end: end, memo: memo }, { where: { id: scheduleId } })
} else { } else {
const { title, startDate, endDate, startTime, endTime, allDay, location, memo } = req.body const { title, startDate, endDate, startTime, endTime, allDay, location, memo } = req.body
updated = await Schedule.update({ title: title, memo: memo }, { where: { id: scheduleId } }) if (allDay === "on") {
start = new Date(startDate)
end = new Date(endDate)
} else {
start = new Date(startDate + " " + startTime)
end = new Date(endDate + " " + endTime)
}
updated = await Schedule.update({ title: title, start: start, end: end, location: location, memo: memo },
{ where: { [Op.and]: [{ id: scheduleId }, { userId: userId }] } })
} }
if (!updated) throw new Error("해당 일정의 일부 정보를 수정하는데 실패하였습니다.") if (!updated) throw new Error("해당 일정의 일부 정보를 수정하는데 실패하였습니다.")
else return res.send(200) else return res.send(200)
...@@ -135,7 +215,7 @@ const remove = async (req, res) => { ...@@ -135,7 +215,7 @@ const remove = async (req, res) => {
const userId = req.userId const userId = req.userId
const { scheduleId } = req.query const { scheduleId } = req.query
if (userId === "ku") deleted = await KU.destroy({ where: { id: scheduleId } }) if (userId === "ku") deleted = await KU.destroy({ where: { id: scheduleId } })
else deleted = await Schedule.destroy({ where: { id: scheduleId } }) else deleted = await Schedule.destroy({ where: { [Op.and]: [{ id: scheduleId }, { userId: userId }] } })
if (!deleted) throw new Error("해당 일정을 삭제하는데 실패하였습니다.") if (!deleted) throw new Error("해당 일정을 삭제하는데 실패하였습니다.")
else return res.send(200) else return res.send(200)
} catch (error) { } catch (error) {
...@@ -180,11 +260,23 @@ function dateToString(dateObj, method) { ...@@ -180,11 +260,23 @@ function dateToString(dateObj, method) {
const year_disit = String(year).substring(2, 4) const year_disit = String(year).substring(2, 4)
const month = dateObj.getMonth() + 1 const month = dateObj.getMonth() + 1
const date = dateObj.getDate() const date = dateObj.getDate()
const hour = dateObj.getHours()
const minute = dateObj.getMinutes()
if (method === "full") return [year, (month > 9 ? "" : "0") + month, (date > 9 ? "" : "0") + date].join("-") switch (method) {
else if (method === "twoYear") return [year_disit, (month > 9 ? "" : "0") + month, (date > 9 ? "" : "0") + date].join("-") case "full":
else if (method === "year") return year return [year, (month > 9 ? "" : "0") + month, (date > 9 ? "" : "0") + date].join("-")
else return month case "twoYear":
return [year_disit, (month > 9 ? "" : "0") + month, (date > 9 ? "" : "0") + date].join("-")
// case "dateTime":
// return [year, (month > 9 ? "" : "0") + month, (date > 9 ? "" : "0") + date, ].join("-")
case "time":
return [(hour > 9 ? "" : "0") + hour, (minute > 9 ? "" : "0") + minute].join(":")
case "year":
return year
case "month":
return month
}
} }
export default { export default {
......
...@@ -4,20 +4,19 @@ import config from "../config/app.config.js"; ...@@ -4,20 +4,19 @@ import config from "../config/app.config.js";
const getUser = async (req, res) => { const getUser = async (req, res) => {
try { try {
if (req.cookies.todayku) { if (req.cookies[config.cookieName]) {
const token = req.cookies.todayku; const token = req.cookies[config.cookieName];
const { id, role, name } = jwt.verify(token, config.jwtSecret); const { id, role, name } = jwt.verify(token, config.jwtSecret);
res.json({ id, role, name }); return res.json({ id, role, name });
} else { } else {
res.json({ id: "", role: "user", name: "" }); // res.json({ id: "", role: "user", name: "" });
throw new Error("유효기간이 만료되었습니다. 다시 로그인해주세요.")
} }
} catch (error) { } catch (error) {
console.error(error); return res.status(500).send(error.message || "사용자 정보 가져오는 중 에러 발생");
return res.status(500).send("유저를 가져오지 못했습니다.");
} }
} }
const signup = async (req, res) => { const signup = async (req, res) => {
console.log('server/signup req.body', req.body) console.log('server/signup req.body', req.body)
const { userId, password, userName, userStudNum } = req.body; const { userId, password, userName, userStudNum } = req.body;
...@@ -33,7 +32,7 @@ const signup = async (req, res) => { ...@@ -33,7 +32,7 @@ const signup = async (req, res) => {
studNum: userStudNum, studNum: userStudNum,
role: "user" role: "user"
}); });
res.status(201).json("success") return res.status(201).json("success")
} catch (error) { } catch (error) {
console.log(error) console.log(error)
return res.status(500).send(error.message || "회원가입 에러발생") return res.status(500).send(error.message || "회원가입 에러발생")
...@@ -54,7 +53,7 @@ const login = async (req, res) => { ...@@ -54,7 +53,7 @@ const login = async (req, res) => {
const signData = { const signData = {
id: user.id, id: user.id,
role: "user", role: user.role,
name: user.userName, name: user.userName,
}; };
...@@ -83,7 +82,7 @@ const login = async (req, res) => { ...@@ -83,7 +82,7 @@ const login = async (req, res) => {
const logout = async (req, res) => { const logout = async (req, res) => {
try { try {
res.clearCookie(config.cookieName); res.clearCookie(config.cookieName);
res.json({ return res.json({
id:"", id:"",
role:"user", role:"user",
name:"" name:""
......
...@@ -22,6 +22,9 @@ const ScheduleModel = (sequelize) => { ...@@ -22,6 +22,9 @@ const ScheduleModel = (sequelize) => {
end: { end: {
type: DataTypes.DATE type: DataTypes.DATE
}, },
allDay: {
type: DataTypes.BOOLEAN,
},
location: { location: {
type:DataTypes.STRING, type:DataTypes.STRING,
defaultValue: "" defaultValue: ""
......
...@@ -13,5 +13,10 @@ router ...@@ -13,5 +13,10 @@ router
router router
.route("/logout") .route("/logout")
.get(userCtrl.logout ) .get(userCtrl.logout)
router
.route("/")
.get(userCtrl.getUser)
export default router; export default router;
\ 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