我试图在Phoenix(Elixir)控制器中进行简单的令牌认证。正确令牌的值存储在config/dev.secrets.exs
POST https:www.myapp.com/notification?token=123
defmodule Myapp.NotificationController do
use Myapp.Web, :controller
def create(conn, params) do
etoken = endpoint_token()
case params["token"] do
etoken ->
# ....
conn |> send_resp(201, "")
_ ->
conn|> send_resp(401, "Not Authorized")
end
defp endpoint_token, do: Application.get_env(:myapp, :notification)[:endpoint_token]
end
它有效,但它感觉不对。我首先需要调用方法endpoint_token()
并将其保存到变量etoken
,然后才能进行case
比较。是否有更清晰的方式来写这个?
现在我理想地喜欢endpoint_token
方法来保留方法,因为我想将其提取到将在其他地方使用的模块
更新
以这种方式顺便说一句,我继续得到/不得(随机)这个警告:warning: variable "etoken" is unused
web/controllers/notification_controller.ex:8
warning: variable "etoken" is unused
web/controllers/notification_controller.ex:1
答案 0 :(得分:1)
实际上,您编写的代码不起作用。您将绑定案例中params["token"]
的值。您需要使用pin运算符来匹配^etoken
。但现在回答你的问题...
为什么不使用if语句?
def create(conn, params) do
if params["token"] == endpoint_token() do
# ....
conn |> send_resp(201, "")
else
conn|> send_resp(401, "Not Authorized")
end
end
编辑:
如果您真的想在这里使用案例,可以翻转案例。
def create(conn, %{"token" => token}) do
case endpoint_token() do
^token ->
# ....
conn |> send_resp(201, "")
_ ->
conn|> send_resp(401, "Not Authorized")
end
end