Skip to content

Commit

Permalink
fix: 사용자 인증 권한 확인 로직 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
jinyongp committed Nov 12, 2023
1 parent 57a478c commit f233fe2
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 36 deletions.
2 changes: 1 addition & 1 deletion src/controllers/my/profile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const getMyProfile = createRouter({
description: "내 프로필을 가져옵니다.",
authorized: true,
async handler(ctx): Promise<AuthUser> {
return ctx.auth.user;
return toAuthUser(await users.findAuthUser(ctx.auth.user.id));
},
});

Expand Down
34 changes: 19 additions & 15 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { HttpError, HttpMethod, response } from "utils/http";
import { InferType, TypeDescriptor, validate } from "utils/validator";

import { jwt, users } from "services";
import { AuthUser, toAuthUser } from "models";

interface Body {
[key: string]: any;
Expand All @@ -33,8 +32,7 @@ interface Context<TBody extends Body> {

interface AuthContext<TBody extends Body> extends Context<TBody> {
auth: {
token: string;
user: AuthUser;
user: { id: number };
};
}

Expand Down Expand Up @@ -93,22 +91,15 @@ export function createRouter<Descriptor extends TypeDescriptor = never>(
}
try {
const payload = jwt.verify<{ id: number }>(token);
const user = await users.findAuthUser(payload.id);
if (!user || user.deletedAt) {
throw new HttpError(
"사용자 정보를 찾을 수 없습니다.",
"UNAUTHORIZED",
);
}
const user = await users.checkAuthorized(payload.id);
(context as AuthContext<any>).auth = {
token,
user: toAuthUser(user),
user,
};
} catch (error) {
throw new HttpError(
"인증 정보가 올바르지 않습니다.",
"UNAUTHORIZED",
error as Error,
"BAD_REQUEST",
error,
);
}
}
Expand Down Expand Up @@ -214,7 +205,7 @@ export default async (req: Request): Promise<Response> => {

try {
logger.info("REQ", { request: req, id: requestId });
const body = await tryCatch(() => req.json());
const body = await tryCatch(() => parseRequestBody(req));
const result = await router.handler({
param,
query: Object.fromEntries(url.searchParams.entries()),
Expand Down Expand Up @@ -252,3 +243,16 @@ export default async (req: Request): Promise<Response> => {

return response({ error: "Not Found" }, "NOT_FOUND");
};

function parseRequestBody(req: Request) {
const contentType = req.headers.get("Content-Type");
if (!contentType) {
return null;
}

if (contentType.includes("application/json")) {
return req.json();
}

return null;
}
58 changes: 39 additions & 19 deletions src/services/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,49 @@ export const userInclude = (authUserId: number): Prisma.UserInclude => ({
},
});

export async function checkAuthorized(id: number) {
try {
return await prisma.user.findUniqueOrThrow({
where: { id, deletedAt: null },
select: { id: true },
});
} catch (error) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === "P2025") {
throw new HttpError("사용자 정보를 찾을 수 없습니다.", "NOT_FOUND");
}
}
throw error;
}
}

export async function findAuthUser(id: number) {
return await prisma.user.findUnique({
where: { id },
include: {
_count: {
select: {
posts: true,
followers: true,
followings: true,
blogs: true,
},
},
blogs: {
select: {
lastPublishedAt: true,
try {
return await prisma.user.findUniqueOrThrow({
where: { id },
include: {
_count: {
select: {
posts: true,
followers: true,
followings: true,
blogs: true,
},
},
orderBy: {
lastPublishedAt: "desc",
blogs: {
select: {
lastPublishedAt: true,
},
orderBy: {
lastPublishedAt: "desc",
},
take: 1,
},
take: 1,
},
},
});
});
} catch {
throw new HttpError("사용자 정보를 찾을 수 없습니다.", "NOT_FOUND");
}
}

export async function findById(authUserId: number, userId: number) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class HttpError extends Error {
return HttpStatusCode[this.status];
}

constructor(message: string, status: Status, cause?: Error) {
constructor(message: string, status: Status, cause?: unknown) {
super(message);
this.status = status;
this.cause = cause;
Expand Down

0 comments on commit f233fe2

Please sign in to comment.