Webmachine和重定向未经身份验证的用户

4

在我的新项目中,我想使用webmachine和mochiweb。首先要做的事情是认证。

我编辑了“dispatch.conf”并创建了一些资源,例如:

{["auth"], my_res_auth, []}.
{["protected"], my_res_protected, []}.
{['*'], my_res_default, []}.

当有人访问“受保护”的资源时,如果他没有登录,我希望将他重定向到“认证”资源。 “认证”资源包含一个带有用户名和密码的Web表单,它完成所有身份验证工作。
我在my_res_protected.erl中放置了以下代码:
is_authorized(ReqData, State) ->
    case my_auth:is_authorized(ReqData) of
        true -> {true, ReqData, State};
        false ->
            % here should be something to redirect user to "auth" resource
            % currently i put such thing, which is incorrect:
            {true, wrq:do_redirect(true, wrq:set_resp_header("location", "/auth", ReqData)), State}
            % dont know what should i put instead of "true"
    end.

我搜索了一些关于如何做到这一点的示例,但我不喜欢必须在所有资源中放置这些需要验证的函数。是否有其他方法可以实现?
2个回答

4
我认为我找到了正确的方法,将这段代码放入auth.hrl文件中并将其包含在我的资源中。
is_authorized(ReqData, State) ->
    case my_auth:is_authorized(ReqData) of
        true -> {true, ReqData, State};
        false ->
            % there i got address, to which should i redirect
            % this address is defined in dispatch.conf
            % and walk trough my_res_protected:init/1 into State
            case proplists:get_value(do_redirect, State, false) of
                false ->
                    {{halt, 401}, wrq:set_resp_header(
                            "Content-type", "text/plain",
                            wrq:set_resp_body("NOT AUTHORIZED", ReqData)
                        ), State};
                Location ->
                    {{halt, 302}, wrq:set_resp_header("Location", Location, ReqData), State}
            end
    end.

1
为什么不使用记录/结构体作为您的状态变量?那么它就是:case State#state.do_redirect of - seancribbs
1
我认为这并不是一个大问题,将其更改为记录形式,我发现 proplist 的方式符合我的需求。尽管在使用其他 Webmachine 资源时我使用记录。 - danechkin

0
在未经授权且 do_redirect 为 false 的情况下,为什么不像 Webmachine 期望的那样返回 { false, ReqData, State },而不是自己构建响应?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接