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