ed-auth.rb 1.92 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Simple ED-Auth library; requires ruby-ldap built
# against OpenLDAP and OpenSSL.
# Sam Stephenson <sams@vt.edu> 2004-06-17
# Modified a bit by Brad Tilley < rtilley@vt.edu> 2006-12-13

require 'ldap'

class NotAuthenticatedError < Exception
end

class EdAuth
    HOST, PORT = 'authn.directory.vt.edu', 389
    DN, FILTER = 'ou=People,dc=vt,dc=edu', '(uupid=%s)'

    def initialize(pid, pass)
        @ldap = LDAP::SSLConn.new(HOST, PORT, true)
        @authenticated = false
        @pid, @pass = pid, pass
        @dn, @filter = DN, format(FILTER, pid)

        @authenticity = false
        @pri_affil, @affil = nil, nil
    end

    def authenticate
        return @authenticity if @authenticated
        begin
            @ldap.search(@dn, LDAP::LDAP_SCOPE_ONELEVEL,
                        @filter) {|c| @dn = c.get_dn}
            @ldap.bind(@dn, @pass)
            @authenticity = true
        rescue LDAP::ResultError
            @authenticity = false
        ensure
            @authenticated = true
        end
        @authenticity
    end

    def get_primary_affiliation
        query if @pri_affil.nil?
    puts @pri_affil
        @pri_affil
    end

    def get_affiliations
        query if @affil.nil?
    puts @affil
        @affil
    end

    def close
        begin
            @ldap.unbind
        rescue LDAP::InvalidDataError
        end
    end

    private
    def query
        raise NotAuthenticatedError unless @authenticated and
        @authenticity
        @ldap.search(@dn, LDAP::LDAP_SCOPE_SUBTREE, @filter,
                    ['eduPersonPrimaryAffiliation',
                    'eduPersonAffiliation']) do |entry|
                    @pri_affil =
                    entry.get_values('edupersonprimaryaffiliation').shift
                    @affil = entry.get_values('edupersonaffiliation')
        end
    end
end

x = EdAuth.new('your_pid', 'your_password')
x.authenticate
x.get_primary_affiliation
x.get_affiliations
x.close