Skip to content
Browse files

Userdao now hashes passwords before storing them.

  • Loading branch information...
1 parent 39b0180 commit a262f45eace39e1ba91ff630b5913e3a61f148c8 @shsu committed
View
23 src/main/java/ca/bcit/infosys/comp4911/access/UserDao.java
@@ -2,6 +2,7 @@
import ca.bcit.infosys.comp4911.domain.User;
import com.google.common.base.Optional;
+import com.google.common.base.Strings;
import org.mindrot.jbcrypt.BCrypt;
import javax.ejb.Stateless;
@@ -17,6 +18,7 @@
private EntityManager em;
public void create(final User user) {
+ user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
em.persist(user);
}
@@ -32,18 +34,28 @@ public void delete(final User user) {
em.remove(read(user.getId()));
}
+ public void updatePassword(final int id, final String newPassword) {
+ User user = read(id);
+ if (user != null && !Strings.isNullOrEmpty(newPassword)) {
+ String oldPassword = user.getPassword();
+
+ // If old password was modified, hash the new one.
+ if (newPassword != oldPassword) {
+ user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
+ }
+ }
+ }
+
public List<User> getAll() {
TypedQuery<User> query = em.createQuery("select u from User u",
User.class);
return query.getResultList();
}
-
-
- public Optional<User> authenticate(final String username, final String password){
+ public Optional<User> authenticate(final String username, final String password) {
for (User user : getAll()) {
- if (user.getUsername().equals(username)){
- if(BCrypt.checkpw(password, user.getPassword())){
+ if (user.getUsername().equals(username)) {
+ if (BCrypt.checkpw(password, user.getPassword())) {
return Optional.of(user);
} else {
return Optional.absent();
@@ -53,4 +65,5 @@ public void delete(final User user) {
return Optional.absent();
}
+
}
View
4 src/main/java/ca/bcit/infosys/comp4911/application/SampleData.java
@@ -13,7 +13,6 @@
import ca.bcit.infosys.comp4911.domain.User;
import ca.bcit.infosys.comp4911.domain.WorkPackage;
import ca.bcit.infosys.comp4911.domain.WorkPackageAssignment;
-import org.mindrot.jbcrypt.BCrypt;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
@@ -62,12 +61,11 @@ public void populateData() {
}
private void generateUsers() {
- String hashedPassword = BCrypt.hashpw("password", BCrypt.gensalt());
for(int i = 0; i < 5; i++)
{
userDao.create(new User(
"username" + i + "@example.com",
- hashedPassword,
+ "password",
"firstName" + i,
"lastName" + i,
new Date(),

0 comments on commit a262f45

Please sign in to comment.
Something went wrong with that request. Please try again.