Skip to content

Commit

Permalink
Merge pull request #170 from boostcampwm-2021/develop
Browse files Browse the repository at this point in the history
Develop ---> main 🔥🔥🔥🔥🔥🔥
  • Loading branch information
24to26 authored Nov 22, 2021
2 parents a0a3f45 + 069c17e commit cf00dc6
Show file tree
Hide file tree
Showing 64 changed files with 2,344 additions and 25,727 deletions.
5 changes: 5 additions & 0 deletions back-end/api-server/database/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,8 @@ export const updateTable = async (table, set, condition = null) => {
queryLine += condition ? `WHERE ${condition}` : ``;
return connectionQuery(queryLine);
};

export const deleteTable = async (table, condition) => {
let queryLine = `DELETE FROM ${table} WHERE ${condition}`;
return connectionQuery(queryLine);
};
26 changes: 19 additions & 7 deletions back-end/api-server/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const oauthDupCheck = async (id, req, res) => {
}
} catch (e) {
console.log(e);
return [false];
}
};

Expand All @@ -51,12 +52,18 @@ AuthRouter.post('/github/code', async (req, res) => {
code,
},
});

const { access_token } = data;
const user = await getGithubUser(access_token);
const [isOurUser, target] = await oauthDupCheck(user['id'], req, res); // 일단 중복 안되는 login 으로 해놓음
const id = user.id;
res.status(200).json({ id, isOurUser, nickname: target?.nickname });
if (access_token) {
const user = await getGithubUser(access_token);
if (!user) {
throw Error('github error');
}
const [isOurUser, target] = await oauthDupCheck(user['id'], req, res); // 일단 중복 안되는 login 으로 해놓음
const id = user.id;
res.status(200).json({ id, isOurUser, nickname: target?.nickname });
} else {
throw Error('github error');
}
} catch (error) {
console.error(error);
res.sendStatus(400);
Expand All @@ -68,8 +75,13 @@ AuthRouter.post('/naver/token', async (req, res) => {
try {
const userInfoFromNaver = await getUserInfoFromNaver(accessToken);
const id = userInfoFromNaver['response']['id'];
const [isOurUser, target] = await oauthDupCheck(id, req, res);
res.json({ id, isOurUser, nickname: target?.nickname });

if (id) {
const [isOurUser, target] = await oauthDupCheck(id, req, res);
res.json({ id, isOurUser, nickname: target?.nickname });
} else {
throw Error('naver error');
}
} catch (error) {
console.error(error);
res.sendStatus(400);
Expand Down
91 changes: 91 additions & 0 deletions back-end/api-server/routes/friend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import * as express from 'express';
import {
checkAlreadyFriend,
getFriendList,
requestFriend,
requestFriendList,
requestFriendUpdate,
} from '../services/friend';

const FriendRouter = express.Router();
interface friendReturnFormInterface {
data: Object;
message: String;
}
const friendReturnForm: friendReturnFormInterface = {
data: {},
message: '',
};

const setMessage = (data, message) => {
friendReturnForm.data = data;
friendReturnForm.message = message;
return friendReturnForm;
};

// 친구 요청 받을 시, 친구 요청 테이블에 넣기
FriendRouter.post('/request', async (req, res, next) => {
const { requestee, requester } = req.body; // userId : 친구 요청을 보낸 사람, friendId : 친구 요청을 받은 사람
try {
const result = await requestFriend({ requestee, requester });
const checkFriend = await checkAlreadyFriend({ requestee, requester }); // 이미 친구인지 확인
if (result && !checkFriend) {
res.status(200).json(setMessage({}, 'success'));
} else {
throw Error('request make error');
}
} catch (error) {
console.error(error);
res.status(400).json(setMessage({}, 'fail'));
}
});

// 친구 요청 수락, 거절 + 수락햇을때 실제 친구 데이터베이스에 넣기
FriendRouter.post('/request-update', async (req, res, next) => {
const { isAccept, requestee, requester } = req.body;
try {
const result = await requestFriendUpdate({ isAccept, requestee, requester });
if (result) {
res.status(200).json(setMessage({}, 'success'));
} else {
throw Error('request update error');
}
} catch (error) {
console.error(error);
res.status(400).json(setMessage({}, 'fail'));
}
});

// 나한테 들어온 친구 요청 목록 가져오기
FriendRouter.get('/request-list', async (req, res, next) => {
const requestee = req.query.requestee;
try {
const friendRequestList = await requestFriendList(requestee);
if (friendRequestList ?? 0) {
res.status(200).json(setMessage(friendRequestList, 'success'));
} else {
throw Error('request list error');
}
} catch (error) {
console.error(error);
res.status(400).json(setMessage([], 'fail'));
}
});

// 내 친구 목록 가져오기
FriendRouter.get('/list', async (req, res, next) => {
const nickname = req.query.nickname;
try {
const friendList = await getFriendList(nickname);
if (friendList ?? 0) {
res.status(200).json(setMessage(friendList, 'success'));
} else {
throw Error('friendlist error');
}
} catch (error) {
console.error(error);
res.status(400).json(setMessage([], 'fail'));
}
});

export default FriendRouter;
46 changes: 31 additions & 15 deletions back-end/api-server/routes/profile.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,88 @@
import * as express from 'express';
import { selectTable, innerJoinTable, updateTable } from '../database/query';
import { setJWT } from './../services/auth';

const ProfileRouter = express.Router();

ProfileRouter.post('/', async (req, res, next) => {
ProfileRouter.post('/stateMessage', async (req, res, next) => {
try {
const stateMessageList = await getStateMessageInDB(req.body.nickname);
const totalList = await getTotalInDB(req.body.nickname);
const recentList = await getRecentInDB(req.body.nickname);

if (stateMessageList.length === 0) {
//잘못된 경우 에러처리
res.status(401).json({ error: '잘못된 인증입니다.' });
} else {
const { state_message } = stateMessageList[0];
const [total, win] = totalList;
res.status(200).json({ state_message, total, win, recentList });
res.status(200).json({ state_message });
}
} catch (error) {
res.status(401).json({ error: '잘못된 인증입니다.' });
}
});

ProfileRouter.post('/total', async (req, res, next) => {
try {
const totalList = await getTotalInDB(req.body.id);
const recentList = await getRecentInDB(req.body.id);
const [total, win] = totalList;
res.status(200).json({ total, win, recentList });
} catch (error) {
console.log(error);
res.status(401).json({ error: '잘못된 인증입니다.' });
}
});

ProfileRouter.patch('/', async (req, res, next) => {
try {
const result = await updateStateMessageInDB(req.body);
const { nickname, id } = req.body;
const result = await updateProfileInDB(req.body);
if (result.warningStatus !== 0) {
res.status(401).json({ error: '잘못된 인증입니다.' });
} else {
res.clearCookie('user');
setJWT(req, res, { nickname, oauth_id: id });
res.status(200).json({ message: 'done' });
}
} catch (error) {
res.status(401).json({ error: '잘못된 인증입니다.' });
}
});

const updateStateMessageInDB = ({ nickname, stateMessage }) => {
return updateTable('USER_INFO', `state_message='${stateMessage}'`, `nickname='${nickname}'`);
const updateProfileInDB = ({ nickname, stateMessage, id }) => {
return updateTable(
'USER_INFO',
`state_message='${stateMessage}', nickname='${nickname}'`,
`oauth_id='${id}'`
);
};

const getStateMessageInDB = (nickname) => {
return selectTable('state_message', 'USER_INFO', `nickname='${nickname}'`);
};

const getTotalInDB = async (nickname) => {
const getTotalInDB = async (id) => {
return await Promise.all([
selectTable(
'SUM(attack_cnt) as total_attack_cnt, COUNT(nickname) as total_game_cnt, SEC_TO_TIME(SUM(TIME_TO_SEC(play_time))) as total_play_time ',
'SUM(attack_cnt) as total_attack_cnt, COUNT(oauth_id) as total_game_cnt, SEC_TO_TIME(SUM(TIME_TO_SEC(play_time))) as total_play_time ',
'PLAY',
`nickname='${nickname}'`
`oauth_id='${id}'`
),
innerJoinTable(
`SUM(case when game_mode='1 vs 1' then player_win else 0 end) as single_player_win, SUM(case when game_mode='normal' then player_win else 0 end) as multi_player_win`,
'PLAY',
'GAME_INFO',
'PLAY.game_id = GAME_INFO.game_id',
`nickname='${nickname}'`
`oauth_id='${id}'`
),
]);
};

const getRecentInDB = (nickname) => {
const getRecentInDB = (id) => {
return innerJoinTable(
'game_date, game_mode, ranking, play_time, attack_cnt, attacked_cnt',
'PLAY',
'GAME_INFO',
'PLAY.game_id = GAME_INFO.game_id',
`nickname='${nickname}'`
`oauth_id='${id}'`
);
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as express from 'express';
import { selectTable } from '../database/query';

const RankRouter = express.Router();
const RankingRouter = express.Router();

const categoryBox: any = {
totalWin: 'player_win',
Expand Down Expand Up @@ -29,11 +29,11 @@ const profileResponse = {
message: '',
};

RankRouter.post('/myInfo', async (req, res) => {
RankingRouter.post('/myInfo', async (req, res) => {
try {
const { nickname } = req.body.myInfoTemplate;
let queryResult = await selectTable(
`sum(player_win), sum(attack_cnt)`,
`sum(player_win) as player_win, sum(attack_cnt) as attack_cnt`,
`PLAY group by nickname having nickname = '${nickname}'`
); // 지금은 nickname이 아니라 oauth id이므로 추후 스토어에 추가되면 바꿀 예정.
profileResponse.data = queryResult?.[0];
Expand All @@ -45,7 +45,7 @@ RankRouter.post('/myInfo', async (req, res) => {
}
});

RankRouter.post('/', async (req, res) => {
RankingRouter.post('/', async (req, res) => {
try {
const { category, mode, nickName, offsetRank, lastNickName }: Query = req.body.rankApiTemplate;
let queryResult = await selectTable(
Expand All @@ -57,7 +57,7 @@ RankRouter.post('/', async (req, res) => {
rank() over (order by sum(p.${categoryBox[category]}) desc) as ranking
FROM
PLAY as p
left join user_info as u on p.nickname = u.nickname
inner join user_info as u on p.nickname = u.nickname
inner join game_info as g on p.game_id = g.game_id and g.\`game_mode\` = '${mode}'
group by p.nickname) a`
//`ranking >= ${Number(offsetRank)} and ranking < ${Number(offsetRank) + 20}`
Expand All @@ -74,9 +74,10 @@ RankRouter.post('/', async (req, res) => {
rankResponse.message = 'success';
res.status(200).json(rankResponse);
} catch (error) {
console.log(error);
rankResponse.message = 'error';
res.status(400).json(rankResponse);
}
});

export default RankRouter;
export default RankingRouter;
18 changes: 11 additions & 7 deletions back-end/api-server/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import axios from 'axios';
import * as jwt from 'jsonwebtoken';

export const getGithubUser = async (token) => {
const { data } = await axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`,
'Content-Type': 'application/json',
},
});
return data;
try {
const { data } = await axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`,
'Content-Type': 'application/json',
},
});
return data;
} catch (error) {
return false;
}
};

export const getUserInfoFromNaver = async (accessToken) => {
Expand Down
Loading

0 comments on commit cf00dc6

Please sign in to comment.