Skip to content

Instantly share code, notes, and snippets.

@guillaumebort
Created October 29, 2010 08:53
Show Gist options
  • Save guillaumebort/653169 to your computer and use it in GitHub Desktop.
Save guillaumebort/653169 to your computer and use it in GitHub Desktop.
Sample secure interceptor for Play framework
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
@With(Secure.class)
public class Application extends Controller {
public static void index(String msg) {
render();
}
@Secure.Admin
public static void edit() {
render();
}
}
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import java.lang.annotation.*;
import models.*;
public class Secure extends Controller {
@Before
static void checkAuthenticated() {
if(session.contains("user")) {
// The user is authenticated,
// add User object to the renderArgs scope
User authenticated = User.findByUsername(session.get("user"));
renderArgs.put("user", authenticated);
} else {
// The user is not authenticated,
// redirect to the login form
Authentication.login();
}
}
@Before
static void checkAuthorization() {
Admin adminAnnotation = getActionAnnotation(Admin.class);
if(adminAnnotation != null) {
// The action method is annotated with @Admin,
// check the permission
if(!renderArgs.get("user", User.class).isAdmin()) {
// The connected user is not admin;
forbidden("You must be admin to see this page");
}
}
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Admin {}
}
@rsirres
Copy link

rsirres commented Jun 1, 2014

I like your idea. However, I think it is not very scalable. What happens if you have 50 or more roles?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment