Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //the JDbcDAO is not doing anything special
- public class AccountJDbcDAO extends JDbcDAO implements IAccountDAO {
- private static final String SQL_ACCOUNTEXISTS = "SELECT id FROM Accounts WHERE email=? ";
- private static final String SQL_ACCOUNTLOGGEDIN = "SELECT loggedin FROM ACCOUNTS WHERE email=?";
- private static final String SQL_TRY_LOGIN2 = "SELECT accountid FROM accounts WHERE email=? ";
- private static final String SQL_ACCOUNT_STATUS = "Select accountstatus FROM accounts WHERE accountid=?";
- private static final String SQL_NEW_ACCOUNT = "INSERT INTO Accounts (email,password,userName,role,loggedin) values (?,?,?,?,?) ";
- private static final String SQL_RESET_PASSWORD_1 = "INSERT INTO PasswordReset (email,token,expirationDate) values (?,?,NOW())";
- private static final String SQL_RESET_PASSWORD_2 = "INSERT INTO Accounts (password) values (?) where email=?";
- private static final String SQL_PASSWORDReset_DATA = "SELECT * FROM PasswordReset where email=?";
- private static final String SQL_LOGOUT = "UPDATE Accounts Set loggedIn=0 WHERE email=? ";
- private static final String SQL_GET_DATA = "SELECT * FROM Accounts WHERE email=? ";
- private static final String SQL_GET_PASSWORD = "SELECT password from accounts where email=?";
- PreparedStatement preparedStatement;
- ResultSet rs = null;
- private static final long TOKEN_EXPIRATION_TIME = 10;
- public AccountJDbcDAO(DatabaseFactory factory) {
- super(factory);
- }
- @Override
- public int createNewAccount(String email, String password, String role, String userName) throws SQLException {
- if(accountExists(email)) throw new SQLException("Account already exists");
- Object[] values = {email,password,userName,role,0
- };
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_NEW_ACCOUNT, values, true);
- int affectedRows = preparedStatement.executeUpdate();
- if (affectedRows != 1) {
- throw new SQLException("New Account not correctly created!");//TODO
- }
- rs = preparedStatement.getGeneratedKeys();
- return rs.getInt("accountid");
- }
- @Override
- public boolean accountExists(String accountNameOrEmail) throws SQLException {
- //TODO
- Object[] values = {
- accountNameOrEmail,
- };
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNTEXISTS, values);
- rs = preparedStatement.executeQuery();
- return rs.next();
- }
- @Override
- public boolean isAccountLoggedIn(String email) throws SQLException {
- Object[] values = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNTLOGGEDIN, values);
- rs = preparedStatement.executeQuery();
- return rs.getBoolean("loggedin");
- }
- @Override
- public int tryLogin(String nameORemail) throws SQLException {
- //couldn´t find account
- if (!accountExists(nameORemail)) throw new SQLException("couldn´t find account");
- if(isAccountLoggedIn(nameORemail)){
- throw new SQLException("already logged in");
- }
- Object[] values1 = {nameORemail};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_TRY_LOGIN2, values1);
- rs = preparedStatement.executeQuery();
- if (rs.getInt("accountid") == 0) throw new SQLException("unknown error");
- int id = rs.getInt("accountid");
- //there is more than one account with this mail/name-> wtf?
- rs.next();
- if (!rs.isLast()) throw new SQLException("for given name/email there is more than one Account!");
- //set login status to true
- Object[] values2 = {nameORemail};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(),"UPDATE Accounts Set loggedIn =1 where email=?", values2);
- int rows = preparedStatement.executeUpdate();
- if(rows!=1) throw new SQLException("couldn´t update login Status!");
- //everything okay
- return id;
- }
- @Override
- public String getStoredPassword(String email) throws SQLException {
- if (!accountExists(email)) throw new SQLException("couldn´t find account");
- Object[] values = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_GET_PASSWORD, values);
- rs = preparedStatement.executeQuery();
- String pass = rs.getString("password");
- if(rs.isLast())return null;
- return pass;
- }
- @Override
- public String getAccountRole(int accountId) throws SQLException {
- Object[] values = {accountId};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNT_STATUS, values);
- rs = preparedStatement.executeQuery();
- String accountRole = rs.getString("role");
- //checking if there is other data
- rs.next();
- if (!rs.isLast()) throw new SQLException("Got more than one Status back.");
- return accountRole;
- }
- @Override
- public boolean saveDeleteAccount(Account acc) {
- return false;
- }
- @Override
- public boolean logout(String email) throws SQLException {
- Object[] em = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_LOGOUT, em);
- int rows = preparedStatement.executeUpdate();
- if (rows == 1) return true;
- return false;
- }
- @Override
- public boolean preparePasswordReset(String email, String token) throws SQLException {
- //check if already exists
- Object[] em = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
- rs = preparedStatement.executeQuery();
- rs.next();
- if(!rs.isLast()){
- //more than one entry for that email
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), "Delete FROM PasswordReset Where email =?", em);
- int rows = preparedStatement.executeUpdate();
- }
- Object[] values = {email, token};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_RESET_PASSWORD_1, values);
- int rows = preparedStatement.executeUpdate();
- if (rows == 1) return true;
- return false;
- }
- @Override
- public boolean isTokenExpired(String email) throws SQLException {
- Object[] em = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
- rs = preparedStatement.executeQuery();
- if(!rs.isBeforeFirst())throw new SQLException("No PasswordReset entry does exist.");
- Instant saveTime = rs.getDate("expirationDate").toInstant();
- saveTime.plus(TOKEN_EXPIRATION_TIME, ChronoUnit.MINUTES);
- if (saveTime.isAfter(Instant.now())) {
- //took to long to set a new password -> delete old data -> user needs to make new one
- deletePasswordResetData(email);
- return true;
- }
- return false;
- }
- @Override
- public String getToken(String email) throws SQLException {
- Object[] em = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
- rs = preparedStatement.executeQuery();
- if(!rs.isBeforeFirst())throw new SQLException("No PasswordReset entry does exist.");
- return rs.getString("token");
- }
- @Override
- public boolean performPasswordReset(String email, String newPassword) throws SQLException {
- if (isTokenExpired(email)) {
- return false;
- }
- Object[] values = {newPassword, email, email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_RESET_PASSWORD_2, values);
- int rows = preparedStatement.executeUpdate();
- if (rows == 1){deletePasswordResetData(email);
- return true;}
- return false;
- }
- @Override
- public boolean deletePasswordResetData(String email) throws SQLException {
- Object[] em = {email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), "DELETE FROM PASSWORDRESET Where email=?", em);
- int rows = preparedStatement.executeUpdate();
- return true;
- }
- @Override
- public Account getAccountData(String email) throws SQLException {
- Object[] values = { email};
- preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_GET_DATA, values);
- rs = preparedStatement.executeQuery();
- if(!rs.isBeforeFirst()) return null;
- Account user = new Account();
- //TODO fill account
- return user;
- }
- //AbstractController isn´t doing anything special
- public class AccountController extends AbstractController {
- private static final long TOKEN_EXPIRATION_TIME = 10;
- private IAccountDAO accountDAO;
- private PasswordTool passAuth = new PasswordTool(); //hashes passwords and checks them; works without problems
- public AccountController(DatabaseFactory factory) {
- super(factory);
- this.accountDAO = factory.getAccountDAO();
- }
- /**
- * Generates for the given Account an token which shall be sent to the email of the Account and must be used to be identified in an given time.
- * @param account the Account whose Password was forgotten
- * @return and token in BASE64.URL encoded which shall be sent to the Account´s email and never stored. null if some DB error.
- */
- public String forgotPassword(Account account) {
- boolean valid = false;
- String token = null;
- try {
- token = passAuth.createToken();
- String hashedToken = passAuth.encryptToken(token);
- valid = accountDAO.preparePasswordReset(account.getEmail(), hashedToken);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if (!valid) return null;
- return token;
- }
- /**
- * Only works if for the same Accounts email #forgotPassword() was previously called.
- * Performs the reset of the old Password to an new one, if the token is valid.
- * @param account the Account whose, password shall be reset.
- * @param newPassword the new Password for this Account. NOTE: Must be verified before this method. NOTE2: password must be in plain text
- * @param token the token which has been sent to the users email (created by forgotPassword)
- * @return false, if the token is wrong or already expired (will need to call #forgotPassword again). True otherwise
- */
- public boolean resetForgottenPassword(Account account, String newPassword, String token) {
- boolean valid = false;
- try {
- if (accountDAO.isTokenExpired(account.getEmail())) {
- return false;
- }
- String storedToken = accountDAO.getToken(account.getEmail());
- if (!passAuth.checkToken(token, storedToken)) {
- accountDAO.deletePasswordResetData(account.getEmail());
- return false;
- }
- //token is correct-> update password
- String password = passAuth.hashPassword(newPassword.toCharArray());
- valid = accountDAO.performPasswordReset(account.getEmail(), password);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return valid;
- }
- public boolean logoutAccount(String email) {
- boolean valid = false;
- try {
- valid = accountDAO.logout(email);
- //TODO notify all systems
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return valid;
- }
- /**
- * Creates an new Account for an given email, if not exists
- * @param tempAcc The Account with the most basic informations
- * @param password The password for that User. NOTE: Password must be validated before this method is called. NOTE2: password must be in plain text
- * @return null, if Account already exists. An Account Object if creation was successfull
- */
- public Account createNewAccount(Account tempAcc, String password) {
- Account account = null;
- try {
- if (accountDAO.accountExists(tempAcc.getEmail())) {
- return null; //TODO throw exception?
- }
- String hashPassword = passAuth.hashPassword(password.toCharArray());
- int id = accountDAO.createNewAccount(tempAcc.getEmail(), hashPassword, tempAcc.getRole().toString(), tempAcc.getCurrentUserName());
- if(!(id>0)) {
- //some error
- }
- account = accountDAO.getAccountData(tempAcc.getEmail());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return account;
- }
- /**
- * logs an known User into the System, if the given password is associated with the email
- * @param email the email of the User to be logged in
- * @param password the delivered password with the User tries to login
- * @return an Account Object with all the known data of that User, null if an Error occured and the email and/or password for it is wrong.
- * Will return null if the User is already logged in, and will log that user out.
- */
- public Account tryLoginUser(String email, String password) {
- Account account = null;
- try {
- if (!accountDAO.accountExists(email)) {
- return null;
- }
- if (accountDAO.isAccountLoggedIn(email)) {
- this.logoutAccount(email);
- return null;
- }
- String storedPassword = accountDAO.getStoredPassword(email);
- if (storedPassword == null) {
- //TODO wtf that can´t be
- return null;
- }
- if (!passAuth.authenticate(password, storedPassword)) {
- return null;
- }
- int id = accountDAO.tryLogin(email);
- //TODO gather information etc
- account = accountDAO.getAccountData(email);
- if (account.getAccountId() != id) {
- //logged in account does not equal to the data, wtf
- //TODO
- }
- //TODO notify systems that new user logged in
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return account;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement