2011-11-21 103 views
3

在Play中处理用户管理的推荐方式是什么?框架?使用Play进行用户管理的最佳做法!框架?

这是我的设置:

  • UserAwareControllerBase作为基类为控制器
  • 主视图模板包括登录/注销按钮
  • 定制Security类延伸Secure.Security,和控制器,只允许签订在用户注释与@With(Secure.class)

(我还没有实现一个真正的p密码/登录系统,只需输入正确的电子邮件即可登录。 TBD)

设置很好,因为控制器不需要编写用户管理代码,并且可以通过调用getUser()轻松获取登录用户。不过,我已经开始感受到这种设置的局限性。我得到了一个令人费解的继承层次结构,如果我想从CRUD class继承,就会面临问题。

在Play中处理用户认证/授权的最佳做法是什么?没有重复代码?

UserAwareControllerBase.java

public abstract class UserAwareControllerBase extends Controller { 
    protected final static UserRepository userRepo = new UserRepository(); 

    @Before 
    static void setConnectedUser() { 
     if(Security.isConnected()) { 
      User user = userRepo.findByEmail(Security.connected()); 
      renderArgs.put("user", user); 
     } 
    } 

    static User getUser() { 
     return renderArgs.get("user", User.class); 
    } 
} 

template.html

<div id='header'> 
    ... 

    #{if user} 
    <a href="@{Secure.logout()}">Log out (${user.email})</a> 
    #{/if} 
    #{else} 
    <a href="@{Secure.login()}">Log in</a> 
    #{/else} 
</div> 

Security.java

public class Security extends Secure.Security { 
    protected final static UserRepository userRepo = new UserRepository(); 

    static boolean authenticate(String username, String password) { 
     User user = userRepo.findByEmail(username); 
     return user != null; 
    } 

    public static void onDisconnected() { 
     Application.index(); 
    } 
} 

回答

2

如果要在控制器之间共享代码,请使用@With注释而不是继承。

用户管理,我习惯把一些权利在会话中onAuthenticated方法这样

static void onAuthenticated() { 
    session.put(Const.MY_RIGHT, true); 
} 

然后我的检查方法是

static boolean check(String profile) { 
    return Boolean.parseBoolean(session.get(profile)); 
} 

有了这个,我可以使用@check注释来检查用户权限。在onAuthenticated方法中,您可以执行任何想要将复杂权限管理映射到简单常量的操作。

+0

谷歌似乎并不知道@With的文档在哪里。 – ripper234

+1

http://www.playframework.org/documentation/1.2.3/controllers#with –

相关问题