Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. @Entity
  2. @Table(name="user")
  3. public class User {
  4.  
  5.   @Id
  6.   @GeneratedValue
  7.   public Long id;
  8.  
  9.   public String email;
  10.   public String password;
  11.  
  12. }
  13.  
  14. public class LoginForm {
  15.  
  16.   @Required
  17.   @Constraints.Email
  18.   private String email;
  19.  
  20.   @Required
  21.   @Constraints.MinLength(value=4)
  22.   private String password;
  23.  
  24.  
  25.   public String validate() {
  26.     if(Authentication.authenticate(this.email, this.password) == null) {
  27.       return "Invalid user or password";
  28.     }
  29.     return null;
  30. }
  31.  
  32. public final class Authentication extends Controller {
  33.  
  34.     public static Result login() {
  35.         return ok(
  36.             login.render(form(LoginForm.class))
  37.         );
  38.     }
  39.    
  40.     public static Result authenticate() {
  41.      // the validate method of the form has already been called
  42.         Form<LoginForm> loginForm = form(LoginForm.class).bindFromRequest();
  43.         if(loginForm.hasErrors()) {
  44.             return badRequest(login.render(loginForm));
  45.         } else {
  46.             session("email", loginForm.get().getEmail());
  47.             return redirect(
  48.                 routes.Application.index()
  49.             );
  50.         }
  51.     }
  52.    
  53.     public static User authenticate(final String email, final String password){
  54.      return Ebean.find(User.class)
  55.      .where()
  56.      .eq("email", email)
  57.         .eq("password", Base64.getSHABase64(password))
  58.         .findUnique();
  59.     }
  60.  
  61.  
  62.     public static Result logout() {
  63.         session().clear();
  64.         flash("success", "You've been logged out");
  65.         return redirect(
  66.             routes.Authentication.login()
  67.         );
  68.     }
  69.  
  70. }
  71.  
  72. public class Secured extends Security.Authenticator {
  73.    
  74.     @Override
  75.     public String getUsername(Context ctx) {
  76.         return ctx.session().get("email");
  77.     }
  78.    
  79.     @Override
  80.     public Result onUnauthorized(Context ctx) {
  81.         return redirect(routes.Authentication.login());
  82.     }
  83. }
  84.  
  85. @Security.Authenticated(Secured.class)
  86. public class Application extends Controller {
  87.   public static Result index() {
  88.     Logger.debug("Logged in as user " + Context.current().request().username());
  89.     return ok(index.render("Your new application is ready."));
  90.   }
  91. }