use @before annotation in play 1.2.5?

600 views Asked by At

I want the session to be checked before sending a user to the login - whereby each URL request results in checking whether this is from a valid session - if not, send them to the login page, else process as normal. If the user already has an active session, we will not show them the login page but take them to a pre-defined main page.

I searched on google related to it, and come to know that it will done by using @Before annotaion in controller but dont know about @Before working and how to use? I'm using play 1.2.5.

2

There are 2 answers

0
emt14 On

The Play secure module does exactly that out of the box. It is used by most applications and integrates with different plugins as well. Check out the documentation here.

If you still want to implement it yourself you can use the secure code as an example.

Otherwise @Before can be used on any of your controller static methods and has access to all the scope Objects, including session.

0
Ogobere On

You can use the @Before this way:

@Before
static void addUser() {
    User user = connected();
    if(user != null) {
        renderArgs.put("user", user);
    }
}

static User connected() {
    if(renderArgs.get("user") != null) {
        return renderArgs.get("user", User.class);
    }
    // Find your user from session
    String username = session.get("user");
    if(username != null) {
        return User.find("byUsername", username).first();
    } 
    return null;
}

// ~~render your login if the user is not finded in session

public static void index() {
    if(connected() != null) {
         render();
    }
    login();
}

You can find this sample code in YOUR_PLAY_DIR/samples-and-tests/booking.

As @emt14 said, you can do this with the Play secure module more easily. Check out the forum apps samples in YOUR_PLAY_DIR/samples-and-tests/forum.