clone from ldap_login_for_asia

This commit is contained in:
邱博亞 2022-01-24 12:41:39 +08:00
parent 9c0ee4a4cd
commit 98a95218f7
1 changed files with 28 additions and 50 deletions

View File

@ -1,63 +1,41 @@
module LdapLogin::Login
require 'net/ldap'
LDAP_ADSERVER=["ad.asia.edu.tw","ad2.asia.edu.tw","ad3.asia.edu.tw"]
LDAP_ADSERVER="https://ap99.mdu.edu.tw/MduDB/api/Auth/token/1"
AppKey = "YhoRop0YmL6"
def ldap_login_auth(user,request,session,flash,params)
ldap_hosts = LDAP_ADSERVER.shuffle
error = ''
ldap_user = params[:user_name]
ldap_pass = params[:password]
login_flag = false
_session = {'ad' => []}
url = '/'
url_method = 'redirect_to'
ldap_hosts.each do |ldap_host|
begin
ldap = Net::LDAP.new
ldap.host = ldap_host
ldap.port = 389
ldap.auth "#{ldap_user}@asia.edu.tw", ldap_pass
if ldap.bind
if !user.nil?
#filter = Net::LDAP::Filter.eq( "sAMAccountName", ldap_user )
#treebase = "ou=Asia Univ,dc=asia,dc=edu,dc=tws"
#puts "==LDAP SEARCH START=="
#ldap.search( :base => treebase, :filter => filter, :return_result => false ) do |entry|
# puts "DN: #{entry.dn}"
# entry.each do |attribute, values|
# puts " #{attribute}:"
# values.each do |value|
# puts " --->#{value}"
# end
# end
#end
puts "==LDAP SEARCH END=="
session[:user_id] = user.id
session[:login_referer] = nil
if params[:referer_url]
url = URI.parse(params[:referer_url]).path
url_method = 'redirect_to'
else
url = admin_dashboards_path
url_method = 'redirect_to'
end
login_flag = true
else
error = I18n.t('devise.failure.ldap_pass_but_account_not_in_orbit')
end
else
error = '驗證失敗,您輸入的使用者名稱或密碼不正確!'
end
break
rescue => e
if !e.class==Net::LDAP::ConnectionError
error = '發生不可預知的錯誤'
puts ['ldap',error,e]
break
else
error = 'Could not connect to AD server.'
end
end
uri = URI(LDAP_ADSERVER)
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = {AppKey: AppKey,username: ldap_user,password: ldap_pass}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
if res.code == '200' && JSON.load(res.body)["userID"]==ldap_user
if !user.nil?
session[:user_id] = ldap_user
session[:login_referer] = nil
if params[:referer_url]
url = URI.parse(params[:referer_url]).path
url_method = 'redirect_to'
else
url = admin_dashboards_path
url_method = 'redirect_to'
end
login_flag = true
else
error = I18n.t('devise.failure.ldap_pass_but_account_not_in_orbit')
end
else
error = '驗證失敗,您輸入的使用者名稱或密碼不正確!'
end
if !login_flag
flash.now.alert = error.html_safe
url = 'new'