gpt4 book ai didi

parsing - Play 2.0 框架,使用带有经过身份验证的请求的 BodyParser

转载 作者:行者123 更新时间:2023-12-04 15:02:01 32 4
gpt4 key购买 nike

我希望能够在经过身份验证的请求上使用 BodyParser,如果我的身份验证设置为 ZenTasks 示例,我就无法弄清楚如何做到这一点。

我的身份验证方法,

def IsAuthenticated(f: => String => Request[AnyContent] => Result) = {
Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}
}

def HasRole(role: List[String])
(f: => String => Request[AnyContent] => Result) = IsAuthenticated {
user => request => if (role.contains(getRole(user))) {
f(user)(request) // This function returns the result.
} else {
Results.Forbidden
}
}

我的 Controller 方法,
def controller = HasRole(List("admin")) { user => _ => { 
Action(parse.temporaryFile){ implicit request =>
request.body.moveTo(new File("/tmp/filepath"))
Redirect(routes.home)
}
}

这是我看到的错误,
[error]  found   : play.api.mvc.Action[play.api.libs.Files.TemporaryFile]
[error] required: play.api.mvc.Result
[error] Action(parse.temporaryFile){ implicit request =>
[error] ^

这是一个相关的问题: parse.json of authenticated play request

这个人找到了一个解决方法,我相信临时文件示例也有一个解决方法,但我想知道我正在做的事情如何(或为什么)不起作用。

最佳答案

我相信我已经弄清楚了这一点,主要是因为我在原始问题中遗漏了一些我没有意识到很重要的细节。

问题是我正在包装一个 Action { Action { } }因为IsAuthenticated方法已经调用了 Action里面的功能。我最终做的是重载 IsAuthenticated函数的方法采用 BodyParser作为参数。因为我正在使用 TemporaryFile方法,它不是 AnyContent 的子类,我还必须更改请求类型。

现在,这就是我的 Secured特征看起来像:

def IsAuthenticated(f: => String => Request[Any] => Result) = {
Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}
}

def IsAuthenticated(b: BodyParser[Any] = parse.anyContent)
(f: => String => Request[Any] => Result) = {
Security.Authenticated(username, onUnauthorized) { user =>
Action(b)(request => f(user)(request))
}
}

def HasRole(role: List[String])(b: BodyParser[Any] = parse.anyContent)
(f: => String => Request[Any] => Result) = IsAuthenticated(b) {
user => request => getRole(user) match {
case Some(r) if role.contains(r) => f(user)(request)
case _ => Results.Forbidden
}
}

这就是我的 Controller 的样子:
def controller = HasRole(List("admin"))(parse.temporaryFile) { user => request =>
request.body match {
case b:TemporaryFile => b.moveTo(new File("/tmp/file"))
case _ => Status(404)
}
}

希望这对其他人有帮助!

关于parsing - Play 2.0 框架,使用带有经过身份验证的请求的 BodyParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104005/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com