]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/botuser.rb
first_html_par: only initialize element collections once
[user/henk/code/ruby/rbot.git] / lib / rbot / botuser.rb
1 #-- vim:sw=2:et\r
2 #++\r
3 # :title: User management\r
4 #\r
5 # rbot user management\r
6 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)\r
7 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta\r
8 # License:: GPLv2\r
9 \r
10 require 'singleton'\r
11 require 'set'\r
12 \r
13 # This would be a good idea if it was failproof, but the truth\r
14 # is that other methods can indirectly modify the hash. *sigh*\r
15 #\r
16 # class AuthNotifyingHash < Hash\r
17 #   %w(clear default= delete delete_if replace invert\r
18 #      merge! update rehash reject! replace shift []= store).each { |m|\r
19 #     class_eval {\r
20 #       define_method(m) { |*a|\r
21 #         r = super(*a)\r
22 #         Irc::Auth.authmanager.set_changed\r
23 #         r\r
24 #       }\r
25 #     }\r
26 #   }\r
27 # end\r
28\r
29 \r
30 module Irc\r
31 \r
32 \r
33   # This module contains the actual Authentication stuff\r
34   #\r
35   module Auth\r
36 \r
37     BotConfig.register BotConfigStringValue.new( 'auth.password',\r
38       :default => 'rbotauth', :wizard => true,\r
39       :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},\r
40       :desc => _('Password for the bot owner'))\r
41     BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',\r
42       :default => 'true',\r
43       :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))\r
44     BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',\r
45       :default => 'true',\r
46       :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))\r
47     BotConfig.register BotConfigBooleanValue.new( 'auth.autouser',\r
48       :default => 'false',\r
49       :desc => _('Set true to allow new botusers to be created automatically'))\r
50     # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',\r
51     #   :default => 10, :wizard => true,\r
52     #   :desc => 'The default level for new/unknown users' )\r
53 \r
54     # Generate a random password of length _l_\r
55     #\r
56     def Auth.random_password(l=8)\r
57       pwd = ""\r
58       l.times do\r
59         pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr\r
60       end\r
61       return pwd\r
62     end\r
63 \r
64 \r
65     # An Irc::Auth::Command defines a command by its "path":\r
66     #\r
67     #   base::command::subcommand::subsubcommand::subsubsubcommand\r
68     #\r
69     class Command\r
70 \r
71       attr_reader :command, :path\r
72 \r
73       # A method that checks if a given _cmd_ is in a form that can be\r
74       # reduced into a canonical command path, and if so, returns it\r
75       #\r
76       def sanitize_command_path(cmd)\r
77         pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")\r
78         return pre if pre.empty?\r
79         return pre if pre =~ /^\S+(::\S+)*$/\r
80         raise TypeError, "#{cmd.inspect} is not a valid command"\r
81       end\r
82 \r
83       # Creates a new Command from a given string; you can then access\r
84       # the command as a symbol with the :command method and the whole\r
85       # path as :path\r
86       #\r
87       #   Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]\r
88       #\r
89       #   Command.new("core::auth::save").command => :"core::auth::save"\r
90       #\r
91       def initialize(cmd)\r
92         cmdpath = sanitize_command_path(cmd).split('::')\r
93         seq = cmdpath.inject(["*"]) { |list, cmd|\r
94           list << (list.length > 1 ? list.last + "::" : "") + cmd\r
95         }\r
96         @path = seq.map { |k|\r
97           k.to_sym\r
98         }\r
99         @command = path.last\r
100         debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"\r
101       end\r
102 \r
103       # Returs self\r
104       def to_irc_auth_command\r
105         self\r
106       end\r
107 \r
108     end\r
109 \r
110   end\r
111 \r
112 end\r
113 \r
114 \r
115 class String\r
116 \r
117   # Returns an Irc::Auth::Comand from the receiver\r
118   def to_irc_auth_command\r
119     Irc::Auth::Command.new(self)\r
120   end\r
121 \r
122 end\r
123 \r
124 \r
125 class Symbol\r
126 \r
127   # Returns an Irc::Auth::Comand from the receiver\r
128   def to_irc_auth_command\r
129     Irc::Auth::Command.new(self)\r
130   end\r
131 \r
132 end\r
133 \r
134 \r
135 module Irc\r
136 \r
137 \r
138   module Auth\r
139 \r
140 \r
141     # This class describes a permission set\r
142     class PermissionSet\r
143 \r
144       attr_reader :perm\r
145       # Create a new (empty) PermissionSet\r
146       #\r
147       def initialize\r
148         @perm = {}\r
149       end\r
150 \r
151       # Inspection simply inspects the internal hash\r
152       def inspect\r
153         @perm.inspect\r
154       end\r
155 \r
156       # Sets the permission for command _cmd_ to _val_,\r
157       #\r
158       def set_permission(str, val)\r
159         cmd = str.to_irc_auth_command\r
160         case val\r
161         when true, false\r
162           @perm[cmd.command] = val\r
163         when nil\r
164           @perm.delete(cmd.command)\r
165         else\r
166           raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)\r
167         end\r
168       end\r
169 \r
170       # Resets the permission for command _cmd_\r
171       #\r
172       def reset_permission(cmd)\r
173         set_permission(cmd, nil)\r
174       end\r
175 \r
176       # Tells if command _cmd_ is permitted. We do this by returning\r
177       # the value of the deepest Command#path that matches.\r
178       #\r
179       def permit?(str)\r
180         cmd = str.to_irc_auth_command\r
181         allow = nil\r
182         cmd.path.reverse.each { |k|\r
183           if @perm.has_key?(k)\r
184             allow = @perm[k]\r
185             break\r
186           end\r
187         }\r
188         return allow\r
189       end\r
190 \r
191     end\r
192 \r
193 \r
194     # This is the error that gets raised when an invalid password is met\r
195     #\r
196     class InvalidPassword < RuntimeError\r
197     end\r
198 \r
199 \r
200     # This is the basic class for bot users: they have a username, a\r
201     # password, a list of netmasks to match against, and a list of\r
202     # permissions. A BotUser can be marked as 'transient', usually meaning\r
203     # it's not intended for permanent storage. Transient BotUsers have lower\r
204     # priority than nontransient ones for autologin purposes.\r
205     #\r
206     # To initialize a BotUser, you pass a _username_ and an optional\r
207     # hash of options. Currently, only two options are recognized:\r
208     #\r
209     # transient:: true or false, determines if the BotUser is transient or\r
210     #             permanent (default is false, permanent BotUser).\r
211     #\r
212     #             Transient BotUsers are initialized by prepending an\r
213     #             asterisk (*) to the username, and appending a sanitized\r
214     #             version of the object_id. The username can be empty.\r
215     #             A random password is generated.\r
216     #\r
217     #             Permanent Botusers need the username as is, and no\r
218     #             password is generated.\r
219     #\r
220     # masks::     an array of Netmasks to initialize the NetmaskList. This\r
221     #             list is used as-is for permanent BotUsers.\r
222     #\r
223     #             Transient BotUsers will alter the list elements which are\r
224     #             Irc::User by globbing the nick and any initial nonletter\r
225     #             part of the ident.\r
226     #\r
227     #             The masks option is optional for permanent BotUsers, but\r
228     #             obligatory (non-empty) for transients.\r
229     #\r
230     class BotUser\r
231 \r
232       attr_reader :username\r
233       attr_reader :password\r
234       attr_reader :netmasks\r
235       attr_reader :perm\r
236       # Please remember to #set_changed() the authmanager\r
237       # when modifying data\r
238       attr_reader :data\r
239       attr_writer :login_by_mask\r
240       attr_writer :autologin\r
241       attr_writer :transient\r
242 \r
243       # Checks if the BotUser is transient\r
244       def transient?\r
245         @transient\r
246       end\r
247 \r
248       # Checks if the BotUser is permanent (not transient)\r
249       def permanent?\r
250         !@permanent\r
251       end\r
252 \r
253       # Sets if the BotUser is permanent or not\r
254       def permanent=(bool)\r
255         @transient=!bool\r
256       end\r
257 \r
258       # Create a new BotUser with given username\r
259       def initialize(username, options={})\r
260         opts = {:transient => false}.merge(options)\r
261         @transient = opts[:transient]\r
262 \r
263         if @transient\r
264           @username = "*"\r
265           @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?\r
266           @username << BotUser.sanitize_username(object_id)\r
267           reset_password\r
268           @login_by_mask=true\r
269           @autologin=true\r
270         else\r
271           @username = BotUser.sanitize_username(username)\r
272           @password = nil\r
273           reset_login_by_mask\r
274           reset_autologin\r
275         end\r
276 \r
277         @netmasks = NetmaskList.new\r
278         if opts.key?(:masks) and opts[:masks]\r
279           masks = opts[:masks]\r
280           masks = [masks] unless masks.respond_to?(:each)\r
281           masks.each { |m|\r
282             mask = m.to_irc_netmask\r
283             if @transient and User === m\r
284               mask.nick = "*"\r
285               mask.host = m.host.dup\r
286               mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')\r
287             end\r
288             add_netmask(mask) unless mask.to_s == "*"\r
289           }\r
290         end\r
291         raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?\r
292 \r
293         @perm = {}\r
294 \r
295         # @data = AuthNotifyingHash.new\r
296         @data = {}\r
297       end\r
298 \r
299       # Inspection\r
300       def inspect\r
301         str = "<#{self.class}:#{'0x%08x' % self.object_id}"\r
302         str << " (transient)" if @transient\r
303         str << ":"\r
304         str << " @username=#{@username.inspect}"\r
305         str << " @netmasks=#{@netmasks.inspect}"\r
306         str << " @perm=#{@perm.inspect}"\r
307         str << " @login_by_mask=#{@login_by_mask}"\r
308         str << " @autologin=#{@autologin}"\r
309         if @data.empty?\r
310           str << " no data"\r
311         else\r
312           str << " data for #{@data.keys.join(', ')}"\r
313         end\r
314         str << ">"\r
315       end\r
316 \r
317       # In strings\r
318       def to_s\r
319         @username\r
320       end\r
321 \r
322       # Convert into a hash\r
323       def to_hash\r
324         {\r
325           :username => @username,\r
326           :password => @password,\r
327           :netmasks => @netmasks,\r
328           :perm => @perm,\r
329           :login_by_mask => @login_by_mask,\r
330           :autologin => @autologin,\r
331           :data => @data\r
332         }\r
333       end\r
334 \r
335       # Do we allow logging in without providing the password?\r
336       #\r
337       def login_by_mask?\r
338         @login_by_mask\r
339       end\r
340 \r
341       # Reset the login-by-mask option\r
342       #\r
343       def reset_login_by_mask\r
344         @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)\r
345       end\r
346 \r
347       # Reset the autologin option\r
348       #\r
349       def reset_autologin\r
350         @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)\r
351       end\r
352 \r
353       # Do we allow automatic logging in?\r
354       #\r
355       def autologin?\r
356         @autologin\r
357       end\r
358 \r
359       # Restore from hash\r
360       def from_hash(h)\r
361         @username = h[:username] if h.has_key?(:username)\r
362         @password = h[:password] if h.has_key?(:password)\r
363         @netmasks = h[:netmasks] if h.has_key?(:netmasks)\r
364         @perm = h[:perm] if h.has_key?(:perm)\r
365         @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)\r
366         @autologin = h[:autologin] if h.has_key?(:autologin)\r
367         @data.replace(h[:data]) if h.has_key?(:data)\r
368       end\r
369 \r
370       # This method sets the password if the proposed new password\r
371       # is valid\r
372       def password=(pwd=nil)\r
373         pass = pwd.to_s\r
374         if pass.empty?\r
375           reset_password\r
376         else\r
377           begin\r
378             raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/\r
379             raise InvalidPassword, "#{pass} too short" if pass.length < 4\r
380             @password = pass\r
381           rescue InvalidPassword => e\r
382             raise e\r
383           rescue => e\r
384             raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"\r
385           end\r
386         end\r
387       end\r
388 \r
389       # Resets the password by creating a new onw\r
390       def reset_password\r
391         @password = Auth.random_password\r
392       end\r
393 \r
394       # Sets the permission for command _cmd_ to _val_ on channel _chan_\r
395       #\r
396       def set_permission(cmd, val, chan="*")\r
397         k = chan.to_s.to_sym\r
398         @perm[k] = PermissionSet.new unless @perm.has_key?(k)\r
399         @perm[k].set_permission(cmd, val)\r
400       end\r
401 \r
402       # Resets the permission for command _cmd_ on channel _chan_\r
403       #\r
404       def reset_permission(cmd, chan ="*")\r
405         set_permission(cmd, nil, chan)\r
406       end\r
407 \r
408       # Checks if BotUser is allowed to do something on channel _chan_,\r
409       # or on all channels if _chan_ is nil\r
410       #\r
411       def permit?(cmd, chan=nil)\r
412         if chan\r
413           k = chan.to_s.to_sym\r
414         else\r
415           k = :*\r
416         end\r
417         allow = nil\r
418         if @perm.has_key?(k)\r
419           allow = @perm[k].permit?(cmd)\r
420         end\r
421         return allow\r
422       end\r
423 \r
424       # Adds a Netmask\r
425       #\r
426       def add_netmask(mask)\r
427         @netmasks << mask.to_irc_netmask\r
428       end\r
429 \r
430       # Removes a Netmask\r
431       #\r
432       def delete_netmask(mask)\r
433         m = mask.to_irc_netmask\r
434         @netmasks.delete(m)\r
435       end\r
436 \r
437       # Removes all <code>Netmask</code>s\r
438       #\r
439       def reset_netmasks\r
440         @netmasks = NetmaskList.new\r
441       end\r
442 \r
443       # This method checks if BotUser has a Netmask that matches _user_\r
444       #\r
445       def knows?(usr)\r
446         user = usr.to_irc_user\r
447         known = false\r
448         @netmasks.each { |n|\r
449           if user.matches?(n)\r
450             known = true\r
451             break\r
452           end\r
453         }\r
454         return known\r
455       end\r
456 \r
457       # This method gets called when User _user_ wants to log in.\r
458       # It returns true or false depending on whether the password\r
459       # is right. If it is, the Netmask of the user is added to the\r
460       # list of acceptable Netmask unless it's already matched.\r
461       def login(user, password=nil)\r
462         if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))\r
463           add_netmask(user) unless knows?(user)\r
464           debug "#{user} logged in as #{self.inspect}"\r
465           return true\r
466         else\r
467           return false\r
468         end\r
469       end\r
470 \r
471       # # This method gets called when User _user_ has logged out as this BotUser\r
472       # def logout(user)\r
473       #   delete_netmask(user) if knows?(user)\r
474       # end\r
475 \r
476       # This method sanitizes a username by chomping, downcasing\r
477       # and replacing any nonalphanumeric character with _\r
478       #\r
479       def BotUser.sanitize_username(name)\r
480         candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")\r
481         raise "sanitized botusername #{candidate} too short" if candidate.length < 3\r
482         return candidate\r
483       end\r
484 \r
485     end\r
486 \r
487     # This is the default BotUser: it's used for all users which haven't\r
488     # identified with the bot\r
489     #\r
490     class DefaultBotUserClass < BotUser\r
491 \r
492       private :add_netmask, :delete_netmask\r
493 \r
494       include Singleton\r
495 \r
496       # The default BotUser is named 'everyone'\r
497       #\r
498       def initialize\r
499         reset_login_by_mask\r
500         reset_autologin\r
501         super("everyone")\r
502         @default_perm = PermissionSet.new\r
503       end\r
504 \r
505       # This method returns without changing anything\r
506       #\r
507       def login_by_mask=(val)\r
508         debug "Tried to change the login-by-mask for default bot user, ignoring"\r
509         return @login_by_mask\r
510       end\r
511 \r
512       # The default botuser allows logins by mask\r
513       #\r
514       def reset_login_by_mask\r
515         @login_by_mask = true\r
516       end\r
517 \r
518       # This method returns without changing anything\r
519       #\r
520       def autologin=(val)\r
521         debug "Tried to change the autologin for default bot user, ignoring"\r
522         return\r
523       end\r
524 \r
525       # The default botuser doesn't allow autologin (meaningless)\r
526       #\r
527       def reset_autologin\r
528         @autologin = false\r
529       end\r
530 \r
531       # Sets the default permission for the default user (i.e. the ones\r
532       # set by the BotModule writers) on all channels\r
533       #\r
534       def set_default_permission(cmd, val)\r
535         @default_perm.set_permission(Command.new(cmd), val)\r
536         debug "Default permissions now: #{@default_perm.pretty_inspect}"\r
537       end\r
538 \r
539       # default knows everybody\r
540       #\r
541       def knows?(user)\r
542         return true if user.to_irc_user\r
543       end\r
544 \r
545       # We always allow logging in as the default user\r
546       def login(user, password)\r
547         return true\r
548       end\r
549 \r
550       # Resets the NetmaskList\r
551       def reset_netmasks\r
552         super\r
553         add_netmask("*!*@*")\r
554       end\r
555 \r
556       # DefaultBotUser will check the default_perm after checking\r
557       # the global ones\r
558       # or on all channels if _chan_ is nil\r
559       #\r
560       def permit?(cmd, chan=nil)\r
561         allow = super(cmd, chan)\r
562         if allow.nil? && chan.nil?\r
563           allow = @default_perm.permit?(cmd)\r
564         end\r
565         return allow\r
566       end\r
567 \r
568     end\r
569 \r
570     # Returns the only instance of DefaultBotUserClass\r
571     #\r
572     def Auth.defaultbotuser\r
573       return DefaultBotUserClass.instance\r
574     end\r
575 \r
576     # This is the BotOwner: he can do everything\r
577     #\r
578     class BotOwnerClass < BotUser\r
579 \r
580       include Singleton\r
581 \r
582       def initialize\r
583         @login_by_mask = false\r
584         @autologin = true\r
585         super("owner")\r
586       end\r
587 \r
588       def permit?(cmd, chan=nil)\r
589         return true\r
590       end\r
591 \r
592     end\r
593 \r
594     # Returns the only instance of BotOwnerClass\r
595     #\r
596     def Auth.botowner\r
597       return BotOwnerClass.instance\r
598     end\r
599 \r
600 \r
601     # This is the AuthManagerClass singleton, used to manage User/BotUser connections and\r
602     # everything\r
603     #\r
604     class AuthManagerClass\r
605 \r
606       include Singleton\r
607 \r
608       attr_reader :everyone\r
609       attr_reader :botowner\r
610       attr_reader :bot\r
611 \r
612       # The instance manages two <code>Hash</code>es: one that maps\r
613       # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps\r
614       # usernames onto <code>BotUser</code>\r
615       def initialize\r
616         @everyone = Auth::defaultbotuser\r
617         @botowner = Auth::botowner\r
618         bot_associate(nil)\r
619       end\r
620 \r
621       def bot_associate(bot)\r
622         raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes\r
623 \r
624         reset_hashes\r
625 \r
626         # Associated bot\r
627         @bot = bot\r
628 \r
629         # This variable is set to true when there have been changes\r
630         # to the botusers list, so that we know when to save\r
631         @has_changes = false\r
632       end\r
633 \r
634       def set_changed\r
635         @has_changes = true\r
636       end\r
637 \r
638       def reset_changed\r
639         @has_changes = false\r
640       end\r
641 \r
642       def changed?\r
643         @has_changes\r
644       end\r
645 \r
646       # resets the hashes\r
647       def reset_hashes\r
648         @botusers = Hash.new\r
649         @allbotusers = Hash.new\r
650         [everyone, botowner].each { |x|\r
651           @allbotusers[x.username.to_sym] = x\r
652         }\r
653         @transients = Set.new\r
654       end\r
655 \r
656       def load_array(ary, forced)\r
657         unless ary\r
658           warning "Tried to load an empty array"\r
659           return\r
660         end\r
661         raise "Won't load with unsaved changes" if @has_changes and not forced\r
662         reset_hashes\r
663         ary.each { |x|\r
664           raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)\r
665           u = x[:username]\r
666           unless include?(u)\r
667             create_botuser(u)\r
668           end\r
669           get_botuser(u).from_hash(x)\r
670           get_botuser(u).transient = false\r
671         }\r
672         @has_changes=false\r
673       end\r
674 \r
675       def save_array\r
676         @allbotusers.values.map { |x|\r
677           x.transient? ? nil : x.to_hash\r
678         }.compact\r
679       end\r
680 \r
681       # checks if we know about a certain BotUser username\r
682       def include?(botusername)\r
683         @allbotusers.has_key?(botusername.to_sym)\r
684       end\r
685 \r
686       # Maps <code>Irc::User</code> to BotUser\r
687       def irc_to_botuser(ircuser)\r
688         logged = @botusers[ircuser.to_irc_user]\r
689         return logged if logged\r
690         return autologin(ircuser)\r
691       end\r
692 \r
693       # creates a new BotUser\r
694       def create_botuser(name, password=nil)\r
695         n = BotUser.sanitize_username(name)\r
696         k = n.to_sym\r
697         raise "botuser #{n} exists" if include?(k)\r
698         bu = BotUser.new(n)\r
699         bu.password = password\r
700         @allbotusers[k] = bu\r
701         return bu\r
702       end\r
703 \r
704       # returns the botuser with name _name_\r
705       def get_botuser(name)\r
706         @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)\r
707       end\r
708 \r
709       # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_\r
710       #\r
711       # raises an error if _botusername_ is not a known BotUser username\r
712       #\r
713       # It is possible to autologin by Netmask, on request\r
714       #\r
715       def login(user, botusername, pwd=nil)\r
716         ircuser = user.to_irc_user\r
717         n = BotUser.sanitize_username(botusername)\r
718         k = n.to_sym\r
719         raise "No such BotUser #{n}" unless include?(k)\r
720         if @botusers.has_key?(ircuser)\r
721           return true if @botusers[ircuser].username == n\r
722           # TODO\r
723           # @botusers[ircuser].logout(ircuser)\r
724         end\r
725         bu = @allbotusers[k]\r
726         if bu.login(ircuser, pwd)\r
727           @botusers[ircuser] = bu\r
728           return true\r
729         end\r
730         return false\r
731       end\r
732 \r
733       # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin\r
734       # and trying to login without a password\r
735       #\r
736       def autologin(user)\r
737         ircuser = user.to_irc_user\r
738         debug "Trying to autologin #{ircuser}"\r
739         return @botusers[ircuser] if @botusers.has_key?(ircuser)\r
740         @allbotusers.each { |n, bu|\r
741           debug "Checking with #{n}"\r
742           return bu if bu.autologin? and login(ircuser, n)\r
743         }\r
744         # Check with transient users\r
745         @transients.each { |bu|\r
746           return bu if bu.login(ircuser)\r
747         }\r
748         # Finally, create a transient if we're set to allow it\r
749         if @bot.config['auth.autouser']\r
750           bu = create_transient_botuser(ircuser)\r
751           return bu\r
752         end\r
753         return everyone\r
754       end\r
755 \r
756       # Creates a new transient BotUser associated with Irc::User _user_,\r
757       # automatically logging him in\r
758       #\r
759       def create_transient_botuser(user)\r
760         ircuser = user.to_irc_user\r
761         bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)\r
762         bu.login(ircuser)\r
763         @transients << bu\r
764         return bu\r
765       end\r
766 \r
767       # Checks if User _user_ can do _cmd_ on _chan_.\r
768       #\r
769       # Permission are checked in this order, until a true or false\r
770       # is returned:\r
771       # * associated BotUser on _chan_\r
772       # * associated BotUser on all channels\r
773       # * everyone on _chan_\r
774       # * everyone on all channels\r
775       #\r
776       def permit?(user, cmdtxt, channel=nil)\r
777         if user.class <= BotUser\r
778           botuser = user\r
779         else\r
780           botuser = irc_to_botuser(user)\r
781         end\r
782         cmd = cmdtxt.to_irc_auth_command\r
783 \r
784         chan = channel\r
785         case chan\r
786         when User\r
787           chan = "?"\r
788         when Channel\r
789           chan = chan.name\r
790         end\r
791 \r
792         allow = nil\r
793 \r
794         allow = botuser.permit?(cmd, chan) if chan\r
795         return allow unless allow.nil?\r
796         allow = botuser.permit?(cmd)\r
797         return allow unless allow.nil?\r
798 \r
799         unless botuser == everyone\r
800           allow = everyone.permit?(cmd, chan) if chan\r
801           return allow unless allow.nil?\r
802           allow = everyone.permit?(cmd)\r
803           return allow unless allow.nil?\r
804         end\r
805 \r
806         raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"\r
807       end\r
808 \r
809       # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally\r
810       # telling if the user is authorized\r
811       #\r
812       def allow?(cmdtxt, user, chan=nil)\r
813         if permit?(user, cmdtxt, chan)\r
814           return true\r
815         else\r
816           # cmds = cmdtxt.split('::')\r
817           # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan\r
818           @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %\r
819                         {:user=>user, :command=>cmdtxt} if chan\r
820           return false\r
821         end\r
822       end\r
823 \r
824     end\r
825 \r
826     # Returns the only instance of AuthManagerClass\r
827     #\r
828     def Auth.authmanager\r
829       return AuthManagerClass.instance\r
830     end\r
831 \r
832   end\r
833 \r
834   class User\r
835 \r
836     # A convenience method to automatically found the botuser\r
837     # associated with the receiver\r
838     #\r
839     def botuser\r
840       Irc::Auth.authmanager.irc_to_botuser(self)\r
841     end\r
842 \r
843     # Bot-specific data can be stored with Irc::Users. This is\r
844     # internally obtained by storing data to the associated BotUser,\r
845     # but this is a detail plugin writers shouldn't care about.\r
846     # bot_data(:key) can be used to retrieve a particular data set.\r
847     # This method is intended for data retrieval, and if the retrieved\r
848     # data is modified directly there is no guarantee the changes will\r
849     # be saved back. Use #set_bot_data() for that.\r
850     #\r
851     def bot_data(key=nil)\r
852       return self.botuser.data if key.nil?\r
853       return self.botuser.data[key]\r
854     end\r
855 \r
856     # This method is used to store bot-specific data for the receiver.\r
857     # If no block is passed, _value_ is stored for the key _key_;\r
858     # if a block is passed, it will be called with the previous\r
859     # _key_ value as parameter, and its return value will be stored\r
860     # as the new value. If _value_ is present in the block form, it\r
861     # will be used to initialize _key_ if it's missing\r
862     # \r
863     def set_bot_data(key,value=nil,&block)\r
864       if not block_given?\r
865         self.botuser.data[key]=value\r
866         Irc::Auth.authmanager.set_changed\r
867         return value\r
868       end\r
869       if value and not bot_data.has_key?(key)\r
870         set_bot_data(key, value)\r
871       end\r
872       r = value\r
873       begin\r
874         r = yield bot_data(key)\r
875       ensure\r
876         Irc::Auth.authmanager.set_changed\r
877       end\r
878       return r\r
879     end\r
880   end\r
881 \r
882 end\r