Created
March 26, 2014 09:45
-
-
Save bjorn-ali-goransson/9779829 to your computer and use it in GitHub Desktop.
Authenticates user and saves username to session, otherwise shows login form with errors.
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
String username = form.get("username")[0]; | |
String password = form.get("password")[0]; | |
boolean usernameIsEmpty = "".equals(username); | |
boolean passwordIsEmpty = "".equals(password); | |
if(usernameIsEmpty || passwordIsEmpty){ | |
if(usernameIsEmpty){ | |
flash().put("username-empty", "yes"); | |
} | |
if(passwordIsEmpty){ | |
flash().put("password-empty", "yes"); | |
} | |
return redirect(routes.AuthenticationController.showLoginForm()); | |
} | |
TypedQuery<User> query = JPA.em().createQuery( "SELECT c FROM User c WHERE c.username = :username AND c.password = :password", User.class); | |
query.setParameter("username", username); | |
query.setParameter("password", password); | |
List<User> matchingUsers = query.getResultList(); | |
if(matchingUsers.size() == 1){ | |
session().put("username", username); | |
return redirect(routes.DefaultController.index()); | |
} else { | |
flash().put("no-username-password-match", "yes"); | |
return redirect(routes.AuthenticationController.showLoginForm()); | |
} |
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
@if(flash.containsKey("username-empty")){ | |
<div class="alert alert-warning">Username required.</div> | |
} | |
@if(flash.containsKey("password-empty")){ | |
<div class="alert alert-warning">Password required.</div> | |
} | |
@if(flash.containsKey("no-username-password-match")){ | |
<div class="alert alert-warning">No username exists with this password.</div> | |
} | |
<form role="form" action="@routes.AuthenticationController.login" method="post"> | |
<div class="form-group"> | |
<label for="username">Username</label> | |
<input type="text" class="form-control" id="username" name="username"> | |
</div> | |
<div class="form-group"> | |
<label for="password">Password</label> | |
<input type="text" class="form-control" id="password" name="password"> | |
</div> | |
<button type="submit" class="btn btn-default">Submit</button> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment