Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2016
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.97 KB | None | 0 0
  1. //the JDbcDAO is not doing anything special
  2. public class AccountJDbcDAO extends JDbcDAO implements IAccountDAO {
  3. private static final String SQL_ACCOUNTEXISTS = "SELECT id FROM Accounts WHERE email=? ";
  4. private static final String SQL_ACCOUNTLOGGEDIN = "SELECT loggedin FROM ACCOUNTS WHERE email=?";
  5. private static final String SQL_TRY_LOGIN2 = "SELECT accountid FROM accounts WHERE email=? ";
  6. private static final String SQL_ACCOUNT_STATUS = "Select accountstatus FROM accounts WHERE accountid=?";
  7. private static final String SQL_NEW_ACCOUNT = "INSERT INTO Accounts (email,password,userName,role,loggedin) values (?,?,?,?,?) ";
  8. private static final String SQL_RESET_PASSWORD_1 = "INSERT INTO PasswordReset (email,token,expirationDate) values (?,?,NOW())";
  9. private static final String SQL_RESET_PASSWORD_2 = "INSERT INTO Accounts (password) values (?) where email=?";
  10. private static final String SQL_PASSWORDReset_DATA = "SELECT * FROM PasswordReset where email=?";
  11. private static final String SQL_LOGOUT = "UPDATE Accounts Set loggedIn=0 WHERE email=? ";
  12. private static final String SQL_GET_DATA = "SELECT * FROM Accounts WHERE email=? ";
  13. private static final String SQL_GET_PASSWORD = "SELECT password from accounts where email=?";
  14.  
  15. PreparedStatement preparedStatement;
  16. ResultSet rs = null;
  17. private static final long TOKEN_EXPIRATION_TIME = 10;
  18.  
  19. public AccountJDbcDAO(DatabaseFactory factory) {
  20. super(factory);
  21. }
  22.  
  23. @Override
  24. public int createNewAccount(String email, String password, String role, String userName) throws SQLException {
  25. if(accountExists(email)) throw new SQLException("Account already exists");
  26.  
  27. Object[] values = {email,password,userName,role,0
  28. };
  29. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_NEW_ACCOUNT, values, true);
  30. int affectedRows = preparedStatement.executeUpdate();
  31.  
  32. if (affectedRows != 1) {
  33. throw new SQLException("New Account not correctly created!");//TODO
  34. }
  35. rs = preparedStatement.getGeneratedKeys();
  36. return rs.getInt("accountid");
  37. }
  38.  
  39. @Override
  40. public boolean accountExists(String accountNameOrEmail) throws SQLException {
  41. //TODO
  42. Object[] values = {
  43. accountNameOrEmail,
  44. };
  45. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNTEXISTS, values);
  46. rs = preparedStatement.executeQuery();
  47. return rs.next();
  48. }
  49.  
  50. @Override
  51. public boolean isAccountLoggedIn(String email) throws SQLException {
  52. Object[] values = {email};
  53. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNTLOGGEDIN, values);
  54. rs = preparedStatement.executeQuery();
  55. return rs.getBoolean("loggedin");
  56. }
  57.  
  58. @Override
  59. public int tryLogin(String nameORemail) throws SQLException {
  60. //couldn´t find account
  61. if (!accountExists(nameORemail)) throw new SQLException("couldn´t find account");
  62.  
  63. if(isAccountLoggedIn(nameORemail)){
  64. throw new SQLException("already logged in");
  65. }
  66.  
  67. Object[] values1 = {nameORemail};
  68. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_TRY_LOGIN2, values1);
  69. rs = preparedStatement.executeQuery();
  70.  
  71.  
  72. if (rs.getInt("accountid") == 0) throw new SQLException("unknown error");
  73. int id = rs.getInt("accountid");
  74.  
  75. //there is more than one account with this mail/name-> wtf?
  76. rs.next();
  77. if (!rs.isLast()) throw new SQLException("for given name/email there is more than one Account!");
  78.  
  79. //set login status to true
  80. Object[] values2 = {nameORemail};
  81. preparedStatement = JDBCUtil.prepareStatement(currentConnection(),"UPDATE Accounts Set loggedIn =1 where email=?", values2);
  82. int rows = preparedStatement.executeUpdate();
  83.  
  84. if(rows!=1) throw new SQLException("couldn´t update login Status!");
  85.  
  86. //everything okay
  87. return id;
  88. }
  89.  
  90.  
  91. @Override
  92. public String getStoredPassword(String email) throws SQLException {
  93. if (!accountExists(email)) throw new SQLException("couldn´t find account");
  94. Object[] values = {email};
  95.  
  96. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_GET_PASSWORD, values);
  97. rs = preparedStatement.executeQuery();
  98.  
  99. String pass = rs.getString("password");
  100.  
  101. if(rs.isLast())return null;
  102.  
  103. return pass;
  104. }
  105.  
  106. @Override
  107. public String getAccountRole(int accountId) throws SQLException {
  108. Object[] values = {accountId};
  109.  
  110. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_ACCOUNT_STATUS, values);
  111. rs = preparedStatement.executeQuery();
  112.  
  113. String accountRole = rs.getString("role");
  114. //checking if there is other data
  115. rs.next();
  116. if (!rs.isLast()) throw new SQLException("Got more than one Status back.");
  117.  
  118. return accountRole;
  119. }
  120.  
  121. @Override
  122. public boolean saveDeleteAccount(Account acc) {
  123. return false;
  124. }
  125.  
  126. @Override
  127. public boolean logout(String email) throws SQLException {
  128. Object[] em = {email};
  129. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_LOGOUT, em);
  130. int rows = preparedStatement.executeUpdate();
  131.  
  132. if (rows == 1) return true;
  133.  
  134. return false;
  135. }
  136.  
  137. @Override
  138. public boolean preparePasswordReset(String email, String token) throws SQLException {
  139. //check if already exists
  140. Object[] em = {email};
  141. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
  142. rs = preparedStatement.executeQuery();
  143.  
  144. rs.next();
  145. if(!rs.isLast()){
  146. //more than one entry for that email
  147. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), "Delete FROM PasswordReset Where email =?", em);
  148. int rows = preparedStatement.executeUpdate();
  149. }
  150.  
  151. Object[] values = {email, token};
  152. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_RESET_PASSWORD_1, values);
  153. int rows = preparedStatement.executeUpdate();
  154.  
  155. if (rows == 1) return true;
  156.  
  157. return false;
  158. }
  159.  
  160. @Override
  161. public boolean isTokenExpired(String email) throws SQLException {
  162. Object[] em = {email};
  163. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
  164. rs = preparedStatement.executeQuery();
  165.  
  166. if(!rs.isBeforeFirst())throw new SQLException("No PasswordReset entry does exist.");
  167.  
  168. Instant saveTime = rs.getDate("expirationDate").toInstant();
  169. saveTime.plus(TOKEN_EXPIRATION_TIME, ChronoUnit.MINUTES);
  170.  
  171. if (saveTime.isAfter(Instant.now())) {
  172. //took to long to set a new password -> delete old data -> user needs to make new one
  173. deletePasswordResetData(email);
  174. return true;
  175. }
  176. return false;
  177. }
  178.  
  179. @Override
  180. public String getToken(String email) throws SQLException {
  181. Object[] em = {email};
  182. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_PASSWORDReset_DATA, em);
  183. rs = preparedStatement.executeQuery();
  184.  
  185. if(!rs.isBeforeFirst())throw new SQLException("No PasswordReset entry does exist.");
  186.  
  187. return rs.getString("token");
  188.  
  189. }
  190.  
  191. @Override
  192. public boolean performPasswordReset(String email, String newPassword) throws SQLException {
  193. if (isTokenExpired(email)) {
  194. return false;
  195. }
  196.  
  197. Object[] values = {newPassword, email, email};
  198. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_RESET_PASSWORD_2, values);
  199. int rows = preparedStatement.executeUpdate();
  200.  
  201. if (rows == 1){deletePasswordResetData(email);
  202. return true;}
  203.  
  204. return false;
  205. }
  206.  
  207.  
  208. @Override
  209. public boolean deletePasswordResetData(String email) throws SQLException {
  210. Object[] em = {email};
  211. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), "DELETE FROM PASSWORDRESET Where email=?", em);
  212. int rows = preparedStatement.executeUpdate();
  213. return true;
  214. }
  215.  
  216. @Override
  217. public Account getAccountData(String email) throws SQLException {
  218. Object[] values = { email};
  219. preparedStatement = JDBCUtil.prepareStatement(currentConnection(), SQL_GET_DATA, values);
  220. rs = preparedStatement.executeQuery();
  221.  
  222. if(!rs.isBeforeFirst()) return null;
  223.  
  224. Account user = new Account();
  225. //TODO fill account
  226. return user;
  227. }
  228.  
  229. //AbstractController isn´t doing anything special
  230. public class AccountController extends AbstractController {
  231. private static final long TOKEN_EXPIRATION_TIME = 10;
  232. private IAccountDAO accountDAO;
  233. private PasswordTool passAuth = new PasswordTool(); //hashes passwords and checks them; works without problems
  234.  
  235. public AccountController(DatabaseFactory factory) {
  236. super(factory);
  237. this.accountDAO = factory.getAccountDAO();
  238. }
  239.  
  240. /**
  241. * 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.
  242. * @param account the Account whose Password was forgotten
  243. * @return and token in BASE64.URL encoded which shall be sent to the Account´s email and never stored. null if some DB error.
  244. */
  245. public String forgotPassword(Account account) {
  246. boolean valid = false;
  247. String token = null;
  248. try {
  249. token = passAuth.createToken();
  250. String hashedToken = passAuth.encryptToken(token);
  251. valid = accountDAO.preparePasswordReset(account.getEmail(), hashedToken);
  252. } catch (SQLException e) {
  253. e.printStackTrace();
  254. }
  255. if (!valid) return null;
  256. return token;
  257. }
  258.  
  259. /**
  260. * Only works if for the same Accounts email #forgotPassword() was previously called.
  261. * Performs the reset of the old Password to an new one, if the token is valid.
  262. * @param account the Account whose, password shall be reset.
  263. * @param newPassword the new Password for this Account. NOTE: Must be verified before this method. NOTE2: password must be in plain text
  264. * @param token the token which has been sent to the users email (created by forgotPassword)
  265. * @return false, if the token is wrong or already expired (will need to call #forgotPassword again). True otherwise
  266. */
  267. public boolean resetForgottenPassword(Account account, String newPassword, String token) {
  268. boolean valid = false;
  269. try {
  270. if (accountDAO.isTokenExpired(account.getEmail())) {
  271. return false;
  272. }
  273. String storedToken = accountDAO.getToken(account.getEmail());
  274.  
  275. if (!passAuth.checkToken(token, storedToken)) {
  276. accountDAO.deletePasswordResetData(account.getEmail());
  277. return false;
  278. }
  279.  
  280. //token is correct-> update password
  281. String password = passAuth.hashPassword(newPassword.toCharArray());
  282. valid = accountDAO.performPasswordReset(account.getEmail(), password);
  283. } catch (SQLException e) {
  284. e.printStackTrace();
  285. }
  286. return valid;
  287. }
  288.  
  289.  
  290. public boolean logoutAccount(String email) {
  291. boolean valid = false;
  292. try {
  293. valid = accountDAO.logout(email);
  294. //TODO notify all systems
  295. } catch (SQLException e) {
  296. e.printStackTrace();
  297. }
  298. return valid;
  299. }
  300.  
  301. /**
  302. * Creates an new Account for an given email, if not exists
  303. * @param tempAcc The Account with the most basic informations
  304. * @param password The password for that User. NOTE: Password must be validated before this method is called. NOTE2: password must be in plain text
  305. * @return null, if Account already exists. An Account Object if creation was successfull
  306. */
  307. public Account createNewAccount(Account tempAcc, String password) {
  308. Account account = null;
  309. try {
  310. if (accountDAO.accountExists(tempAcc.getEmail())) {
  311. return null; //TODO throw exception?
  312. }
  313. String hashPassword = passAuth.hashPassword(password.toCharArray());
  314. int id = accountDAO.createNewAccount(tempAcc.getEmail(), hashPassword, tempAcc.getRole().toString(), tempAcc.getCurrentUserName());
  315.  
  316. if(!(id>0)) {
  317. //some error
  318. }
  319. account = accountDAO.getAccountData(tempAcc.getEmail());
  320. } catch (SQLException e) {
  321. e.printStackTrace();
  322. }
  323.  
  324. return account;
  325. }
  326.  
  327. /**
  328. * logs an known User into the System, if the given password is associated with the email
  329. * @param email the email of the User to be logged in
  330. * @param password the delivered password with the User tries to login
  331. * @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.
  332. * Will return null if the User is already logged in, and will log that user out.
  333. */
  334. public Account tryLoginUser(String email, String password) {
  335. Account account = null;
  336. try {
  337. if (!accountDAO.accountExists(email)) {
  338. return null;
  339. }
  340. if (accountDAO.isAccountLoggedIn(email)) {
  341. this.logoutAccount(email);
  342. return null;
  343. }
  344. String storedPassword = accountDAO.getStoredPassword(email);
  345.  
  346. if (storedPassword == null) {
  347. //TODO wtf that can´t be
  348. return null;
  349. }
  350.  
  351. if (!passAuth.authenticate(password, storedPassword)) {
  352. return null;
  353. }
  354.  
  355. int id = accountDAO.tryLogin(email);
  356.  
  357. //TODO gather information etc
  358. account = accountDAO.getAccountData(email);
  359.  
  360. if (account.getAccountId() != id) {
  361. //logged in account does not equal to the data, wtf
  362. //TODO
  363. }
  364. //TODO notify systems that new user logged in
  365.  
  366. } catch (SQLException e) {
  367. e.printStackTrace();
  368. }
  369. return account;
  370. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement