Ruby/LDAP

LDAP の情報を読み書きする Web アプリを作ろうと思って Ruby/LDAP を触ってみた。


プログラムの動作

  • POST でパラメータ {user,shell,passwd} を受け取る
  • LDAP で user の loginShell を変更する
  • 成功したら "success" と表示、失敗ならエラーメッセージを表示する

WEBrick::CGIRuby/LDAP のサンプルコードくらいには
なりそうなのでとりあえず置いておきます。

#!/usr/bin/ruby

require "webrick/cgi"
require "ldap"

class LdapCGI < WEBrick::CGI

  def chsh (user,shell,passwd)
    conn = LDAP::Conn.new('ldapserver',LDAP::LDAP_PORT)
    conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION,3)
    begin
      conn.bind("uid=#{user},ou=People,dc=lab",passwd) {
        mods = {"loginShell"=>[shell]}
        dn = "uid=#{user},ou=People,dc=lab"
        conn.modify(dn,mods)
      }
      "success"
    rescue LDAP::ResultError
      errcode = conn.err
      conn.err2string(errcode)
    ensure
      #conn.unbind()
    end
  end

  def do_POST(req, res)
    res["content-type"] = "text/html; charset=EUC-JP"
    res.body = chsh(req.query["user"], req.query["shell"], req.query["passwd"])
  end

end

#$SAFE = 1
LdapCGI.new.start


ちなみに Web アプリを作る話は、作ってる途中に
phpLDAPadmin を見つけたので無かったことになりました。

Ruby/ActiveLdap を使えば Rails で簡単にできるのかも。