Skip to content

Commit

Permalink
修复未登录能访问设置页面
Browse files Browse the repository at this point in the history
  • Loading branch information
kingwrcy committed Apr 14, 2024
1 parent bd73f51 commit b7d9b25
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
10 changes: 10 additions & 0 deletions middleware/auth.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export default defineNuxtRouteMiddleware((to, from) => {
const cookie = useCookie('token')

if (to.fullPath === '/settings' && !cookie.value) {
return navigateTo('/login')
}
if (to.fullPath === '/login' && cookie.value) {
return navigateTo('/')
}
})
27 changes: 14 additions & 13 deletions server/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const needLoginUrl = [
"/api/files/s3Presigned",
"/api/files/upload",
"/api/memo/remove",
"/api/user/settings/save",
"/api/user/settings/full",
];

export default defineEventHandler(async (event) => {
Expand All @@ -26,24 +28,23 @@ export default defineEventHandler(async (event) => {
} catch (error) {}
}

if (!needLoginUrl.includes(url.pathname)) {
return;
}
if (!token) {
if (needLoginUrl.includes(url.pathname) && !token) {
throw createError({
statusCode: 401,
statusMessage: "Unauthorized",
});
}

try {
const result = jwt.verify(token, jwtKey);
const payload = result as JwtPayload;
event.context.userId = payload.userId;
} catch (error) {
throw createError({
statusCode: 401,
statusMessage: "Unauthorized",
});
if (needLoginUrl.includes(url.pathname) && token) {
try {
const result = jwt.verify(token, jwtKey);
const payload = result as JwtPayload;
event.context.userId = payload.userId;
} catch (error) {
throw createError({
statusCode: 401,
statusMessage: "Unauthorized",
});
}
}
});

0 comments on commit b7d9b25

Please sign in to comment.