Guest User

Untitled

a guest
Nov 5th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. class Login
  2. attr_reader :sessions, :users
  3.  
  4. # Receives a array with hash with usernames and passwords
  5. def initialize(db = {})
  6. @sessions = []
  7. @users = db
  8. end
  9.  
  10. # check if user exists
  11. def find_user(username, password)
  12. @users.select{ |user| user if (user[:username] == username && user[:password] == password) }
  13. end
  14.  
  15. # new user registration, username and password are required
  16. def user_registration(username, password)
  17. users << { username: username, password: password }
  18. end
  19.  
  20. # check that there is a username and password, before deleting a user.
  21. def destroy(username, password)
  22. results = find_user(username, password)
  23. @users.delete_if { |u| u[:username] == username && u[:password] == password } if results.present?
  24. end
  25.  
  26. # We can update password
  27. def update_password(username, old_password, new_password)
  28. results = find_user(username, old_password)
  29. results[0][:password] = new_password
  30.  
  31. end
  32.  
  33. # We check if there is a username and password in our hash
  34. def authentication(username, password)
  35. return false if username.nil? || password.nil?
  36. auth = find_user(username, password)
  37. @sessions << auth[0] if auth.present?
  38. end
  39.  
  40. # We eliminate session in case it exists.
  41. def logout(username)
  42. sessions.delete_if { |u| u[:username] == username } if username.present?
  43. end
  44.  
  45. end
  46.  
  47. registered_users = { username: 'Felipe', password: '123'},
  48. { username: 'Lisandro', password: '123'}
  49.  
  50. login = Login.new(registered_users)
  51. login.user_registration('Amit', '123');
  52. login.authentication('Felipe', '123');
  53. login.update_password('Felipe', '123', '456');
  54. login.authentication('Felipe', '123');
  55. login.logout('Felipe');
  56. login.destroy('Felipe', '123');
Add Comment
Please, Sign In to add comment