<commit_before>#!/bin/env ruby
# encoding: utf-8
#07-2013 Migration in Ruby On Rails  3.2 by <NAME>
require 'digest/sha1'

class User < ActiveRecord::Base
  # Virtual attribute for the unencrypted password
  attr_accessor :password, :is_admin, :is_contrat_admin, :is_fonc_admin
  # Class attribute accessor for current user
  cattr_accessor :current_user

  has_many                  :memberships, :dependent => :destroy
  has_one                   :user_image
  has_many                  :groups, :through => :memberships
  has_many                  :roles

  # Conf pour le plugin Authorization
  acts_as_authorized_user
  acts_as_authorizable
  # -----

  validates_uniqueness_of   :nom,
                            :scope => :prenom,
                            :message => " le couple nom et prénom est déja référencé",
                            :case_sensitive => false
  validates_presence_of     :login, :email, :nom, :prenom
  validates_presence_of     :password,                   :if => :password_required?
  validates_presence_of     :password_confirmation,      :if => :password_required?
  validates_length_of       :password, :within => 4..40, :if => :password_required?
  validates_confirmation_of :password,                   :if => :password_required?
  validates_length_of       :login,    :within => 3..40
  validates_length_of       :email,    :within => 3..100
  validates_format_of       :email,
                            :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                            :message => ': email doit être valide'
  validates_uniqueness_of   :login, :email, :case_sensitive => false, :message => " Cette valeur est déjà utilisée par un autre utilisateur"

  before_save :encrypt_password
  
  def has_role?( role_name, authorizable_obj = nil )
    if authorizable_obj.nil?
      for role in self.roles
        if role.name == role_name
          return true
        end
      end
    else
      for role in self.roles
        if (role.name == role_name ) && (authorizable_obj.class.to_s == role.authorizable_type) && (authorizable_obj.id == role.authorizable_id)
          return true
        end
        if(role.name == role_name) && (authorizable_obj.class.to_s == 'Contrat') && (role.authorizable_type == 'Projet')
          projet = Projet.find(role.authorizable_id)
          if authorizable_obj.projets.include? projet
            return true
          end
        end
      end
    end
    return false
  end


  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    #utile pour developper offline
    #return u
    if u && u.ldap == true
      u && u.authenticated_ldap?(password, login) ? u : nil
    else
      u && u.authenticated?(password) ? u : nil
    end
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

  def authenticated_ldap?(password, login)
    flag = false

    user = User.find_by_login(login)

    # authentification ldap
    BASES_LDAP.each do |ldap|
      if user.type_ldap == ldap["type"]
        flag = false
        port = ldap["port"]
        host = ldap["host"]
        if port == 389
          conn = Net::LDAP.new(:host=>host, :port=>port)
        else
          conn = Net::LDAP.new(:host=>host, :port=>port, :encryption => :simple_tls)
        end
        begin
          base = ldap["base"]
          if ldap["type"] == 'ildap INRIA'
             
            if conn.bind_as(:base => base,:filter =>"(inriaLogin=#{login})",:password => password) 
              flag = true
            end
            break
          else
            if conn.bind_as(:base => base,:filter =>"(uid=#{login})",:password => password)
              flag = true
            end
            break
          end
        rescue Errno::ETIMEDOUT
          flag = false
        rescue Net::LDAP::LdapError
          flag = false
        end
      end
    end
    return flag
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at
  end

  # These create and unset the fields required for remembering users between browser closes<commit_msg>ajout authentification ldap non anonyme<commit_after>#!/bin/env ruby
# encoding: utf-8
#07-2013 Migration in Ruby On Rails  3.2 by <NAME>
require 'digest/sha1'

class User < ActiveRecord::Base
  # Virtual attribute for the unencrypted password
  attr_accessor :password, :is_admin, :is_contrat_admin, :is_fonc_admin
  # Class attribute accessor for current user
  cattr_accessor :current_user

  has_many                  :memberships, :dependent => :destroy
  has_one                   :user_image
  has_many                  :groups, :through => :memberships
  has_many                  :roles

  # Conf pour le plugin Authorization
  acts_as_authorized_user
  acts_as_authorizable
  # -----

  validates_uniqueness_of   :nom,
                            :scope => :prenom,
                            :message => " le couple nom et prénom est déja référencé",
                            :case_sensitive => false
  validates_presence_of     :login, :email, :nom, :prenom
  validates_presence_of     :password,                   :if => :password_required?
  validates_presence_of     :password_confirmation,      :if => :password_required?
  validates_length_of       :password, :within => 4..40, :if => :password_required?
  validates_confirmation_of :password,                   :if => :password_required?
  validates_length_of       :login,    :within => 3..40
  validates_length_of       :email,    :within => 3..100
  validates_format_of       :email,
                            :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                            :message => ': email doit être valide'
  validates_uniqueness_of   :login, :email, :case_sensitive => false, :message => " Cette valeur est déjà utilisée par un autre utilisateur"

  before_save :encrypt_password
  
  def has_role?( role_name, authorizable_obj = nil )
    if authorizable_obj.nil?
      for role in self.roles
        if role.name == role_name
          return true
        end
      end
    else
      for role in self.roles
        if (role.name == role_name ) && (authorizable_obj.class.to_s == role.authorizable_type) && (authorizable_obj.id == role.authorizable_id)
          return true
        end
        if(role.name == role_name) && (authorizable_obj.class.to_s == 'Contrat') && (role.authorizable_type == 'Projet')
          projet = Projet.find(role.authorizable_id)
          if authorizable_obj.projets.include? projet
            return true
          end
        end
      end
    end
    return false
  end


  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    #utile pour developper offline
    #return u
    if u && u.ldap == true
      u && u.authenticated_ldap?(password, login) ? u : nil
    else
      u && u.authenticated?(password) ? u : nil
    end
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

  def authenticated_ldap?(password, login)
    flag = false

    user = User.find_by_login(login)

    # authentification ldap
    BASES_LDAP.each do |ldap|
      if user.type_ldap == ldap["type"]
        flag = false
        port = ldap["port"]
        host = ldap["host"]
        base = ldap["base"]
	auth = ldap["auth"]
	if auth == 1
	  binddn = ldap["binddn"]
	  bindpw = ldap["bindpw"]
	end

        if port == 389
	  if auth == 0
            conn = Net::LDAP.new(:host=>host, :port=>port)
	  else
            conn = Net::LDAP.new(:host=>host, :port=>port, :base=>base, :auth => {
           		:method => :simple,
           		:username => binddn,
           		:password => <PASSWORD> }
	    )
	  end
        else
	  if auth == 0
            conn = Net::LDAP.new(:host=>host, :port=>port, :encryption => :simple_tls)
	  else
            conn = Net::LDAP.new(:host=>host, :port=>port, :encryption => :simple_tls, :base=>base, :auth => {
           		:method => :simple,
           		:username => binddn,
           		:password => <PASSWORD> }
	    )
	  end
        end
        begin
          if ldap["type"] == 'ildap INRIA'
             
            if conn.bind_as(:base => base,:filter =>"(inriaLogin=#{login})",:password => password) 
              flag = true
            end
            break
          else
            if conn.bind_as(:base => base,:filter =>"(uid=#{login})",:password => password)
              flag = true
            end
            break
          end
        rescue Errno::ETIMEDOUT
          flag = false
        rescue Net::LDAP::LdapError
          flag = false
        end
      end
    end
    return flag
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at
  end

  # These create and unset the fields required for remembering users between browser closes
{'fraction_non_alphanumeric': 0.10703459809762726, 'fraction_numerical': 0.005957980558168705, 'mean_word_length': 2.1535926170072512, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 76, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2802488', 'n_tokens_mistral': 3038, 'n_tokens_neox': 2933, 'n_words': 747}