2011-10-07 107 views
4

在我的新項目中,我想使用webmachine和mochiweb。我想要做的第一件事是認證。webmachine和重定向未經身份驗證的用戶

我編輯「dispatch.conf」,並提出一些資源,如:

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

當有人訪問「受保護」的資源,我想他重定向到「權威性」資源,如果他沒有登錄「 auth「資源包含帶有用戶名和密碼的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. 

我GOOGLE的如何做到這一點一些example,但不喜歡,我應該把這個函數中的所有資源,這需要身份驗證。

有沒有辦法做到這一點?

回答

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' – seancribbs

+1

我認爲這並不是什麼大事來改變它的記錄,我發現proplist的方式符合我的需要。雖然我在其他webmachine的資源中使用記錄。 – danechkin

0

的情況下你不授權和do_redirect是假的,爲什麼不回{ false, ReqData, State }像webmachine期待is_authorized(),而不是自己構建的迴應?

相關問題