Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class App {

private router(): void {
this.application.get('/', (req: express.Request, res: express.Response) => {
res.send('hello! world!');
res.send("hello! It's Trollo Server!");
});
}
}
Expand All @@ -31,7 +31,7 @@ app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.json());
app.use(cors(corsOption));
app.use('/', devRouter);
app.use('/', devRouter); // 테스트용으로 바로 넘어감, 배포 전 삭제해야함!
app.listen(4000, () => {
console.log('Server listening on port 4000');
});
Expand Down
18 changes: 13 additions & 5 deletions controller/emailauth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import express from 'express';
import { Request, Response } from 'express';
const jwt = require('jsonwebtoken');
import * as dotenv from 'dotenv';
dotenv.config();
Expand All @@ -8,7 +8,7 @@ import { refreshTokenGenerator } from '../Auth/GenerateRefreshToken';
// const Users = require('../src/db/models/user');

const emailAuthController = {
authorizationCode: async (req: express.Request, res: express.Response) => {
authorizationCode: async (req: Request, res: Response) => {
//오소리코드 확인

// console.log(req.query);
Expand Down Expand Up @@ -41,14 +41,22 @@ const emailAuthController = {
// secure: true,
// sameOrigin: 'none',
});
res.status(200).send({ message: 'ok', data: { accessToken: accessToken } });
// access token과 loginType을 응답으로 보내줌
res.status(200).json({
accessToken,
LoginType: 'email',
});
} else {
//expired
res.status(404).send({ message: 'authorizationCode Expired!' });
res.status(403).json({
message: 'authorizationCode Expired!',
});
}
}
} catch (err) {
res.status(500).send({ message: 'authorizationCode Error!' });
res.status(401).json({
message: 'authorizationCode Error!',
});
}
},
);
Expand Down
27 changes: 18 additions & 9 deletions controller/loginOAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Request, Response } from 'express';
import axios from 'axios';
//const jwt = require('jsonwebtoken');
import * as dotenv from 'dotenv';
dotenv.config();
import { Users } from '../src/db/models/user';
Expand All @@ -16,11 +15,12 @@ const oauthController = {
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
code: req.body.authorizationCode,
redirect_uri: process.env.CLIENT_URL, // 클라이언트 리디렉션 uri - 나중에 수정해야함
redirect_uri: process.env.CLIENT_URL,
grant_type: 'authorization_code',
})
.then(async result => {
let accessToken = result.data.access_token;
let refreshToken = result.data.refresh_token;
// accessToken을 통해 로그인한 유저 정보 가져오기
const resInfo = await axios
.get(googleInfoURL, {
Expand All @@ -38,19 +38,26 @@ const oauthController = {
email: resInfo,
},
});
if (userInfo == null && userInfo !== undefined) {
if (userInfo == null && resInfo !== undefined) {
await Users.create({
email: resInfo,
});
}
// cookie에 refresh token 저장
res.cookie('refreshToken', refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 7,
httpOnly: true,
});
// access token과 loginType을 응답으로 보내줌
res.status(200).json({
accessToken,
LoginType: 'google',
});
})
.catch(err => {
console.log(err.message);
res.status(400).json({
message: 'login error',
res.status(401).json({
message: 'authorizationCode Error!',
});
});
},
Expand Down Expand Up @@ -79,7 +86,7 @@ const oauthController = {
const resInfo = await axios
.get(githubInfoURL, {
headers: {
authorization: `Bearer ${accessToken}`, //`token ${accessToken}`,
authorization: `Bearer ${accessToken}`,
},
})
.then(result => {
Expand All @@ -95,19 +102,21 @@ const oauthController = {
email: `${resInfo}@github.com`,
},
});
if (userInfo == null && userInfo !== undefined) {
if (userInfo == null && resInfo !== undefined) {
await Users.create({
email: `${resInfo}@github.com`,
});
}
// access token과 loginType을 응답으로 보내줌
res.status(200).json({
accessToken,
LoginType: 'github',
});
})
.catch(err => {
console.log(err.message);
res.status(400).json({
message: 'error',
res.status(401).json({
message: 'authorizationCode Error!',
});
});
},
Expand Down
109 changes: 68 additions & 41 deletions middleware/authChecker.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,78 @@
import jwt, { VerifyErrors } from 'jsonwebtoken';
// import jwtObj from '../config/jwt';
import * as dotenv from 'dotenv';
import axios from 'axios';
import { Request, Response, NextFunction } from 'express';
import { accessTokenGenerator } from '../Auth/GenerateAccessToken';
import * as dotenv from 'dotenv';
dotenv.config();

export const authChecker = (req: Request, res: Response, next: NextFunction) => {
export const authChecker = async (req: Request, res: Response, next: NextFunction) => {
if (req.headers.authorization) {
const token = req.headers.authorization.split('Bearer ')[1];

jwt.verify(token, process.env.ACCESS_SECRET as string, err => {
if (err) {
// 기간만료 ? 맞다.
// 그럼이제 리프레시토큰을 이용해서 액세스토큰 재발급
// 그럼 두가지 분기처리를 해야한다, 리프레시토큰이없거나,만료되었거나해서 리다이렉트 로그인페이지
// 다시 액세스토큰을 내려주거나
// res.status(401).json({ error: 'expired!' });
const refresh = req.cookies.refreshToken;
if (refresh) {
//리프레시토큰 존재
jwt.verify(
refresh,
process.env.REFRESH_SECRET as string,
async (err: VerifyErrors | null, decoded: any | undefined) => {
if (err) {
//리프레시토큰 정상적이지않음,
res.redirect(`${process.env.CLIENT_URL}/Login`);
} else {
// 액세스토큰 새로 발급
const id = decoded.userId;
const email = decoded.email;
const newAccessToken = await accessTokenGenerator(id, email);
res.send({ message: 'newAccessToken', data: { accessToken: newAccessToken } });
}
},
);
} else {
//리프레시 없음
res.redirect(`${process.env.CLIENT_URL}/Login`);
const accessToken = req.headers.authorization.split('Bearer ')[1];
const LoginType = req.headers.LoginType;
if (LoginType === 'email') {
// 로그인 방식 - email
jwt.verify(accessToken, process.env.ACCESS_SECRET as string, err => {
if (err) {
// 기간만료 ? 맞다.
// 그럼이제 리프레시토큰을 이용해서 액세스토큰 재발급
// 그럼 두가지 분기처리를 해야한다, 리프레시토큰이없거나,만료되었거나해서 리다이렉트 로그인페이지
// 다시 액세스토큰을 내려주거나
// res.status(401).json({ error: 'expired!' });
const refreshToken = req.cookies.refreshToken;
if (refreshToken) {
// refresh token 존재
jwt.verify(
refreshToken,
process.env.REFRESH_SECRET as string,
async (err: VerifyErrors | null, decoded: any | undefined) => {
if (err) {
// refresh token 정상적이지않음
res.redirect(`${process.env.CLIENT_URL}/Login`);
} else {
// 새로운 access token을 발급받음
const id = decoded.userId;
const email = decoded.email;
const newAccessToken = await accessTokenGenerator(id, email);
req.newAccessToken = newAccessToken;
}
},
);
} else {
// refresh token 없음
res.redirect(`${process.env.CLIENT_URL}/login`);
}
}
} else {
// 액세스토큰 이상없음 다음꺼로 넘어감
next();
}
});
});
} else if (LoginType === 'google') {
// 로그인 방식 - google
// refresh token을 이용하여 새로운 access token을 발급받음
const googleLoginURL = 'https://accounts.google.com/o/oauth2/token';
await axios
.post(googleLoginURL, {
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
grant_type: 'refresh_token',
refresh_token: req.cookies.refreshToken,
})
.then(async result => {
let accessToken = result.data.access_token;
req.newAccessToken = accessToken;
})
.catch(err => {
// 에러 발생 -> 인증 불가 -> 다시 로그인해야함
console.log(err.message);
res.redirect(`${process.env.CLIENT_URL}/login`);
});
} else if (LoginType === 'github') {
// 로그인 방식 - github
// refresh token이 없음, 로그아웃 하기 전까지 access token 계속 사용 가능
req.newAccessToken = accessToken;
}
// 실제 요청으로 넘어감
// 나중에 응답 보낼때 accessToken에 req.newAccessToken을 넣어주면 됨
next();
} else {
// 액세스 토큰 없을때
res.redirect(`${process.env.CLIENT_URL}/Login`);
// access token이 없을 때 -> 로그인 페이지로 돌아감
res.redirect(`${process.env.CLIENT_URL}/login`);
}
};
26 changes: 18 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --exec ts-node app.ts",
"start": "nodemon --exec ts-node -T app.ts",
"create_db": "ts-node ./src/db/migrations/migration-all-table.ts"
},
"repository": {
Expand All @@ -25,7 +25,9 @@
"eslint": "^7.25.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"prettier": "^2.2.1"
"prettier": "^2.2.1",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
},
"dependencies": {
"@types/dotenv": "^8.2.0",
Expand All @@ -50,8 +52,6 @@
"sequelize-cli": "^6.2.0",
"sequelize-cli-typescript": "^3.2.0-c",
"sequelize-typescript": "^2.1.0",
"ts-node": "^9.1.1",
"typescript": "^4.2.4",
"util": "^0.10.4"
}
}
Loading