vkill'blog

“技术本身没有太多价值,掌握了新的思考方式才是真的收获”

ruby 写的 squid 用户验证辅助器

23:25 , vkill
因在win上工作,基于mysql的已有的验证辅助器好像不适合win,linux可以使用pam或mysql_auth,所以就自己写了个
具体的api看这篇文章http://www.squid-cache.net.cn/book/chap12.html
自己写验证辅助器的重点就在于定义 $stdout 不能缓存,就为这个,折腾了我一个晚上
还有,现在的脚本是自动判断是 基本验证 还是 摘要式验证 的,所以数据库中密码必须是明文

代码:


#!/usr/bin/ruby
# squid_auth.rb 2010.04.10 by:vkill
# squid 3.0
# squid auth_param use, auto select auth type
# eg:
#auth_param basic program d:/language/ruby/bin/ruby.exe D:/httpd/squid/libexec/squid_auth.rb
#auth_param basic children 4
#auth_param basic realm welcome to upd.avira.net.cn
#or
#auth_param digest program d:/language/ruby/bin/ruby.exe D:/httpd/squid/libexec/squid_auth.rb
#auth_param digest children 4
#auth_param digest realm welcome to upd.avira.net.cn

require "rubygems"
require "active_record"
require "digest/md5"
require 'uri'

def md5(hex)
  Digest::MD5.hexdigest(hex)
end
def uri_decode(uri)
  return if !uri
  URI.decode(uri.gsub(/[\t\r\n]/,""))
end

#conn mysql server
class User < ActiveRecord::Base
  establish_connection(
    :adapter => "mysql",
    :host => "127.0.0.1",
    :username => "root",
    :password => "1234567",
    :database => "webuser"
  )
  set_table_name "users"
  #has_one :info
end
#Users表中须包含有 username 和 passwd 列,且 passwd 须是明文
def query_passwd(username)
  u = User.find(:first, :conditions => [ "username=:u", {:u => username}])
  u ? u.passwd : nil
end

i = 0
while i < 1000
  i += 1
  $stdout.flush
  str = $stdin.gets
  case str
    when nil
      next
    when /^([^ \"]+?) ([^ \"]+?)$/
      #Basic Authentication   "username password"
      username = uri_decode($1)
      password = uri_decode($2)
      if passwd_t = query_passwd(username)
        puts password == passwd_t ? "OK" : "ERR passwd error"
      else
        puts "ERR undefined username"
      end
    when /\"([^\"]+?)\":\"([^\"]+?)\"/
      #Digest Access Authentication   "username":"realm"
      username = $1
      realm = $2
      if passwd_t = query_passwd(username)
        hex = username.concat(":").concat(realm).concat(":").concat(passwd_t)
        puts md5(hex)
      else
        puts "ERR undefined username"
      end
    else
      puts "ERR unknow auth type"
  end
end

Last modified by vkill on2010/04/21 23:20
类别:ruby & rails | Tags: , , , , , , , | 0 条评论, 891 次阅读
网友评论(0):
发表评论:

Nickname: 
Email:
Site URI: