Skip to content

Instantly share code, notes, and snippets.

@marcosgz
Created June 19, 2021 14:31
Show Gist options
  • Save marcosgz/280c4605cc64d16a3825a7a5e45cde16 to your computer and use it in GitHub Desktop.
Save marcosgz/280c4605cc64d16a3825a7a5e45cde16 to your computer and use it in GitHub Desktop.
Simple demonstration about md5 login
>> authenticate?(3, 'one')
=> false
>> authenticate?(1, 'one1')
=> false
>> authenticate?(1, 'one')
=> true
class Account < Struct.new(:id, :digest_password)
# Check if password is valid
#
# @param password [String] The user password
# @return [Boolean] True when given password match with encrypted user password
def valid_password?(password)
self.class.encrypt(password) == digest_password
end
# Create a new Account
#
# @param options [Hash] List of attributes to the account
# @option options [Integer] :id The account ID
# @option options [Integer] :id The account plain password (Application are going to encrypt and safe store password)
# @return [Account] Return an instance of Account
def self.create(id:, password:)
new(id, encrypt(password))
end
# Encrypt string using MD5
#
# @param value [String] The string that should be encrypted
# @return [String] hexdigest generated with MD5 algorithm
def self.encrypt(value)
Digest::MD5.hexdigest(value.to_s)
end
end
# Add accounts to the @accounts instance variable
@accounts = []
@accounts << Account.create(id: 1, password: 'one') #<struct Account id=1, digest_password="f97c5d29941bfb1b2fdab0874906ab82">
@accounts << Account.create(id: 2, password: 'two') #<struct Account id=2, digest_password="b8a9f715dbb64fd5c56e7783c6820a61">
# Define authenticate method
# @param id [Number] the account id
# @param password [String] the account password
# @return [Boolean] Return true if account exist and given password match, or false in case of missing id or invalid password
def authenticate?(id, password)
account = @accounts.find { |a| a.id == id }
return false unless account
account.valid_password?(password)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment