|
| 1 | +package com.hktransfield; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.Map; |
| 4 | + |
| 5 | +import com.password4j.Hash; |
| 6 | +import com.password4j.Password; |
| 7 | + |
| 8 | +/** Represents |
| 9 | + * https://happycoding.io/tutorials/java-server/secure-password-storage |
| 10 | + * https://www.quickprogrammingtips.com/java/how-to-securely-store-passwords-in-java.html |
| 11 | + */ |
| 12 | +public class UserDatabase { |
| 13 | + // declare class scope variables |
| 14 | + private static UserDatabase instance; |
| 15 | + private Map<String, Hash> userDB = new HashMap<>(); |
| 16 | + private UserDatabase(){} // singleton class |
| 17 | + |
| 18 | + /** |
| 19 | + * Create UserDatabase object if it does not exist. |
| 20 | + * |
| 21 | + * @return |
| 22 | + */ |
| 23 | + public static UserDatabase getInstance(){ |
| 24 | + if(instance == null) instance = new UserDatabase(); |
| 25 | + return instance; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Prevents a new user from creating an account with an |
| 30 | + * already existing username. |
| 31 | + * |
| 32 | + * @param username the chosen username to validate |
| 33 | + * @return true if username already exists |
| 34 | + */ |
| 35 | + public boolean isUsernameTaken(String username){ |
| 36 | + return userDB.containsKey(username); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * |
| 41 | + * @param username |
| 42 | + * @param password |
| 43 | + */ |
| 44 | + public void registerUser(String username, char[] password){ |
| 45 | + Hash hash = Password.hash(new String(password)).addRandomSalt(42).addPepper("COMPX518").withArgon2(); |
| 46 | + userDB.put(username, hash); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * |
| 51 | + * @param username |
| 52 | + * @param password |
| 53 | + * @return |
| 54 | + */ |
| 55 | + public boolean isLoginCorrect(String username, char[] password) { |
| 56 | + |
| 57 | + // username isn't registered |
| 58 | + if(!userDB.containsKey(username)){ |
| 59 | + System.out.println("Can't find username"); |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + Hash storedPassword = userDB.get(username); |
| 64 | + boolean verified = Password.check(new String(password), storedPassword); |
| 65 | + |
| 66 | + return verified; |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments