class Trackington::UserRepository

Constants

SALT_LENGHT
SESSION_KEY_LENGTH

Public Instance Methods

count() click to toggle source
# File lib/trackington/app/users.rb, line 54
def count
  Models::User.count
end
login(email, password) click to toggle source
# File lib/trackington/app/users.rb, line 29
def login(email, password)
  user = Models::User.where(email: email).first

  fail "Email/password don't match" if user.nil?

  credential = Models::Credential.where(user_id: user.id).first

  check_credentials(credential, password)

  credential.session_key = generate_string SESSION_KEY_LENGTH

  credential.save

  credential.session_key
end
logout(session_key) click to toggle source
# File lib/trackington/app/users.rb, line 45
def logout(session_key)
  credential = Models::Credential.where(session_key: session_key).first

  return if credential.nil?

  credential.session_key = nil
  credential.save
end
register(email, password) click to toggle source
# File lib/trackington/app/users.rb, line 9
def register(email, password)
  check_existing email

  user = Models::User.new
  user.email = email
  user.save

  credential = create_credentials(user.id, password)

  credential.session_key
end
user(session_key) click to toggle source
# File lib/trackington/app/users.rb, line 21
def user(session_key)
  db_credential = Models::Credential.where(session_key: session_key).first

  db_user = Models::User.find(db_credential.user_id)

  User.new(db_user.id, db_user.email)
end

Private Instance Methods

check_credentials(credential, password) click to toggle source
# File lib/trackington/app/users.rb, line 66
def check_credentials(credential, password)
  expected = hash(credential.salt + password)

  fail "Username/password don't match." if expected != credential.password
end
check_existing(email) click to toggle source
# File lib/trackington/app/users.rb, line 72
def check_existing(email)
  existing_user = Models::User.where(email: email).first

  fail 'User already exists.' unless existing_user.nil?
end
create_credentials(user_id, password) click to toggle source
# File lib/trackington/app/users.rb, line 78
def create_credentials(user_id, password)
  salt = hash(generate_string(SALT_LENGHT))
  credential = Models::Credential.new
  credential.password = hash(salt + password)
  credential.salt = salt
  credential.session_key = generate_string SESSION_KEY_LENGTH
  credential.user_id = user_id
  credential.save
  credential
end
generate_string(length) click to toggle source
# File lib/trackington/app/users.rb, line 93
def generate_string(length)
  o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
  (0...length).map { o[rand(o.length)] }.join
end
hash(input) click to toggle source
# File lib/trackington/app/users.rb, line 89
def hash(input)
  Digest::SHA256.base64digest(input)
end