class User < ActiveRecord::Base
  validates :uid,  presence: true, uniqueness: true
  validates :provider, presence: true

  # Takes an ldap authentication and looks it up in the database
  def self.sign_in_from_omniauth(auth)
    uid = auth[:extra][:raw_info][:uid].to_a[0]
    provider = auth[:provider]

    find_by(uid: uid, provider: provider) || create_user_from_omniauth(auth)
  end

  # Adds an ldap authentication into the database
  def self.create_user_from_omniauth(auth)
    uid = auth[:extra][:raw_info][:uid].to_a[0]
    email = auth[:info][:email]
    provider = auth[:provider]
    name = auth[:info][:name]

    create!(uid: uid,
            name: name,
            email: email,
            provider: provider,
            admin: false )
  end
end
