2011-10-07 53 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(),而不是自己构建的回应?

相关问题