송용우

Merge commit '14b0e21b' into feature/database

Showing 49 changed files with 1536 additions and 50 deletions
This diff could not be displayed because it is too large.
......@@ -3,13 +3,24 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.10.2",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"immer": "^7.0.1",
"include-media": "^1.4.9",
"open-color": "^1.7.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1"
"react-scripts": "3.4.1",
"redux": "^4.0.5",
"redux-actions": "^2.6.5",
"redux-devtools-extension": "^2.13.8",
"redux-saga": "^1.1.3",
"styled-components": "^5.1.1"
},
"scripts": {
"start": "react-scripts start",
......@@ -31,5 +42,6 @@
"last 1 firefox version",
"last 1 safari version"
]
}
},
"proxy": "http://localhost:4000"
}
......
import React from 'react';
import logo from './logo.svg';
import { Route } from 'react-router-dom';
import './App.css';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import HomePage from './pages/HomePage';
import SettingPage from './pages/SettingPage';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
<>
<Route component={HomePage} path={['/@:username', '/']} exact />
<Route component={LoginPage} path="/login" />
<Route component={RegisterPage} path="/register" />
<Route component={SettingPage} path="/setting" />
</>
);
}
......
import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import palette from '../../lib/styles/palette';
import Button from '../common/Button';
const AuthFormBlock = styled.div`
h3 {
margin: 0;
color: ${palette.gray[8]};
margin-bottom: 1rem;
}
`;
const StyledInput = styled.input`
font-size: 1rem;
border: none;
border-bottom: 1px solid ${palette.gray[5]};
padding-bottom: 0.5rem;
outline: none;
width: 100%;
&:focus {
color: $oc-teal-7;
border-bottom: 1px solid ${palette.gray[7]};
}
& + & {
margin-top: 1rem;
}
`;
const Footer = styled.div`
margin-top: 2rem;
text-align: right;
a {
color: ${palette.gray[6]};
text-decoration: underline;
&:hover {
color: ${palette.gray[9]};
}
}
`;
const ButtonWithMarginTop = styled(Button)`
margin-top: 1rem;
`;
const ErrorMessage = styled.div`
color: red;
text-align: center;
font-size: 0.875rem;
margin-top: 1rem;
`;
const textMap = {
login: '로그인',
register: '회원가입',
};
const AuthForm = ({ type, form, onChange, onSubmit, error }) => {
const text = textMap[type];
return (
<AuthFormBlock>
<h3>{text}</h3>
<form onSubmit={onSubmit}>
<StyledInput
autoComplete="username"
name="username"
placeholder="아이디"
onChange={onChange}
value={form.username}
/>
<StyledInput
autoComplete="new-password"
name="password"
placeholder="비밀번호"
type="password"
onChange={onChange}
value={form.password}
/>
{type === 'register' && (
<StyledInput
autoComplete="new-password"
name="passwordConfirm"
placeholder="비밀번호 확인"
type="password"
onChange={onChange}
value={form.passwordConfirm}
/>
)}
{error && <ErrorMessage>{error}</ErrorMessage>}
<ButtonWithMarginTop cyan fullWidth>
{text}
</ButtonWithMarginTop>
</form>
<Footer>
{type === 'login' ? (
<Link to="/register">회원가입</Link>
) : (
<Link to="/login">로그인</Link>
)}
</Footer>
</AuthFormBlock>
);
};
export default AuthForm;
import React from 'react';
import styled from 'styled-components';
import palette from '../../lib/styles/palette';
import { Link } from 'react-router-dom';
/*
register/login Layout
*/
const AuthTemplateBlock = styled.div`
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: ${palette.gray[2]};
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
const WhiteBox = styled.div`
.logo-area {
display: block;
padding-bottom: 2rem;
text-align: center;
font-weight: bold;
letter-spacing: 2px;
}
box-shadow: 0 0 8px rgba(0, 0, 0, 0.025);
padding: 2rem;
width: 360px;
background: white;
border-radius: 2px;
`;
const AuthTemplate = ({ children }) => {
return (
<AuthTemplateBlock>
<WhiteBox>
<div className="logo-area">
<Link to="/">작심삼일</Link>
</div>
{children}
</WhiteBox>
</AuthTemplateBlock>
);
};
export default AuthTemplate;
import React from 'react';
import styled, { css } from 'styled-components';
import palette from '../../lib/styles/palette';
import { withRouter } from 'react-router-dom';
const StyledButton = styled.button`
border: none;
border-radius: 4px;
font-size: 1rem;
font-weight: bold;
padding: 0.25rem 1rem;
color: white;
outline: none;
cursor: pointer;
background: ${palette.gray[8]};
&:hover {
background: ${palette.gray[6]};
}
${props =>
props.fullWidth &&
css`
padding-top: 0.75rem;
padding-bottom: 0.75rem;
width: 100%;
font-size: 1.125rem;
`}
${props =>
props.cyan &&
css`
background: ${palette.cyan[5]};
&:hover {
background: ${palette.cyan[4]};
}
`}
`;
const Button = ({ to, history, ...rest }) => {
const onClick = e => {
if (to) {
history.push(to);
}
if (rest.onClick) {
rest.onClick(e);
}
};
return <StyledButton {...rest} onClick={onClick} />;
};
export default withRouter(Button);
import React from 'react';
import styled from 'styled-components';
import { NavLink } from 'react-router-dom';
const categories = [
{
name: 'home',
text: '홈',
},
{
name: 'setting',
text: '설정',
},
];
const CategoriesBlock = styled.div`
display: flex;
padding: 1rem;
margin: 0 auto;
@media screen and (max-width: 768px) {
width: 100%;
overflow-x: auto;
}
`;
const Category = styled(NavLink)`
font-size: 1.2rem;
cursor: pointer;
white-space: pre;
text-decoration: none;
color: inherit;
padding-bottom: 0.25rem;
&:hover {
color: #495057;
}
& + & {
margin-left: 2rem;
}
&.active {
font-weight: 600;
border-bottom: 2px solid #22b8cf;
color: #22b8cf;
&:hover {
color: #3bc9db;
}
}
`;
const Categories = () => {
return (
<CategoriesBlock>
{categories.map((c) => (
<Category
activeClassName="active"
key={c.name}
exact={c.name === 'home'}
to={c.name === 'home' ? '/' : `/${c.name}`}
>
{c.text}
</Category>
))}
</CategoriesBlock>
);
};
export default Categories;
import React from 'react';
import styled from 'styled-components';
import Responsive from './Responsive';
import Button from './Button';
import { Link } from 'react-router-dom';
import Categories from './Categories';
const HeaderBlock = styled.div`
position: fixed;
width: 100%;
background: white;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08);
`;
const Wrapper = styled(Responsive)`
height: 4rem;
display: flex;
align-items: center;
justify-content: space-between;
.logo {
font-size: 1.125rem;
font-weight: 800;
letter-spacing: 2px;
}
.right {
display: flex;
align-items: center;
}
`;
const Spacer = styled.div`
height: 4rem;
`;
const UserInfo = styled.div`
font-weight: 800;
margin-right: 1rem;
`;
const Header = ({ user, onLogout, category, onSelect }) => {
return (
<>
<HeaderBlock>
<Wrapper>
<Link to="/" className="logo">
작심삼일
</Link>
<Categories
category={category}
onSelect={onSelect}
className="right"
/>
{user ? (
<div className="right">
<UserInfo>{user.username}</UserInfo>
<Button onClick={onLogout}>로그아웃</Button>
</div>
) : (
<div className="right">
<Button to="/login">로그인</Button>
</div>
)}
</Wrapper>
</HeaderBlock>
<Spacer />
</>
);
};
export default Header;
import React from 'react';
import styled from 'styled-components';
const ResponsiveBlock = styled.div`
padding-left: 1rem;
padding-right: 1rem;
width: 1024px;
margin: 0 auto;
@media (max-width: 1024px) {
width: 768px;
}
@media (max-width: 768px) {
width: 100%;
}
`;
const Responsive = ({ children, ...rest }) => {
return <ResponsiveBlock {...rest}>{children}</ResponsiveBlock>;
};
export default Responsive;
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import palette from '../../lib/styles/palette';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
background: palette.gray[2],
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
const HomeForm = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>xs=12</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
</Grid>
</div>
);
};
export default HomeForm;
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import styled from 'styled-components';
import palette from '../../lib/styles/palette';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
}));
const BJIDForm = ({ onChange, onBJIDSubmit, profile, onSyncBJIDSubmit }) => {
const classes = useStyles();
return (
<div>
<form onSubmit={onBJIDSubmit}>
<TextField
name="userBJID"
onChange={onChange}
value={profile.userBJID}
placeholder="백준 아이디"
label="백준 아이디"
/>
<Button variant="outlined" type="submit">
등록
</Button>
</form>
<Button variant="outlined" onClick={onSyncBJIDSubmit}>
동기화
</Button>
</div>
);
};
export default BJIDForm;
import React from 'react';
import styled from 'styled-components';
import Button from '../common/Button';
import palette from '../../lib/styles/palette';
import BJIDForm from './BJIDForm';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
const SettingFormBlock = styled.div`
h3 {
margin: 0;
color: ${palette.gray[8]};
margin-bottom: 1rem;
}
background: ${palette.gray[2]};
margin: 0 auto;
display: flex;
flex-direction: column;
`;
const StyledInput = styled.input`
font-size: 1rem;
border: none;
border-bottom: 1px solid ${palette.gray[5]};
padding-bottom: 0.5rem;
outline: none;
&:focus {
color: $oc-teal-7;
border-bottom: 1px solid ${palette.gray[7]};
}
& + & {
margin-top: 1rem;
}
`;
const SectionContainer = styled.div`
display: flex;
`;
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
background: palette.gray[2],
},
paper: {
margin: 'auto',
textAlign: 'center',
padding: 30,
},
}));
const SettingForm = ({ onChange, onBJIDSubmit, profile, onSyncBJIDSubmit }) => {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Paper className={classes.paper}>
<h3>{profile.username}</h3>
</Paper>
</Grid>
<Grid container item xs={12}>
<Paper className={classes.paper} elevation={3}>
<BJIDForm
profile={profile}
onChange={onChange}
onBJIDSubmit={onBJIDSubmit}
onSyncBJIDSubmit={onSyncBJIDSubmit}
/>
</Paper>
</Grid>
</Grid>
</div>
);
};
export default SettingForm;
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { changeField, initializeForm, login } from '../../modules/auth';
import AuthForm from '../../components/auth/AuthForm';
import { check } from '../../modules/user';
const LoginForm = ({ history }) => {
const dispatch = useDispatch();
const [error, setError] = useState(null);
const { form, auth, authError, user } = useSelector(({ auth, user }) => ({
form: auth.login,
auth: auth.auth,
authError: auth.authError,
user: user.user,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
form: 'login',
key: name,
value,
}),
);
};
const onSubmit = (e) => {
e.preventDefault();
const { username, password } = form;
dispatch(login({ username, password }));
};
useEffect(() => {
dispatch(initializeForm('login'));
}, [dispatch]);
useEffect(() => {
if (authError) {
console.log('Error Occured');
console.log(authError);
setError('로그인 실패');
return;
}
if (auth) {
console.log('Login Success');
dispatch(check());
}
}, [auth, authError, dispatch]);
useEffect(() => {
if (user) {
history.push('/');
try {
localStorage.setItem('user', JSON.stringify(user));
} catch (e) {
console.log('localStorage is not working');
}
console.log(user);
}
}, [history, user]);
return (
<AuthForm
type="login"
form={form}
onChange={onChange}
onSubmit={onSubmit}
error={error}
></AuthForm>
);
};
export default withRouter(LoginForm);
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { changeField, initializeForm, register } from '../../modules/auth';
import AuthForm from '../../components/auth/AuthForm';
import { check } from '../../modules/user';
import { withRouter } from 'react-router-dom';
const RegisterForm = ({ history }) => {
const [error, setError] = useState(null);
const dispatch = useDispatch();
const { form, auth, authError, user } = useSelector(({ auth, user }) => ({
form: auth.register,
auth: auth.auth,
authError: auth.authError,
user: user.user,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
form: 'register',
key: name,
value,
}),
);
};
const onSubmit = (e) => {
e.preventDefault();
const { username, password, passwordConfirm } = form;
if ([username, password, passwordConfirm].includes('')) {
setError('빈 칸을 모두 입력하세요');
return;
}
if (password !== passwordConfirm) {
setError('비밀번호가 일치하지 않습니다.');
changeField({ form: 'register', key: 'password', value: '' });
changeField({ form: 'register', key: 'passwordConfirm', value: '' });
return;
}
dispatch(register({ username, password }));
};
useEffect(() => {
dispatch(initializeForm('register'));
}, [dispatch]);
useEffect(() => {
if (authError) {
if (authError.response.status === 409) {
setError('이미 존재하는 계정명입니다.');
return;
}
setError('회원가입 실패');
return;
}
if (auth) {
console.log('Register Success!');
console.log(auth);
dispatch(check());
}
}, [auth, authError, dispatch]);
useEffect(() => {
if (user) {
console.log('SUCCESS check API');
history.push('/');
try {
localStorage.setItem('user', JSON.stringify(user));
} catch (e) {
console.log('localStorage is not working');
}
}
}, [history, user]);
return (
<AuthForm
type="register"
form={form}
onChange={onChange}
onSubmit={onSubmit}
error={error}
></AuthForm>
);
};
export default withRouter(RegisterForm);
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Header from '../../components/common/Header';
import { logout } from '../../modules/user';
const HeaderContainer = () => {
const { user } = useSelector(({ user }) => ({ user: user.user }));
const dispatch = useDispatch();
const onLogout = () => {
dispatch(logout());
};
return <Header user={user} onLogout={onLogout} />;
};
export default HeaderContainer;
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import HomeForm from '../../components/home/HomeForm';
import { getPROFILE } from '../../modules/profile';
import { analyzeBJ } from '../../lib/util/analyzeBJ';
const HomeContainer = ({ history }) => {
const dispatch = useDispatch();
const [isLogin, setLogin] = useState(false);
const { user, profile } = useSelector(({ user, profile }) => ({
user: user.user,
profile: profile,
}));
useEffect(() => {
analyzeBJ(profile.solvedBJ);
}, [profile.solvedBJ]);
useEffect(() => {
setLogin(true);
if (user) {
let username = user.username;
dispatch(getPROFILE({ username }));
}
}, [dispatch, user]);
return <HomeForm />;
};
export default withRouter(HomeContainer);
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter } from 'react-router-dom';
import {
changeField,
setBJID,
getPROFILE,
syncBJID,
initializeProfile,
} from '../../modules/profile';
import SettingForm from '../../components/setting/SettingForm';
const SettingContainer = ({ history }) => {
const dispatch = useDispatch();
const { user, profile } = useSelector(({ user, profile }) => ({
user: user.user,
profile: profile,
}));
const onChange = (e) => {
const { value, name } = e.target;
dispatch(
changeField({
key: name,
value: value,
}),
);
};
const onSyncBJIDSubmit = (e) => {
e.preventDefault();
let username = profile.username;
dispatch(syncBJID({ username }));
};
const onBJIDSubmit = (e) => {
e.preventDefault();
let username = profile.username;
let userBJID = profile.userBJID;
dispatch(setBJID({ username, userBJID }));
};
useEffect(() => {
if (!user) {
alert('로그인이 필요합니다 ');
history.push('/');
} else {
let username = user.username;
dispatch(getPROFILE({ username }));
return () => {
dispatch(initializeProfile());
};
}
}, [dispatch, user, history]);
return (
<SettingForm
type="setting"
onChange={onChange}
onBJIDSubmit={onBJIDSubmit}
onSyncBJIDSubmit={onSyncBJIDSubmit}
profile={profile}
></SettingForm>
);
};
export default withRouter(SettingContainer);
......@@ -5,6 +5,24 @@ body {
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
box-sizing: border-box;
min-height: 100%;
}
#root {
min-height: 100%;
}
html {
height: 100%;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: inherit;
}
code {
......
......@@ -3,12 +3,41 @@ import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import rootReducer, { rootSaga } from './modules';
import { tempSetUser, check } from './modules/user';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(sagaMiddleware)),
);
function loadUser() {
try {
const user = localStorage.getItem('user');
if (!user) return;
store.dispatch(tempSetUser(user));
store.dispatch(check());
} catch (e) {
console.log('localStorage is not working');
}
}
sagaMiddleware.run(rootSaga);
loadUser();
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</React.StrictMode>,
document.getElementById('root')
</BrowserRouter>
</Provider>,
document.getElementById('root'),
);
// If you want your app to work offline and load faster, you can change
......
import client from './client';
export const login = ({ username, password }) =>
client.post('api/auth/login', { username, password });
export const register = ({ username, password }) =>
client.post('api/auth/register', { username, password });
export const check = () => client.get('api/auth/check');
export const logout = () => client.post('/api/auth/logout');
import axios from 'axios';
const client = axios.create();
export default client;
import client from './client';
export const setBJID = ({ username, userBJID }) =>
client.post('api/profile/setprofile', {
username: username,
userBJID: userBJID,
});
export const getPROFILE = ({ username }) =>
client.post('api/profile/getprofile', { username });
export const syncBJ = ({ username }) =>
client.patch('api/profile/syncBJ', { username });
import { call, put } from 'redux-saga/effects';
import { startLoading, finishLoading } from '../modules/loading';
export const createRequestActionTypes = (type) => {
const SUCCESS = `${type}_SUCCESS`;
const FAILURE = `${type}_FAILURE`;
return [type, SUCCESS, FAILURE];
};
export default function createRequestSaga(type, request) {
const SUCCESS = `${type}_SUCCESS`;
const FAILURE = `${type}_FAILURE`;
return function* (action) {
yield put(startLoading(type));
try {
const response = yield call(request, action.payload);
yield put({
type: SUCCESS,
payload: response.data,
});
} catch (e) {
yield put({
type: FAILURE,
payload: e,
error: true,
});
}
yield put(finishLoading(type));
};
}
// source: https://yeun.github.io/open-color/
const palette = {
gray: [
'#f8f9fa',
'#f1f3f5',
'#e9ecef',
'#dee2e6',
'#ced4da',
'#adb5bd',
'#868e96',
'#495057',
'#343a40',
'#212529',
],
cyan: [
'#e3fafc',
'#c5f6fa',
'#99e9f2',
'#66d9e8',
'#3bc9db',
'#22b8cf',
'#15aabf',
'#1098ad',
'#0c8599',
'#0b7285',
],
};
export default palette;
/*
1. 날짜 순 정렬
2. 현재 날짜와의 차이
3. 최근 일주일간 푼 문제 수
4. 추천 문제
*/
exports.analyzeBJ = function (solvedBJ) {
console.log(typeof solvedBJ);
if (solvedBJ) {
solvedBJ.sort(function (a, b) {
return a.solvedDate > b.solvedDate
? -1
: a.solvedDate < b.solvedDate
? 1
: 0;
});
console.log(solvedBJ);
}
};
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>
import { createAction, handleActions } from 'redux-actions';
import produce from 'immer';
import { takeLatest } from 'redux-saga/effects';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
import * as authAPI from '../lib/api/auth';
const CHANGE_FIELD = 'auth/CHANGE_FIELD';
const INITIALIZE_FORM = 'auth/INITIALIZE_FORM';
const [REGISTER, REGISTER_SUCCESS, REGISTER_FAILURE] = createRequestActionTypes(
'auth/REGISTER',
);
const [LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE] = createRequestActionTypes(
'auth/REGISTER',
);
export const changeField = createAction(
CHANGE_FIELD,
({ form, key, value }) => ({
form,
key,
value,
}),
);
export const initializeForm = createAction(INITIALIZE_FORM, (form) => form);
const initalState = {
register: {
username: '',
password: '',
passwordConfirm: '',
},
login: {
username: '',
password: '',
},
auth: null,
authError: null,
};
export const register = createAction(REGISTER, ({ username, password }) => ({
username,
password,
}));
export const login = createAction(LOGIN, ({ username, password }) => ({
username,
password,
}));
const registerSaga = createRequestSaga(REGISTER, authAPI.register);
const loginSaga = createRequestSaga(LOGIN, authAPI.login);
export function* authSaga() {
yield takeLatest(REGISTER, registerSaga);
yield takeLatest(LOGIN, loginSaga);
}
const auth = handleActions(
{
[CHANGE_FIELD]: (state, { payload: { form, key, value } }) =>
produce(state, (draft) => {
draft[form][key] = value;
}),
[INITIALIZE_FORM]: (state, { payload: form }) => ({
...state,
[form]: initalState[form],
authError: null,
}),
[REGISTER_SUCCESS]: (state, { payload: auth }) => ({
...state,
authError: null,
auth,
}),
[REGISTER_FAILURE]: (state, { payload: error }) => ({
...state,
authError: error,
}),
[LOGIN_SUCCESS]: (state, { payload: auth }) => ({
...state,
authError: null,
auth,
}),
[LOGIN_FAILURE]: (state, { payload: error }) => ({
...state,
authError: error,
}),
},
initalState,
);
export default auth;
import { combineReducers } from 'redux';
import { all } from 'redux-saga/effects';
import auth, { authSaga } from './auth';
import loading from './loading';
import user, { userSaga } from './user';
import profile, { profileSaga } from './profile';
const rootReducer = combineReducers({
auth,
loading,
user,
profile,
});
export function* rootSaga() {
yield all([authSaga(), userSaga(), profileSaga()]);
}
export default rootReducer;
import { createAction, handleActions } from 'redux-actions';
const START_LOADING = 'loading/START_LOADING';
const FINISH_LOADING = 'loading/FINISH_LOADING';
export const startLoading = createAction(
START_LOADING,
(requestType) => requestType,
);
export const finishLoading = createAction(
FINISH_LOADING,
(requestType) => requestType,
);
const initialState = {};
const loading = handleActions(
{
[START_LOADING]: (state, action) => ({
...state,
[action.payload]: true,
}),
[FINISH_LOADING]: (state, action) => ({
...state,
[action.payload]: false,
}),
},
initialState,
);
export default loading;
import { createAction, handleActions } from 'redux-actions';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
import produce from 'immer';
import * as profileAPI from '../lib/api/profile';
import { takeLatest } from 'redux-saga/effects';
const INITIALIZE = 'profile/INITIALIZE';
const CHANGE_FIELD = 'profile/CHANGE_FIELD';
const [SET_BJID, SET_BJID_SUCCESS, SET_BJID_FAILURE] = createRequestActionTypes(
'profile/SET_BJID',
);
const [
GET_PROFILE,
GET_PROFILE_SUCCESS,
GET_PROFILE_FAILURE,
] = createRequestActionTypes('profile/GET_PROFILE');
const [
SYNC_BJID,
SYNC_BJID_SUCCESS,
SYNC_BJID_FAILURE,
] = createRequestActionTypes('profile/SYNC_BJID');
export const initializeProfile = createAction(INITIALIZE);
export const syncBJID = createAction(SYNC_BJID, ({ username }) => ({
username,
}));
export const setBJID = createAction(SET_BJID, ({ username, userBJID }) => ({
username,
userBJID,
}));
export const changeField = createAction(CHANGE_FIELD, ({ key, value }) => ({
key,
value,
}));
export const getPROFILE = createAction(GET_PROFILE, ({ username }) => ({
username,
}));
const initialState = {
username: '',
userBJID: '',
solvedBJ: '',
friendList: [],
profileError: '',
};
const getPROFILESaga = createRequestSaga(GET_PROFILE, profileAPI.getPROFILE);
const setBJIDSaga = createRequestSaga(SET_BJID, profileAPI.setBJID);
const syncBJIDSaga = createRequestSaga(SYNC_BJID, profileAPI.syncBJ);
export function* profileSaga() {
yield takeLatest(SET_BJID, setBJIDSaga);
yield takeLatest(GET_PROFILE, getPROFILESaga);
yield takeLatest(SYNC_BJID, syncBJIDSaga);
}
export default handleActions(
{
[INITIALIZE]: (state) => initialState,
[CHANGE_FIELD]: (state, { payload: { key, value } }) =>
produce(state, (draft) => {
draft[key] = value;
}),
[GET_PROFILE_SUCCESS]: (
state,
{ payload: { username, userBJID, solvedBJ, friendList } },
) => ({
...state,
username: username,
userBJID: userBJID,
solvedBJ: solvedBJ,
friendList: friendList,
profileError: null,
}),
[GET_PROFILE_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
[SET_BJID_SUCCESS]: (state, { payload: { userBJID } }) => ({
...state,
userBJID: userBJID,
profileError: null,
}),
[SET_BJID_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
[SYNC_BJID_SUCCESS]: (state, { payload: { solvedBJ } }) => ({
...state,
solvedBJ,
profileError: null,
}),
[SYNC_BJID_FAILURE]: (state, { payload: error }) => ({
...state,
profileError: error,
}),
},
initialState,
);
import { createAction, handleActions } from 'redux-actions';
import { takeLatest, call } from 'redux-saga/effects';
import * as authAPI from '../lib/api/auth';
import createRequestSaga, {
createRequestActionTypes,
} from '../lib/createRequestSaga';
const TEMP_SET_USER = 'user/TEMP_SET_USER';
const [CHECK, CHECK_SUCCESS, CHECK_FAILURE] = createRequestActionTypes(
'user/CHECK',
);
const LOGOUT = 'user/LOGOUT';
export const tempSetUser = createAction(TEMP_SET_USER, (user) => user);
export const check = createAction(CHECK);
export const logout = createAction(LOGOUT);
const checkSaga = createRequestSaga(CHECK, authAPI.check);
function checkFailureSaga() {
try {
localStorage.removeItem('user');
} catch (e) {
console.log('localStroage is not working');
}
}
function* logoutSaga() {
try {
yield call(authAPI.logout);
console.log('logout');
localStorage.removeItem('user');
} catch (e) {
console.log(e);
}
}
export function* userSaga() {
yield takeLatest(CHECK, checkSaga);
yield takeLatest(CHECK_FAILURE, checkFailureSaga);
yield takeLatest(LOGOUT, logoutSaga);
}
const initialState = {
user: null,
checkError: null,
};
export default handleActions(
{
[TEMP_SET_USER]: (state, { payload: user }) => ({
...state,
user,
}),
[CHECK_SUCCESS]: (state, { payload: user }) => ({
...state,
user,
checkError: null,
}),
[CHECK_FAILURE]: (state, { payload: error }) => ({
...state,
user: null,
checkError: error,
}),
[LOGOUT]: (state) => ({
...state,
user: null,
}),
},
initialState,
);
import React from 'react';
import HeaderContainer from '../containers/common/HeaderContainer';
import HomeContainer from '../containers/home/HomeContainer';
const HomePage = () => {
return (
<div>
<HeaderContainer />
<HomeContainer />
</div>
);
};
export default HomePage;
import React from 'react';
import AuthTemplate from '../components/auth/AuthTemplate';
import LoginForm from '../containers/auth/LoginForm';
const LoginPage = () => {
return (
<AuthTemplate>
<LoginForm type="login" />
</AuthTemplate>
);
};
export default LoginPage;
import React from 'react';
import AuthTemplate from '../components/auth/AuthTemplate';
import RegisterForm from '../containers/auth/RegisterForm';
const RegisterPage = () => {
return (
<AuthTemplate>
<RegisterForm type="register" />
</AuthTemplate>
);
};
export default RegisterPage;
import React from 'react';
import HeaderContainer from '../containers/common/HeaderContainer';
import SettingForm from '../components/setting/SettingForm';
import SettingContainer from '../containers/setting/SettingContainer';
const SettingPage = () => {
return (
<div>
<HeaderContainer />
<SettingContainer></SettingContainer>
</div>
);
};
export default SettingPage;
This diff could not be displayed because it is too large.
......@@ -3,5 +3,8 @@
# dotenv
.env
#access.log
access.log
# dependencies
/node_modules
......
......@@ -19,19 +19,21 @@
## API Table
| group | description | method | URL | Detail | Auth |
| ------- | ------------------------ | ------ | -------------------------- | -------- | --------- |
| ------- | --------------------------- | --------- | ------------------------ | -------- | --------- |
| user | 유저 등록 | POST | api/user | 바로가기 | JWT Token |
| user | 유저 삭제 | DELETE | api/user:id | 바로가기 | JWT Token |
| user | 특정 유저 조회 | GET | api/user:id | 바로가기 | None |
| user | 전체 유저 조회 | GET | api/user | 바로가기 | JWT Token |
| friend | 유저 친구 등록 | POST | api/friend | 바로가기 | JWT Token |
| friend | 유저의 친구 조회 | GET | api/friend:id | 바로가기 | None |
| profile | 유저가 푼 문제 조회 | GET | api/profile/solved:id | 바로가기 | None |
| profile | 유저가 푼 문제 동기화 | Update | api/profile/solved:id | 바로가기 | None |
| profile | 유저가 푼 문제 개수 조회 | GET | api/profile/solvednum:id | 바로가기 | None |
| profile | 추천 문제 조회 | GET | api/profile/recommendps:id | 바로가기 | None |
| notify | 슬랙 메시지 전송 요청 | POST | api/notify/slack | 바로가기 | Jwt Token |
| profile | 유저가 푼 문제 조회(백준) | GET | api/profile/solvedBJ:id | 바로가기 | None |
| profile | 유저가 푼 문제 동기화(백준) | PATCH | api/profile/syncBJ | 바로가기 | None |
| profile | 유저 정보 수정 | POST | api/profile/setprofile | 바로가기 | JWT TOKEN |
| profile | 유저 정보 받아오기 | POST | api/profile/getprofile | 바로가기 | JWT |
| profile | 추천 문제 조회 | GET | api/profile/recommend:id | 바로가기 | None |
| notify | 슬랙 메시지 전송 요청 | POST | api/notify/ |
| slack | 바로가기 | Jwt Token |
| auth | 로그인 | POST | api/auth/login | 바로가기 | None |
| auth | 로그아웃 | GET | api/auth/logout | 바로가기 | JWT Token |
| auth | 로그아웃 | POST | api/auth/logout | 바로가기 | JWT Token |
| auth | 회원가입 | POST | api/auth/register | 바로가기 | None |
| auth | 로그인 확인 | GET | api/auth/check | 바로가기 | None |
......
......@@ -2,6 +2,8 @@ const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const mongoose = require("mongoose");
const fs = require("fs");
const morgan = require("koa-morgan");
const jwtMiddleware = require("./src/lib/jwtMiddleware");
const api = require("./src/api");
......@@ -9,10 +11,13 @@ require("dotenv").config();
const app = new Koa();
const router = new Router();
const accessLogStream = fs.createWriteStream(__dirname + "/access.log", {
flags: "a",
});
require("dotenv").config();
app.use(bodyParser());
app.use(jwtMiddleware);
app.use(morgan("combined", { stream: accessLogStream }));
const { SERVER_PORT, MONGO_URL } = process.env;
router.use("/api", api.routes());
......
This diff is collapsed. Click to expand it.
......@@ -17,10 +17,14 @@
"jsonwebtoken": "^8.5.1",
"koa": "^2.12.0",
"koa-bodyparser": "^4.3.0",
"koa-morgan": "^1.0.1",
"koa-router": "^9.0.1",
"mongoose": "^5.9.17",
"morgan": "^1.10.0",
"node-schedule": "^1.3.2",
"path": "^0.12.7",
"slack-client": "^2.0.6",
"slack-node": "^0.1.8",
"voca": "^1.4.0"
},
"devDependencies": {
......
const Joi = require("joi");
const User = require("../../models/user");
const Profile = require("../../models/profile");
/*
POST /api/auth/register
{
......@@ -27,15 +28,19 @@ exports.register = async (ctx) => {
ctx.status = 409;
return;
}
const profile = new Profile({
username,
});
const user = new User({
username,
});
await user.setPassword(password);
await profile.save();
await user.save();
ctx.body = user.serialize();
const token = user.generateToken();
ctx.cookies.set("acces_token", token, {
ctx.cookies.set("access_token", token, {
//3일동안 유효
maxAge: 1000 * 60 * 60 * 24 * 3,
httpOnly: true,
......@@ -70,7 +75,7 @@ exports.login = async (ctx) => {
}
ctx.body = user.serialize();
const token = user.generateToken();
ctx.cookies.set("acces_token", token, {
ctx.cookies.set("access_token", token, {
//7일동안 유효
maxAge: 1000 * 60 * 60 * 24 * 7,
httpOnly: true,
......
......@@ -2,7 +2,8 @@ const Router = require("koa-router");
const auth = new Router();
const authCtrl = require("./auth.ctrl");
auth.post("/login", authCtrl.login);
auth.get("/logout", authCtrl.logout);
auth.post("/logout", authCtrl.logout);
auth.post("/register", authCtrl.register);
auth.get("/check", authCtrl.check);
module.exports = auth;
......
const Router = require("koa-router");
const profile = new Router();
const profileCtrl = require("./profile.ctrl");
profile.post("/solved:id");
profile.get("/solvednum:id");
profile.get("recommendps:id");
profile.get("/recommendps:id");
profile.patch("/syncBJ", profileCtrl.syncBJ);
profile.post("/setprofile", profileCtrl.setProfile);
profile.post("/getprofile", profileCtrl.getProfile);
module.exports = profile;
......
const Profile = require("../../models/profile");
const mongoose = require("mongoose");
const getBJ = require("../../util/getBJ");
const Joi = require("joi");
const { ObjectId } = mongoose.Types;
exports.checkObjectId = (ctx, next) => {
const { username } = ctx.request.body;
if (!ObjectId.isValid(username)) {
ctx.status = 400;
return;
}
return next();
};
/*POST /api/profile/getprofile
{
username: "username"
}
*/
exports.getProfile = async (ctx) => {
try {
const { username } = ctx.request.body;
const profile = await Profile.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
}
ctx.body = profile;
} catch (e) {
ctx.throw(500, e);
}
};
/*
POST /api/proflie/setprofile
{
username: "username",
userBJID: "userBJID",
friendList: [String],
}
*/
exports.setProfile = async (ctx) => {
const schema = Joi.object()
.keys({
username: Joi.string(),
userBJID: Joi.string(),
//freindList: Joi.array().items(Joi.string()),
})
.unknown();
const result = Joi.validate(ctx.request.body, schema);
if (result.error) {
ctx.status = 400;
ctx.body = result.error;
return;
}
try {
const profile = await Profile.findOneAndUpdate(
{ username: ctx.request.body.username },
ctx.request.body,
{
new: true,
}
).exec();
if (!profile) {
ctx.status = 404;
return;
}
ctx.body = profile;
} catch (e) {
ctx.throw(500, e);
}
};
/*
PATCH /api/proflie/syncBJ
{
username: 'userid'
}
*/
exports.syncBJ = async function (ctx) {
const { username } = ctx.request.body;
if (!username) {
ctx.status = 401;
return;
}
try {
const profile = await Profile.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
}
const BJID = await profile.getBJID();
let BJdata = await getBJ.getBJ(BJID);
const updateprofile = await Profile.findOneAndUpdate(
{ username: username },
{ solvedBJ: BJdata },
{ new: true }
).exec();
ctx.body = updateprofile;
} catch (e) {
ctx.throw(500, e);
}
};
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const jwtMiddleware = async (ctx, next) => {
const token = ctx.cookies.get("access_token");
if (!token) {
//토큰이 없을 때
return next();
}
try {
const decoded = jwt.verify(token, process.env.JWT_TOKEN);
const decoded = jwt.verify(token, process.env.JWT_SECRET);
ctx.state.user = {
_id: decoded._id,
username: decoded.username,
};
//토큰의 남은 유효 기간이 2일 이하라면 재발급
if (decoded.exp - Date.now() / 1000 < 60 * 60 * 24 * 2) {
const now = Math.floor(Date.now() / 1000);
if (decoded.exp - now < 60 * 60 * 24 * 3.5) {
const user = await User.findById(decoded._id);
const token = user.generateToken();
ctx.cookies.set("access_token", token, {
maxAge: 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7, //7days
httpOnly: true,
});
}
return next();
} catch (e) {
return next();
}
};
module.exports = jwtMiddleware;
......
const mongoose = require("mongoose");
const { Schema } = mongoose;
const ProfileSchema = new Schema({
username: { type: String, required: true, unique: true },
userBJID: String,
solvedBJ: Object,
friendList: [String],
});
ProfileSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
};
ProfileSchema.methods.getBJID = function () {
return this.userBJID;
};
ProfileSchema.methods.serialize = function () {
const data = this.toJSON();
return data;
};
const Profile = mongoose.model("Profile", ProfileSchema);
module.exports = Profile;
......@@ -3,7 +3,6 @@ const cheerio = require("cheerio");
const StringToDate = require("./StringToDate");
/*
ToDO
- 유저 네임 검증
- 예외 처리
*/
exports.getBJ = async function (userid) {
......
const Slack = require("slack-node"); // 슬랙 모듈 사용
const webhookUri =
"https://hooks.slack.com/services/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"; // Webhook URL
const slack = new Slack();
slack.setWebhook(webhookUri);
const send = async (message) => {
slack.webhook(
{
text: message,
},
function (err, response) {
console.log(response);
}
);
};
send("hello");