Created
October 29, 2010 08:53
-
-
Save guillaumebort/653169 to your computer and use it in GitHub Desktop.
Sample secure interceptor for Play framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like your idea. However, I think it is not very scalable. What happens if you have 50 or more roles?