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.

私はそれを行う方法のいくつかの例をグーグルで検索しましたが、認証が必要なすべてのリソースにこの関数を配置する必要があるのは好きではありません。

それを行う方法はありますか?

4

2 に答える 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.
于 2011-10-07T14:50:19.083 に答える
0

権限がなくdo_redirect、falseの場合は、応答を自分で作成するのではなく、{ false, ReqData, State }webmachine が期待するように返さないのはなぜですか?is_authorized()

于 2013-04-11T11:41:30.897 に答える