Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/modify delete algorithm #13

Merged
merged 2 commits into from
Dec 25, 2021
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
9 changes: 5 additions & 4 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,16 @@ functions:
method: delete
cors: true

changeStatusAlgorithm:
handler: src/handler.setAlgorithmStatus
modifyAlgorithm:
handler: src/handler.modifyAlogirithemContent
events:
- http:
path: algoirthm/{id}
method: patch
cors: true

modifyAlgorithm:
handler: src/handler.modifyAlogirithemContent
changeStatusAlgorithm:
handler: src/handler.setAlgorithmStatus
events:
- http:
path: algoirthm/{id}/status
Expand All @@ -111,6 +111,7 @@ functions:
path: verify
method: get
cors: true

addVerify:
handler: src/handler.addVerifyQuestion
events:
Expand Down
2 changes: 2 additions & 0 deletions src/DTO/algorithm.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export type AlgorithmStatusType =
| "ACCEPTED"
| "REJECTED"
| "REPORTED";

export interface ModifyAlgorithmDTO extends BaseAlgorithmDTO {}
4 changes: 4 additions & 0 deletions src/DTO/user.dto.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export type IdentityType = "faculty" | "graduate" | "student";
export interface DecodedAccessToken {
isAdmin: boolean;
email: string;
}
21 changes: 20 additions & 1 deletion src/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import { APIGatewayEvent } from "aws-lambda";
import { getRepository } from "typeorm";
import { getCustomRepository, getRepository } from "typeorm";

import { ALLOWED_ORIGINS, createErrorRes, createRes } from "../util/http";
import { verifyToken } from "../util/token";
import { checkQuestionAnswer } from "../util/verify";
import { User } from "../entity";
import jwt, { JwtPayload } from "jsonwebtoken";
import { issuer } from "../config";
import { UserRepository } from "../repository/user";
import { DecodedAccessToken } from "../DTO/user.dto";
export class AuthMiddleware {
static onlyOrigin(_: any, __: string, desc: PropertyDescriptor) {
const originMethod = desc.value; // get function with a decorator on it.
desc.value = async function (...args: any[]) {
// argument override
const req: APIGatewayEvent = args[0];

const origin = req.headers.Origin || req.headers.origin;
if (!ALLOWED_ORIGINS.includes(origin) && origin) {
// ignore request from not allowed origin
Expand Down Expand Up @@ -126,4 +129,20 @@ export class AuthMiddleware {
return originMethod.apply(this, args);
};
}
static onlyAdmin(_: any, __: string, desc: PropertyDescriptor) {
const originMethod = desc.value;

desc.value = async function (...args: any[]) {
const req: APIGatewayEvent = args[0];
const token: string = req.headers.Authorization;

const { email } = verifyToken(token) as DecodedAccessToken;
const userRepo = getCustomRepository(UserRepository);
const isAdmin = await userRepo.getIsAdminByEmail(email);

return isAdmin
? originMethod.apply(this, args)
: createErrorRes({ errorCode: "JL002", status: 401 });
};
}
}
9 changes: 9 additions & 0 deletions src/repository/algorithm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EntityRepository, Repository } from "typeorm";
import { ModifyAlgorithmDTO } from "../DTO/algorithm.dto";

import { Algorithm } from "../entity";

Expand All @@ -11,4 +12,12 @@ export class AlgorithmRepository extends Repository<Algorithm> {
.groupBy("algorithm.algorithmStatus")
.getRawMany();
}

async modifyAlgorithm(id: number, data: ModifyAlgorithmDTO) {
return this.update(id, data);
}

async deleteAlgorithm(id: number) {
return this.delete(id);
}
}
13 changes: 13 additions & 0 deletions src/repository/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { EntityRepository, Repository } from "typeorm";
import { User } from "../entity/User";

@EntityRepository(User)
export class UserRepository extends Repository<User> {
async getIsAdminByEmail(email: string): Promise<boolean> {
return (
await this.createQueryBuilder("user")
.where("user.email = :email", { email })
.getOne()
).isAdmin;
}
}
28 changes: 27 additions & 1 deletion src/router/algorithm/algorithm.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { APIGatewayEvent } from "aws-lambda";
import { getCustomRepository, getRepository } from "typeorm";

import { bold13, bold15, ruleForWeb, rules } from "../../config";
import { BaseAlgorithmDTO } from "../../DTO/algorithm.dto";
import { BaseAlgorithmDTO, ModifyAlgorithmDTO } from "../../DTO/algorithm.dto";
import { Algorithm } from "../../entity";
import { AlgorithmRepository } from "../../repository/algorithm";
import { getLastPostNumber } from "../../util/algorithm";
import { createErrorRes, createRes } from "../../util/http";
import { isNumeric } from "../../util/number";

export const AlgorithmService: { [k: string]: Function } = {
writeAlgorithm: async ({ title, content, tag }: BaseAlgorithmDTO) => {
Expand Down Expand Up @@ -48,6 +50,30 @@ export const AlgorithmService: { [k: string]: Function } = {
},
});
},
modifyAlgorithmContent: async (event: APIGatewayEvent) => {
const { id } = event.pathParameters;

if (!isNumeric(id)) {
return createErrorRes({ errorCode: "JL007" });
}

const data: ModifyAlgorithmDTO = JSON.parse(event.body);
const algorithmRepo = getCustomRepository(AlgorithmRepository);
return createRes({
body: await algorithmRepo.modifyAlgorithm(Number(id), data),
});
},
deleteAlgorithm: async (event: APIGatewayEvent) => {
const { id } = event.pathParameters;

if (!isNumeric(id)) {
return createErrorRes({ errorCode: "JL007" });
}

const algorithmRepo = getCustomRepository(AlgorithmRepository);
await algorithmRepo.deleteAlgorithm(Number(id));
return createRes({});
},
};

const checkArgument: Function = (...args: any[]): boolean => {
Expand Down
21 changes: 17 additions & 4 deletions src/router/algorithm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class AlgorithmRouter {
static async getAlgorithmCountAtAll(_: APIGatewayEvent, __: any) {
return AlgorithmService.getAlgorithmCountAtAll();
}

static async getAlgorithmRules(_: APIGatewayEvent, __: any) {
return AlgorithmService.getAlgorithmRules();
}
Expand All @@ -27,9 +27,22 @@ export class AlgorithmRouter {
static async wirteAlgorithm(event: APIGatewayEvent, _: any, __: Function) {
return AlgorithmService.writeAlgorithm(JSON.parse(event.body));
}

static async setAlgorithmStatus() {}
static async modifyAlgorithmContent() {}

@AuthMiddleware.onlyOrigin
@DBMiddleware.connectTypeOrm
@AuthMiddleware.onlyAdmin
static async modifyAlgorithmContent(event: APIGatewayEvent, _: any) {
return AlgorithmService.modifyAlgorithmContent(event);
}

static async reportAlgorithm() {}
static async deleteAlgorithm() {}

@AuthMiddleware.onlyOrigin
@DBMiddleware.connectTypeOrm
@AuthMiddleware.onlyAdmin
static async deleteAlgorithm(event: APIGatewayEvent, _: any) {
return AlgorithmService.deleteAlgorithm(event);
}
}
4 changes: 3 additions & 1 deletion src/util/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const ERROR_CODE_LIST: { [key in ErrorCodeType]: string } = {
JL004: "예상치 못한 에러입니다. 개발자에게 문의해주세요.",
JL005: "Token 값을 찾을수 없습니다.",
JL006: "Token 인증이 실패하였습니다.",
JL007: "잘못된 요청입니다.",
} as const;

export type ErrorCodeType =
Expand All @@ -25,7 +26,8 @@ export type ErrorCodeType =
| "JL003"
| "JL004"
| "JL005"
| "JL006";
| "JL006"
| "JL007";

export const createRes = ({
statusCode,
Expand Down
2 changes: 2 additions & 0 deletions src/util/number.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const isNumeric: Function = (data: string): boolean =>
!isNaN(Number(data));