Skip to content

Instantly share code, notes, and snippets.

@dapi
Created January 4, 2012 20:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dapi/1562013 to your computer and use it in GitHub Desktop.
Save dapi/1562013 to your computer and use it in GitHub Desktop.
1С-Битрикс авторизация на рельсах (ruby on rails)
# Расширение контроллера
#
module Bitrix::Authorization
def current_user
@current_user ||= find_from_cookie
end
def login_user(user)
logout_user if current_user
@current_user = user
flash[:notice] = t(:login_user, :scope=>[:flashes], :name=>user.name)
auth = Session.create_or_update_by_hash(self.bitrix_session_hash, user, request.remote_ip)
self.bitrix_session_hash = auth.stored_hash
end
def logout_user
@current_user = nil if current_user
# Странно, но если вызывать bitrix_session_hash
# без self. то возвращает nil
#
Session.delete_by_hash(self.bitrix_session_hash)
self.bitrix_session_hash = nil
end
def find_from_cookie
if auth = Session.find_by_stored_hash(self.bitrix_session_hash)
auth.user
else
nil
end
end
def bitrix_session_hash
cookies['INVESTCAFE_UIDH']
end
def bitrix_session_hash=(hash)
unless hash
# http://stackoverflow.com/questions/52917/how-do-you-delete-wild-card-cookies-in-rails
# http://stackoverflow.com/questions/1232174/rails-cookies-set-start-date-and-expire-date
#__utma __utmb __utmc __utmz
%w(ICF_HASH_UNAUTH INVESTCAFE_UIDH INVESTCAFE_LOGIN PHPSESSID).each do |key|
cookies.delete key, :domain => Settings.application.cookie_domain
end
return
end
if request.domain == 'localhost'
cookies['INVESTCAFE_UIDH'] = { :value => hash }
cookies['INVESTCAFE_LOGIN'] = { :value => current_user.login }
else
cookies['ICF_HASH_UNAUTH'] = { :value => '' }
cookies['INVESTCAFE_UIDH'] = {
:value => hash,
:domain => Settings.application.cookie_domain # request.domain
}
cookies['INVESTCAFE_LOGIN'] = {
:value => current_user.login,
:domain => Settings.application.cookie_domain # request.domain
}
end
end
end
#
# разработчик - Дмитрий Максимов http://www.dmaximov.net/
#
class Session < ActiveRecord::Base
set_table_name :b_user_stored_auth
belongs_to :user, :foreign_key => 'user_id'
attr_accessor :login, :password, :backurl
def self.create_or_update_by_hash(hash, user, ip_addr)
t = Time.now
if hash and auth = find_by_stored_hash(hash)
auth.update_attributes('last_auth' => t,
'user_id' => user.id,
'temp_hash' => 'N',
'ip_addr' => ip_addr)
auth
else
create('user_id' => user.id,
'last_auth' => t,
'date_reg' => t,
'temp_hash' => 'N',
'ip_addr' => ip_addr,
'stored_hash' => session_hash)
end
end
def self.delete_by_hash(hash)
find_by_stored_hash(hash).try :destroy
end
def self.session_hash
(0...32).map{ ('a'..'z').to_a[rand(26)] }.join
end
end
#
# разработчик - Дмитрий Максимов http://www.dmaximov.net/
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment