Skip to content

Commit

Permalink
忽略token支持url参数
Browse files Browse the repository at this point in the history
  • Loading branch information
cool-team-official committed Mar 20, 2024
1 parent 08a7842 commit d1829e5
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
33 changes: 31 additions & 2 deletions src/modules/base/middleware/authority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ export class BaseAuthorityMiddleware
return;
}
} catch (error) {}
// 不需要登录 无需权限校验
if (this.ignoreUrls.includes(url)) {
// 使用matchUrl方法来检查URL是否应该被忽略
const isIgnored = this.ignoreUrls.some(pattern =>
this.matchUrl(pattern, url)
);
if (isIgnored) {
await next();
return;
}
Expand Down Expand Up @@ -153,4 +156,30 @@ export class BaseAuthorityMiddleware
await next();
};
}

// 匹配URL的方法
matchUrl(pattern, url) {
const patternSegments = pattern.split('/').filter(Boolean);
const urlSegments = url.split('/').filter(Boolean);

// 如果段的数量不同,则无法匹配
if (patternSegments.length !== urlSegments.length) {
return false;
}

// 逐段进行匹配
for (let i = 0; i < patternSegments.length; i++) {
if (patternSegments[i].startsWith(':')) {
// 如果模式段以':'开始,我们认为它是一个参数,可以匹配任何内容
continue;
}
// 如果两个段不相同,则不匹配
if (patternSegments[i] !== urlSegments[i]) {
return false;
}
}

// 所有段都匹配
return true;
}
}
32 changes: 31 additions & 1 deletion src/modules/user/middleware/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ export class UserMiddleware implements IMiddleware<Context, NextFunction> {
return;
}
} catch (error) {}
if (this.ignoreUrls.includes(url)) {
// 使用matchUrl方法来检查URL是否应该被忽略
const isIgnored = this.ignoreUrls.some(pattern =>
this.matchUrl(pattern, url)
);
if (isIgnored) {
await next();
return;
} else {
Expand All @@ -63,4 +67,30 @@ export class UserMiddleware implements IMiddleware<Context, NextFunction> {
await next();
};
}

// 匹配URL的方法
matchUrl(pattern, url) {
const patternSegments = pattern.split('/').filter(Boolean);
const urlSegments = url.split('/').filter(Boolean);

// 如果段的数量不同,则无法匹配
if (patternSegments.length !== urlSegments.length) {
return false;
}

// 逐段进行匹配
for (let i = 0; i < patternSegments.length; i++) {
if (patternSegments[i].startsWith(':')) {
// 如果模式段以':'开始,我们认为它是一个参数,可以匹配任何内容
continue;
}
// 如果两个段不相同,则不匹配
if (patternSegments[i] !== urlSegments[i]) {
return false;
}
}

// 所有段都匹配
return true;
}
}

0 comments on commit d1829e5

Please sign in to comment.