Skip to content

Commit

Permalink
refactor: 로그인 요구 여부를 defineRoute에 표현
Browse files Browse the repository at this point in the history
  • Loading branch information
potados99 committed Feb 7, 2022
1 parent 161e5ed commit 99753b4
Show file tree
Hide file tree
Showing 16 changed files with 66 additions and 73 deletions.
2 changes: 1 addition & 1 deletion src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {BaseEntity, Column, CreateDateColumn, Entity, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import Event from './Event';
import Comment from './Comment';
import {UserReponse} from '../server/routes/users/types';
import {UserReponse} from '../service/types';

/**
* 사용자!
Expand Down
44 changes: 2 additions & 42 deletions src/server/middleware/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,22 @@ import config from '../../config';
import {decodeJwt} from '../../common/utils/token';
import PathMatcher from '../libs/PathMatcher';

export type AuthorizerConfig = {
exclude?: string[];
};

export function authorizer({exclude}: AuthorizerConfig): RequestHandler {
const exclududPathMatcher = new PathMatcher(exclude);

export function authorizer(): RequestHandler {
return (req, res, next) => {
if (exclududPathMatcher.anyMatch(req.path)) {
assignGetter(req, extractUserIdIfJwtExists(req));

return next();
}

const jwtInRequest = extractJwt(req);
if (jwtInRequest == null) {
return next(NotLoggedIn());
}

try {
const {userId} = decodeJwt(jwtInRequest);

assignGetter(req, userId);

decodeJwt(jwtInRequest);
return next();
} catch (e) {
return next(InvalidJwt());
}
};
}

function assignGetter(req: express.Request, initial?: number) {
Object.defineProperty(req, 'userId', {
get() {
if (initial) {
return initial;
} else {
throw NotLoggedIn();
}
},
});
}

function extractJwt(req: express.Request): string | undefined {
return req.header('token') ?? req.cookies[config.server.jwt.cookieName];
}

function extractUserIdIfJwtExists(req: express.Request): number | undefined {
const jwt = extractJwt(req);
if (jwt == null) {
return undefined;
}

try {
return decodeJwt(jwt).userId;
} catch (e) {
return undefined;
}
}
42 changes: 42 additions & 0 deletions src/server/middleware/userIdGetterAssigner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import express, {RequestHandler} from 'express';
import {InvalidJwt, NotLoggedIn} from '../../common/errors/general';
import config from '../../config';
import {decodeJwt} from '../../common/utils/token';
import PathMatcher from '../libs/PathMatcher';

export function userIdGetterAssigner(): RequestHandler {
return (req, res, next) => {
const jwtInRequest = extractJwt(req);
if (jwtInRequest == null) {
assignGetter(req);

return next();
}

try {
const {userId} = decodeJwt(jwtInRequest);

assignGetter(req, userId);

return next();
} catch (e) {
return next();
}
};
}

function assignGetter(req: express.Request, initial?: number) {
Object.defineProperty(req, 'userId', {
get() {
if (initial) {
return initial;
} else {
throw NotLoggedIn();
}
},
});
}

function extractJwt(req: express.Request): string | undefined {
return req.header('token') ?? req.cookies[config.server.jwt.cookieName];
}
3 changes: 2 additions & 1 deletion src/server/routes/comments/deleteComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import CommentService from '../../../service/CommentService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
commentId: stringAsInt
},
});

export default defineRoute('delete', '/comments/:commentId', schema, async (req, res) => {
export default defineRoute('delete', '/comments/:commentId', schema, authorizer(), async (req, res) => {
const {commentId} = req.params;

await CommentService.deleteComment(commentId);
Expand Down
2 changes: 1 addition & 1 deletion src/server/routes/comments/getComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const schema = defineSchema({
},
});

export default defineRoute('get', '/comments/:commentId', schema, async (req, res) => {
export default defineRoute('get', '/comment/:commentId', schema, async (req, res) => {
const {commentId} = req.params;

const commentInformation = await CommentService.getComment(commentId);
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/comments/makeComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import CommentService from '../../../service/CommentService';
import UserService from '../../../service/UserService';
import EventService from '../../../service/EventService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
body: {
Expand All @@ -13,7 +14,7 @@ const schema = defineSchema({
}
});

export default defineRoute('post', '/comments', schema, async (req, res) => {
export default defineRoute('post', '/comments', schema, authorizer(), async (req, res) => {
console.log('make coomet!');

const {userId} = req;
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/comments/updateComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {z} from 'zod';
import {defineRoute} from '../../libs/route';
import CommentService from '../../../service/CommentService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
Expand All @@ -13,7 +14,7 @@ const schema = defineSchema({
}
});

export default defineRoute('patch', '/comments/:commentId', schema, async (req, res) => {
export default defineRoute('patch', '/comments/:commentId', schema, authorizer(), async (req, res) => {
const {commentId} = req.params;

await CommentService.patchComment(commentId, req.body);
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/events/deleteEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import EventService from '../../../service/EventService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
eventId: stringAsInt,
},
});

export default defineRoute('delete', '/events/:eventId', schema, async (req, res) => {
export default defineRoute('delete', '/events/:eventId', schema, authorizer(), async (req, res) => {
const {eventId} = req.params;

await EventService.deleteEvent(eventId);
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/events/makeEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {defineRoute} from '../../libs/route';
import EventService from '../../../service/EventService';
import UserService from '../../../service/UserService';
import {stringAsDate} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
body: {
Expand All @@ -17,7 +18,7 @@ const schema = defineSchema({
}
});

export default defineRoute('post', '/events', schema, async (req, res) => {
export default defineRoute('post', '/events', schema, authorizer(), async (req, res) => {
console.log('make Event!');

const {userId} = req;
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/events/updateEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {z} from 'zod';
import {defineRoute} from '../../libs/route';
import EventService from '../../../service/EventService';
import {stringAsDate, stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
Expand All @@ -19,7 +20,7 @@ const schema = defineSchema({
}
});

export default defineRoute('patch', '/events/:eventId?', schema, async (req, res) => {
export default defineRoute('patch', '/events/:eventId?', schema, authorizer(), async (req, res) => {
const {eventId} = req.params;

await EventService.patchEvent(eventId, req.body);
Expand Down
10 changes: 0 additions & 10 deletions src/server/routes/me.ts

This file was deleted.

3 changes: 2 additions & 1 deletion src/server/routes/users/deleteUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import UserService from '../../../service/UserService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
id: stringAsInt,
},
});

export default defineRoute('delete', '/users/:id', schema, async (req, res) => {
export default defineRoute('delete', '/users/:id', schema, authorizer(), async (req, res) => {
const {id} = req.params;

await UserService.deleteUser(id);
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/users/getMe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import UserService from '../../../service/UserService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
});

export default defineRoute('get', '/me', schema, async (req, res) => {
export default defineRoute('get', '/me', schema, authorizer(), async (req, res) => {
const {userId} = req;

const user = await UserService.getUser(userId);
Expand Down
3 changes: 2 additions & 1 deletion src/server/routes/users/updateUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {z} from 'zod';
import {defineRoute} from '../../libs/route';
import UserService from '../../../service/UserService';
import {stringAsInt} from '../../libs/zodTypes';
import {authorizer} from '../../middleware/authorizer';

const schema = defineSchema({
params: {
Expand All @@ -13,7 +14,7 @@ const schema = defineSchema({
}
});

export default defineRoute('patch', '/users/:id', schema, async (req, res) => {
export default defineRoute('patch', '/users/:id', schema, authorizer(), async (req, res) => {
const {id} = req.params;

await UserService.patchUser(id, req.body);
Expand Down
12 changes: 2 additions & 10 deletions src/server/server.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import express from 'express';
import cookieParser from 'cookie-parser';
import {authorizer} from './middleware/authorizer';
import {errorHandler} from './middleware/errorHandler';
import {registerRoutes} from '../common/utils/express';

/**
* 인증을 건너뛰는 endpoint 목록입니다.
*/
const allowList = [
'/**', // 전체 경로 허용입니다 나중에 빼주세용~
'/login'
];
import {userIdGetterAssigner} from './middleware/userIdGetterAssigner';

export async function startServer() {
const app = express();
Expand All @@ -19,7 +11,7 @@ export async function startServer() {
app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.use(authorizer({exclude: allowList}));
app.use(userIdGetterAssigner());

await registerRoutes(app, __dirname + '/routes');

Expand Down
File renamed without changes.

0 comments on commit 99753b4

Please sign in to comment.