如何将通配符运算符 * 集成到数学认证路由中?

huangapple go评论83阅读模式
英文:

How to integrate a wildcard operator * to math auth routes

问题

我正在使用Go语言构建一个身份验证系统,目前对其工作情况非常满意。但是现在我想要集成一个通配符操作符,如下所示:

如果URI是/user/list,并且在允许的映射中存在/user/*,则它必须通过。

Allowed {
"": {"administrator", "regional"}, // 逻辑正常工作
"/user/
": {"administrator"}, // 如何实现
"/login": {"administrator", "regional"}, // 逻辑正常工作
}

func (a *Authentication) IsAllowed(req *http.Request, role string) error {
schema := a.Schema // = 上面的 Allowed map[string][]string
url := req.URL.String()

// 检查URL在模式中的严格匹配
roles, ok := schema


if ok {
if util.InSlice(role, roles) {
return nil
} else {
return USERNOTALLOWED // 错误
}
}

// 这里必须加入通配符后缀的逻辑
if a.hasWildCardSuffix(url string) {

}

// 回退到通配符 *
if a.hasWildCard() { // 每当有一个 "" 键时返回一个布尔值
roles, _ = a.Schema["
"]
if util.InSlice(role, roles) {
return nil
} else {
return USERNOTALLOWED // 错误
}
}
return nil
}

非常感谢。

英文:

I am building a authentication system in go and so far i am verry pleased with the working of it. But now i want to integrate a wildcard operator like the following:

if the uri is /user/list and in the allowed map there is /user/* it must pas.

Allowed {
  "*": {"administrator", "regional"}, // logic works
  "/user/*": {"administrator"}, // how to implement
  "/login": {"administrator", "regional"}, // logic works
}

func (a *Authentication) IsAllowed(req *http.Request, role string) error {
schema := a.Schema // = the Allowed map[string][]string above
url := req.URL.String()

// Check strict match of the url in the schema
roles, ok := schema
if ok { if util.InSlice(role, roles) { return nil } else { return USERNOTALLOWED // error } } // here must come the logic of the wildcardsuffix if a.hasWildCardSuffix(url string) { } // Fallback to wildCard * if a.hasWildCard() { // return a bool whenever there is a "*" key roles, _ = a.Schema["*"] if util.InSlice(role, roles) { return nil } else { return USERNOTALLOWED // error } } return nil }

thx alot

答案1

得分: 1

filepath包中有一个Match函数可以帮助你实现这个功能:

package main

import (
	"log"
	"path/filepath"
)

func main() {	
	ok, err := filepath.Match("/user/*", "/user/list")
	log.Print(err)
	log.Print(ok)
	ok, err = filepath.Match("/user/*/*", "/user/list/detail")
	log.Print(err)
	log.Print(ok)
}

playground: http://play.golang.org/p/DZ2yVmi5zs

英文:

The filepath has a Match function can do this for you:

package main

import (
	"log"
	"path/filepath"
)

func main() {	
	ok, err := filepath.Match("/user/*", "/user/list")
	log.Print(err)
	log.Print(ok)
	ok, err = filepath.Match("/user/*/*", "/user/list/detail")
	log.Print(err)
	log.Print(ok)
}

playground: http://play.golang.org/p/DZ2yVmi5zs

huangapple
  • 本文由 发表于 2014年7月19日 22:16:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/24841320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定