/assignments/exam/6.4 - blog-likes/src/main/java/course/UserDAO.java

https://gitlab.com/lorenzo-biava/MongoDB-101J · Java · 114 lines · 73 code · 23 blank · 18 comment · 9 complexity · 3d23afbbaf97611ebf1347ed3016b8bc MD5 · raw file

  1. /*
  2. * Copyright 2013-2015 MongoDB Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package course;
  18. import com.mongodb.ErrorCategory;
  19. import com.mongodb.MongoWriteException;
  20. import com.mongodb.client.MongoDatabase;
  21. import com.mongodb.client.MongoCollection;
  22. import sun.misc.BASE64Encoder;
  23. import org.bson.Document;
  24. import java.io.UnsupportedEncodingException;
  25. import java.security.MessageDigest;
  26. import java.security.NoSuchAlgorithmException;
  27. import java.util.Random;
  28. import static com.mongodb.client.model.Filters.eq;
  29. public class UserDAO {
  30. private final MongoCollection<Document> usersCollection;
  31. private final ThreadLocal<Random> random = new ThreadLocal<Random>();
  32. public UserDAO(final MongoDatabase blogDatabase) {
  33. usersCollection = blogDatabase.getCollection("users");
  34. }
  35. // validates that username is unique and insert into db
  36. public boolean addUser(String username, String password, String email) {
  37. String passwordHash = makePasswordHash(password, Integer.toString(getRandom().nextInt()));
  38. Document user = new Document();
  39. user.append("_id", username).append("password", passwordHash);
  40. if (email != null && !email.equals("")) {
  41. // the provided email address
  42. user.append("email", email);
  43. }
  44. try {
  45. usersCollection.insertOne(user);
  46. return true;
  47. } catch (MongoWriteException e) {
  48. if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
  49. System.out.println("Username already in use: " + username);
  50. return false;
  51. }
  52. throw e;
  53. }
  54. }
  55. public Document validateLogin(String username, String password) {
  56. Document user;
  57. user = usersCollection.find(eq("_id", username)).first();
  58. if (user == null) {
  59. return null;
  60. }
  61. String hashedAndSalted = user.get("password").toString();
  62. String salt = hashedAndSalted.split(",")[1];
  63. if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
  64. System.out.println("Submitted password is not a match");
  65. return null;
  66. }
  67. return user;
  68. }
  69. private String makePasswordHash(String password, String salt) {
  70. try {
  71. String saltedAndHashed = password + "," + salt;
  72. MessageDigest digest = MessageDigest.getInstance("MD5");
  73. digest.update(saltedAndHashed.getBytes());
  74. BASE64Encoder encoder = new BASE64Encoder();
  75. byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes();
  76. return encoder.encode(hashedBytes) + "," + salt;
  77. } catch (NoSuchAlgorithmException e) {
  78. throw new RuntimeException("MD5 is not available", e);
  79. } catch (UnsupportedEncodingException e) {
  80. throw new RuntimeException("UTF-8 unavailable? Not a chance", e);
  81. }
  82. }
  83. private Random getRandom() {
  84. Random result = random.get();
  85. if (result == null) {
  86. result = new Random();
  87. random.set(result);
  88. }
  89. return result;
  90. }
  91. }