Skip to content

Commit

Permalink
fix: authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
henzyd committed Oct 30, 2024
1 parent d5812a1 commit 952cefa
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
18 changes: 7 additions & 11 deletions src/middlewares/api/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,26 @@ const protectedRoutes = ["/api/users"];
export const authorization: MiddlewareFactory = (next) => {
return catchAsync(async (req: NextRequest, _next: NextFetchEvent) => {
const pathname = req.nextUrl.pathname;
const sessionToken =
req.cookies.get(SESSION_KEY)?.value || req.headers.get("Authorization")?.split(" ")[1];

if (protectedRoutes.some((path) => pathname.startsWith(path))) {
const session =
req.cookies.get(SESSION_KEY)?.value || req.headers.get("Authorization")?.split(" ")[1];
if (!sessionToken) {
return appError({ status: 401, error: "No session provided" });
}

const {
data: { user_id },
} = await axiosInstance.post("/api/utils/decode", {
session,
});
} = await axiosInstance.post("/api/utils/decode", { session: sessionToken });

if (!user_id) {
return appError({
status: 401,
error: "No session provided",
});
return appError({ status: 401, error: "Invalid session" });
}

const res = NextResponse.next();
res.headers.set(HEADER_DATA_KEY, user_id);

return res;
}

return next(req, _next);
});
};
12 changes: 6 additions & 6 deletions src/middlewares/app/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ function redirect({
return NextResponse.redirect(redirectUrl, 307);
}

async function getMe(jwt: string | undefined): Promise<User | null> {
if (!jwt) return null;
async function getUserBySessionToken(token: string | undefined): Promise<User | null> {
if (!token) return null;

try {
const { data: user } = await axiosInstance.get<User>("/api/users/me", {
headers: {
Authorization: `Bearer ${jwt}`,
Authorization: `Bearer ${token}`,
},
});

Expand Down Expand Up @@ -67,14 +67,14 @@ export const authorization: MiddlewareFactory = (next) => {
return redirect({ req, pathname: authPaths.signin, origin: pathname });
}

const user = await getMe(session);
const user = await getUserBySessionToken(session);

console.log(user);

if (isProtectedPath && !user) {
return redirect({ req, pathname: authPaths.signin, origin: pathname });
}

console.log(user);

if (user && !user.complete_profile) {
return redirect({ req, pathname: authPaths.completeProfile, origin: pathname });
}
Expand Down

0 comments on commit 952cefa

Please sign in to comment.