简体   繁体   中英

Best practices for user management with Play! Framework?

What's the recommended way to handle user management in Play! Framework?

This is my setup:

  • UserAwareControllerBase as a base class for controllers
  • The main view template includes a login/logout button
  • custom Security class extending Secure.Security , and controllers that only allow signed-in users are annotated with @With(Secure.class)

(I haven't implemented a real password/login system yet, just entering the correct email suffices to login. TBD)

The setup is nice because Controllers don't need to bother writing user management code, and can easily get the signed-in user by calling getUser() . However, I'm already starting to feel the limitations of this setup. I'm getting a convoluted inheritance hierarchy, and am facing a problem if I want to inherit from the CRUD class .

What's the best practice for handling user authentication/authorization in Play! without repeating code?

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();
    }
}

If you want to share code between controllers, prefer using the @With annotation rather than using inheritance.

For user management, I am used to put some rights in the session in the onAuthenticated method like this

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

And then my check method is

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

With this I can use the @check annotation to check user rights. In the onAuthenticated method you can do whatever you want to map complex rights managements into simple constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM