Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Login
- attr_reader :sessions, :users
- # Receives a array with hash with usernames and passwords
- def initialize(db = {})
- @sessions = []
- @users = db
- end
- # check if user exists
- def find_user(username, password)
- @users.select{ |user| user if (user[:username] == username && user[:password] == password) }
- end
- # new user registration, username and password are required
- def user_registration(username, password)
- users << { username: username, password: password }
- end
- # check that there is a username and password, before deleting a user.
- def destroy(username, password)
- results = find_user(username, password)
- @users.delete_if { |u| u[:username] == username && u[:password] == password } if results.present?
- end
- # We can update password
- def update_password(username, old_password, new_password)
- results = find_user(username, old_password)
- results[0][:password] = new_password
- end
- # We check if there is a username and password in our hash
- def authentication(username, password)
- return false if username.nil? || password.nil?
- auth = find_user(username, password)
- @sessions << auth[0] if auth.present?
- end
- # We eliminate session in case it exists.
- def logout(username)
- sessions.delete_if { |u| u[:username] == username } if username.present?
- end
- end
- registered_users = { username: 'Felipe', password: '123'},
- { username: 'Lisandro', password: '123'}
- login = Login.new(registered_users)
- login.user_registration('Amit', '123');
- login.authentication('Felipe', '123');
- login.update_password('Felipe', '123', '456');
- login.authentication('Felipe', '123');
- login.logout('Felipe');
- login.destroy('Felipe', '123');
Add Comment
Please, Sign In to add comment