beast rev 2066
[beast-modified.git] / vendor / plugins / open_id_authentication / lib / open_id_authentication / db_store.rb
blob3500a228f355d8669b975e749fceb79670917797
1 module OpenIdAuthentication
2   class DbStore < OpenID::Store
3     def self.gc
4       now = Time.now.to_i
6       # remove old nonces
7       nonces = Nonce.find(:all)
8       nonces.each {|n| n.destroy if now - n.created > 6.hours} unless nonces.nil?
9     
10       # remove expired assocs
11       assocs = Association.find(:all)
12       assocs.each { |a| a.destroy if a.from_record.expired? } unless assocs.nil?
13     end
16     def get_auth_key
17       unless setting = Setting.find_by_setting('auth_key')
18         auth_key = OpenID::Util.random_string(20)
19         setting  = Setting.create(:setting => 'auth_key', :value => auth_key)
20       end
22       setting.value
23     end
25     def store_association(server_url, assoc)
26       remove_association(server_url, assoc.handle)    
27       Association.create(:server_url => server_url,
28                          :handle     => assoc.handle,
29                          :secret     => assoc.secret,
30                          :issued     => assoc.issued,
31                          :lifetime   => assoc.lifetime,
32                          :assoc_type => assoc.assoc_type)
33     end
35     def get_association(server_url, handle=nil)
36       assocs = handle.blank? ? 
37         Association.find_all_by_server_url(server_url) :
38           Association.find_all_by_server_url_and_handle(server_url, handle)
39     
40       assocs.reverse.each do |assoc|
41         a = assoc.from_record    
42         if a.expired?
43           assoc.destroy
44         else
45           return a
46         end
47       end if assocs.any?
48     
49       return nil
50     end
51   
52     def remove_association(server_url, handle)
53       assoc = Association.find_by_server_url_and_handle(server_url, handle)
54       unless assoc.nil?
55         assoc.destroy
56         return true
57       end
58       false
59     end
60   
61     def store_nonce(nonce)
62       use_nonce(nonce)
63       Nonce.create :nonce => nonce, :created => Time.now.to_i
64     end
65   
66     def use_nonce(nonce)
67       nonce = Nonce.find_by_nonce(nonce)
68       return false if nonce.nil?
69     
70       age = Time.now.to_i - nonce.created
71       nonce.destroy
73       age < 6.hours # max nonce age of 6 hours
74     end
75   
76     def dumb?
77       false
78     end
79   end
80 end