]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/botuser.rb
botuser: add command to reset the netmasks list
[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         # TODO user-configurable list of always-allowed commands,\r
186         # for admins that want to set permissions -* for everybody\r
187         return true if cmd.command == :login\r
188         allow = nil\r
189         cmd.path.reverse.each { |k|\r
190           if @perm.has_key?(k)\r
191             allow = @perm[k]\r
192             break\r
193           end\r
194         }\r
195         return allow\r
196       end\r
197 \r
198     end\r
199 \r
200 \r
201     # This is the error that gets raised when an invalid password is met\r
202     #\r
203     class InvalidPassword < RuntimeError\r
204     end\r
205 \r
206 \r
207     # This is the basic class for bot users: they have a username, a\r
208     # password, a list of netmasks to match against, and a list of\r
209     # permissions. A BotUser can be marked as 'transient', usually meaning\r
210     # it's not intended for permanent storage. Transient BotUsers have lower\r
211     # priority than nontransient ones for autologin purposes.\r
212     #\r
213     # To initialize a BotUser, you pass a _username_ and an optional\r
214     # hash of options. Currently, only two options are recognized:\r
215     #\r
216     # transient:: true or false, determines if the BotUser is transient or\r
217     #             permanent (default is false, permanent BotUser).\r
218     #\r
219     #             Transient BotUsers are initialized by prepending an\r
220     #             asterisk (*) to the username, and appending a sanitized\r
221     #             version of the object_id. The username can be empty.\r
222     #             A random password is generated.\r
223     #\r
224     #             Permanent Botusers need the username as is, and no\r
225     #             password is generated.\r
226     #\r
227     # masks::     an array of Netmasks to initialize the NetmaskList. This\r
228     #             list is used as-is for permanent BotUsers.\r
229     #\r
230     #             Transient BotUsers will alter the list elements which are\r
231     #             Irc::User by globbing the nick and any initial nonletter\r
232     #             part of the ident.\r
233     #\r
234     #             The masks option is optional for permanent BotUsers, but\r
235     #             obligatory (non-empty) for transients.\r
236     #\r
237     class BotUser\r
238 \r
239       attr_reader :username\r
240       attr_reader :password\r
241       attr_reader :netmasks\r
242       attr_reader :perm\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 TypeError, "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       end\r
321 \r
322       # Inspection\r
323       def inspect\r
324         str = self.__to_s__[0..-2]\r
325         str << " (transient)" if @transient\r
326         str << ":"\r
327         str << " @username=#{@username.inspect}"\r
328         str << " @netmasks=#{@netmasks.inspect}"\r
329         str << " @perm=#{@perm.inspect}"\r
330         str << " @login_by_mask=#{@login_by_mask}"\r
331         str << " @autologin=#{@autologin}"\r
332         str << ">"\r
333       end\r
334 \r
335       # In strings\r
336       def to_s\r
337         @username\r
338       end\r
339 \r
340       # Convert into a hash\r
341       def to_hash\r
342         {\r
343           :username => @username,\r
344           :password => @password,\r
345           :netmasks => @netmasks,\r
346           :perm => @perm,\r
347           :login_by_mask => @login_by_mask,\r
348           :autologin => @autologin,\r
349         }\r
350       end\r
351 \r
352       # Do we allow logging in without providing the password?\r
353       #\r
354       def login_by_mask?\r
355         @login_by_mask\r
356       end\r
357 \r
358       # Reset the login-by-mask option\r
359       #\r
360       def reset_login_by_mask\r
361         @login_by_mask = Auth.manager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)\r
362       end\r
363 \r
364       # Reset the autologin option\r
365       #\r
366       def reset_autologin\r
367         @autologin = Auth.manager.bot.config['auth.autologin'] unless defined?(@autologin)\r
368       end\r
369 \r
370       # Do we allow automatic logging in?\r
371       #\r
372       def autologin?\r
373         @autologin\r
374       end\r
375 \r
376       # Restore from hash\r
377       def from_hash(h)\r
378         @username = h[:username] if h.has_key?(:username)\r
379         @password = h[:password] if h.has_key?(:password)\r
380         @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)\r
381         @autologin = h[:autologin] if h.has_key?(:autologin)\r
382         if h.has_key?(:netmasks)\r
383           @netmasks = h[:netmasks]\r
384           debug @netmasks\r
385           @netmasks.each { |n| Auth.manager.maskdb.add(self, n) } if @autologin\r
386           debug @netmasks\r
387         end\r
388         @perm = h[:perm] if h.has_key?(:perm)\r
389       end\r
390 \r
391       # This method sets the password if the proposed new password\r
392       # is valid\r
393       def password=(pwd=nil)\r
394         pass = pwd.to_s\r
395         if pass.empty?\r
396           reset_password\r
397         else\r
398           begin\r
399             raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/\r
400             raise InvalidPassword, "#{pass} too short" if pass.length < 4\r
401             @password = pass\r
402           rescue InvalidPassword => e\r
403             raise e\r
404           rescue => e\r
405             raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"\r
406           end\r
407         end\r
408       end\r
409 \r
410       # Resets the password by creating a new onw\r
411       def reset_password\r
412         @password = Auth.random_password\r
413       end\r
414 \r
415       # Sets the permission for command _cmd_ to _val_ on channel _chan_\r
416       #\r
417       def set_permission(cmd, val, chan="*")\r
418         k = chan.to_s.to_sym\r
419         @perm[k] = PermissionSet.new unless @perm.has_key?(k)\r
420         @perm[k].set_permission(cmd, val)\r
421       end\r
422 \r
423       # Resets the permission for command _cmd_ on channel _chan_\r
424       #\r
425       def reset_permission(cmd, chan ="*")\r
426         set_permission(cmd, nil, chan)\r
427       end\r
428 \r
429       # Checks if BotUser is allowed to do something on channel _chan_,\r
430       # or on all channels if _chan_ is nil\r
431       #\r
432       def permit?(cmd, chan=nil)\r
433         if chan\r
434           k = chan.to_s.to_sym\r
435         else\r
436           k = :*\r
437         end\r
438         allow = nil\r
439         if @perm.has_key?(k)\r
440           allow = @perm[k].permit?(cmd)\r
441         end\r
442         return allow\r
443       end\r
444 \r
445       # Adds a Netmask\r
446       #\r
447       def add_netmask(mask)\r
448         m = mask.to_irc_netmask\r
449         @netmasks << m\r
450         if self.autologin?\r
451           Auth.manager.maskdb.add(self, m)\r
452           Auth.manager.logout_transients(m) if self.permanent?\r
453         end\r
454       end\r
455 \r
456       # Removes a Netmask\r
457       #\r
458       def delete_netmask(mask)\r
459         m = mask.to_irc_netmask\r
460         @netmasks.delete(m)\r
461         Auth.manager.maskdb.remove(self, m) if self.autologin?\r
462       end\r
463 \r
464       # Reset Netmasks, clearing @netmasks\r
465       #\r
466       def reset_netmasks\r
467         @netmasks.each { |m|\r
468           Auth.manager.maskdb.remove(self, m) if self.autologin?\r
469         }\r
470         @netmasks.clear\r
471       end\r
472 \r
473       # This method checks if BotUser has a Netmask that matches _user_\r
474       #\r
475       def knows?(usr)\r
476         user = usr.to_irc_user\r
477         !!@netmasks.find { |n| user.matches? n }\r
478       end\r
479 \r
480       # This method gets called when User _user_ wants to log in.\r
481       # It returns true or false depending on whether the password\r
482       # is right. If it is, the Netmask of the user is added to the\r
483       # list of acceptable Netmask unless it's already matched.\r
484       def login(user, password=nil)\r
485         if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))\r
486           add_netmask(user) unless knows?(user)\r
487           debug "#{user} logged in as #{self.inspect}"\r
488           return true\r
489         else\r
490           return false\r
491         end\r
492       end\r
493 \r
494       # # This method gets called when User _user_ has logged out as this BotUser\r
495       # def logout(user)\r
496       #   delete_netmask(user) if knows?(user)\r
497       # end\r
498 \r
499       # This method sanitizes a username by chomping, downcasing\r
500       # and replacing any nonalphanumeric character with _\r
501       #\r
502       def BotUser.sanitize_username(name)\r
503         candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")\r
504         raise "sanitized botusername #{candidate} too short" if candidate.length < 3\r
505         return candidate\r
506       end\r
507 \r
508     end\r
509 \r
510     # This is the default BotUser: it's used for all users which haven't\r
511     # identified with the bot\r
512     #\r
513     class DefaultBotUserClass < BotUser\r
514 \r
515       private :add_netmask, :delete_netmask\r
516 \r
517       include Singleton\r
518 \r
519       # The default BotUser is named 'everyone'\r
520       #\r
521       def initialize\r
522         reset_login_by_mask\r
523         reset_autologin\r
524         super("everyone")\r
525         @default_perm = PermissionSet.new\r
526       end\r
527 \r
528       # This method returns without changing anything\r
529       #\r
530       def login_by_mask=(val)\r
531         debug "Tried to change the login-by-mask for default bot user, ignoring"\r
532         return @login_by_mask\r
533       end\r
534 \r
535       # The default botuser allows logins by mask\r
536       #\r
537       def reset_login_by_mask\r
538         @login_by_mask = true\r
539       end\r
540 \r
541       # This method returns without changing anything\r
542       #\r
543       def autologin=(val)\r
544         debug "Tried to change the autologin for default bot user, ignoring"\r
545         return\r
546       end\r
547 \r
548       # The default botuser doesn't allow autologin (meaningless)\r
549       #\r
550       def reset_autologin\r
551         @autologin = false\r
552       end\r
553 \r
554       # Sets the default permission for the default user (i.e. the ones\r
555       # set by the BotModule writers) on all channels\r
556       #\r
557       def set_default_permission(cmd, val)\r
558         @default_perm.set_permission(Command.new(cmd), val)\r
559         debug "Default permissions now: #{@default_perm.pretty_inspect}"\r
560       end\r
561 \r
562       # default knows everybody\r
563       #\r
564       def knows?(user)\r
565         return true if user.to_irc_user\r
566       end\r
567 \r
568       # We always allow logging in as the default user\r
569       def login(user, password)\r
570         return true\r
571       end\r
572 \r
573       # DefaultBotUser will check the default_perm after checking\r
574       # the global ones\r
575       # or on all channels if _chan_ is nil\r
576       #\r
577       def permit?(cmd, chan=nil)\r
578         allow = super(cmd, chan)\r
579         if allow.nil? && chan.nil?\r
580           allow = @default_perm.permit?(cmd)\r
581         end\r
582         return allow\r
583       end\r
584 \r
585     end\r
586 \r
587     # Returns the only instance of DefaultBotUserClass\r
588     #\r
589     def Auth.defaultbotuser\r
590       return DefaultBotUserClass.instance\r
591     end\r
592 \r
593     # This is the BotOwner: he can do everything\r
594     #\r
595     class BotOwnerClass < BotUser\r
596 \r
597       include Singleton\r
598 \r
599       def initialize\r
600         @login_by_mask = false\r
601         @autologin = true\r
602         super("owner")\r
603       end\r
604 \r
605       def permit?(cmd, chan=nil)\r
606         return true\r
607       end\r
608 \r
609     end\r
610 \r
611     # Returns the only instance of BotOwnerClass\r
612     #\r
613     def Auth.botowner\r
614       return BotOwnerClass.instance\r
615     end\r
616 \r
617 \r
618     class BotUser\r
619       # Check if the current BotUser is the default one\r
620       def default?\r
621         return DefaultBotUserClass === self\r
622       end\r
623 \r
624       # Check if the current BotUser is the owner\r
625       def owner?\r
626         return BotOwnerClass === self\r
627       end\r
628     end\r
629 \r
630 \r
631     # This is the ManagerClass singleton, used to manage\r
632     # Irc::User/Irc::Bot::Auth::BotUser connections and everything\r
633     #\r
634     class ManagerClass\r
635 \r
636       include Singleton\r
637 \r
638       attr_reader :maskdb\r
639       attr_reader :everyone\r
640       attr_reader :botowner\r
641       attr_reader :bot\r
642 \r
643       # The instance manages two <code>Hash</code>es: one that maps\r
644       # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps\r
645       # usernames onto <code>BotUser</code>\r
646       def initialize\r
647         @everyone = Auth::defaultbotuser\r
648         @botowner = Auth::botowner\r
649         bot_associate(nil)\r
650       end\r
651 \r
652       def bot_associate(bot)\r
653         raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes\r
654 \r
655         reset_hashes\r
656 \r
657         # Associated bot\r
658         @bot = bot\r
659 \r
660         # This variable is set to true when there have been changes\r
661         # to the botusers list, so that we know when to save\r
662         @has_changes = false\r
663       end\r
664 \r
665       def set_changed\r
666         @has_changes = true\r
667       end\r
668 \r
669       def reset_changed\r
670         @has_changes = false\r
671       end\r
672 \r
673       def changed?\r
674         @has_changes\r
675       end\r
676 \r
677       # resets the hashes\r
678       def reset_hashes\r
679         @botusers = Hash.new\r
680         @maskdb = NetmaskDb.new\r
681         @allbotusers = Hash.new\r
682         [everyone, botowner].each do |x|\r
683           @allbotusers[x.username.to_sym] = x\r
684         end\r
685       end\r
686 \r
687       def load_array(ary, forced)\r
688         unless ary\r
689           warning "Tried to load an empty array"\r
690           return\r
691         end\r
692         raise "Won't load with unsaved changes" if @has_changes and not forced\r
693         reset_hashes\r
694         ary.each { |x|\r
695           raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)\r
696           u = x[:username]\r
697           unless include?(u)\r
698             create_botuser(u)\r
699           end\r
700           get_botuser(u).from_hash(x)\r
701           get_botuser(u).transient = false\r
702         }\r
703         @has_changes=false\r
704       end\r
705 \r
706       def save_array\r
707         @allbotusers.values.map { |x|\r
708           x.transient? ? nil : x.to_hash\r
709         }.compact\r
710       end\r
711 \r
712       # checks if we know about a certain BotUser username\r
713       def include?(botusername)\r
714         @allbotusers.has_key?(botusername.to_sym)\r
715       end\r
716 \r
717       # Maps <code>Irc::User</code> to BotUser\r
718       def irc_to_botuser(ircuser)\r
719         logged = @botusers[ircuser.to_irc_user]\r
720         return logged if logged\r
721         return autologin(ircuser)\r
722       end\r
723 \r
724       # creates a new BotUser\r
725       def create_botuser(name, password=nil)\r
726         n = BotUser.sanitize_username(name)\r
727         k = n.to_sym\r
728         raise "botuser #{n} exists" if include?(k)\r
729         bu = BotUser.new(n)\r
730         bu.password = password\r
731         @allbotusers[k] = bu\r
732         return bu\r
733       end\r
734 \r
735       # returns the botuser with name _name_\r
736       def get_botuser(name)\r
737         @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)\r
738       end\r
739 \r
740       # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_\r
741       #\r
742       # raises an error if _botusername_ is not a known BotUser username\r
743       #\r
744       # It is possible to autologin by Netmask, on request\r
745       #\r
746       def login(user, botusername, pwd=nil)\r
747         ircuser = user.to_irc_user\r
748         n = BotUser.sanitize_username(botusername)\r
749         k = n.to_sym\r
750         raise "No such BotUser #{n}" unless include?(k)\r
751         if @botusers.has_key?(ircuser)\r
752           return true if @botusers[ircuser].username == n\r
753           # TODO\r
754           # @botusers[ircuser].logout(ircuser)\r
755         end\r
756         bu = @allbotusers[k]\r
757         if bu.login(ircuser, pwd)\r
758           @botusers[ircuser] = bu\r
759           return true\r
760         end\r
761         return false\r
762       end\r
763 \r
764       # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin\r
765       # and trying to login without a password\r
766       #\r
767       def autologin(user)\r
768         ircuser = user.to_irc_user\r
769         debug "Trying to autologin #{ircuser}"\r
770         return @botusers[ircuser] if @botusers.has_key?(ircuser)\r
771         bu = maskdb.find(ircuser)\r
772         if bu\r
773           debug "trying #{bu}"\r
774           bu.login(ircuser) or raise '...what?!'\r
775           @botusers[ircuser] = bu\r
776           return bu\r
777         end\r
778         # Finally, create a transient if we're set to allow it\r
779         if @bot.config['auth.autouser']\r
780           bu = create_transient_botuser(ircuser)\r
781           @botusers[ircuser] = bu\r
782           return bu\r
783         end\r
784         return everyone\r
785       end\r
786 \r
787       # Creates a new transient BotUser associated with Irc::User _user_,\r
788       # automatically logging him in. Note that transient botuser creation can\r
789       # fail, typically if we don't have the complete user netmask (e.g. for\r
790       # messages coming in from a linkbot)\r
791       #\r
792       def create_transient_botuser(user)\r
793         ircuser = user.to_irc_user\r
794         bu = everyone\r
795         begin\r
796           bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)\r
797           bu.login(ircuser)\r
798         rescue\r
799           warning "failed to create transient for #{user}"\r
800           error $!\r
801         end\r
802         return bu\r
803       end\r
804 \r
805       # Logs out any Irc::User matching Irc::Netmask _m_ and logged in\r
806       # to a transient BotUser\r
807       #\r
808       def logout_transients(m)\r
809         debug "to check: #{@botusers.keys.join ' '}"\r
810         @botusers.keys.each do |iu|\r
811           debug "checking #{iu.fullform} against #{m.fullform}"\r
812           bu = @botusers[iu]\r
813           bu.transient? or next\r
814           iu.matches?(m) or next\r
815           @botusers.delete(iu).autologin = false\r
816         end\r
817       end\r
818 \r
819       # Makes transient BotUser _user_ into a permanent BotUser\r
820       # named _name_; if _user_ is an Irc::User, act on the transient\r
821       # BotUser (if any) it's logged in as\r
822       #\r
823       def make_permanent(user, name)\r
824         buname = BotUser.sanitize_username(name)\r
825         # TODO merge BotUser instead?\r
826         raise "there's already a BotUser called #{name}" if include?(buname)\r
827 \r
828         tuser = nil\r
829         case user\r
830         when String, Irc::User\r
831           tuser = irc_to_botuser(user)\r
832         when BotUser\r
833           tuser = user\r
834         else\r
835           raise TypeError, "sorry, don't know how to make #{user.class} into a permanent BotUser"\r
836         end\r
837         return nil unless tuser\r
838         raise TypeError, "#{tuser} is not transient" unless tuser.transient?\r
839 \r
840         tuser.make_permanent(buname)\r
841         @allbotusers[tuser.username.to_sym] = tuser\r
842 \r
843         return tuser\r
844       end\r
845 \r
846       # Checks if User _user_ can do _cmd_ on _chan_.\r
847       #\r
848       # Permission are checked in this order, until a true or false\r
849       # is returned:\r
850       # * associated BotUser on _chan_\r
851       # * associated BotUser on all channels\r
852       # * everyone on _chan_\r
853       # * everyone on all channels\r
854       #\r
855       def permit?(user, cmdtxt, channel=nil)\r
856         if user.class <= BotUser\r
857           botuser = user\r
858         else\r
859           botuser = irc_to_botuser(user)\r
860         end\r
861         cmd = cmdtxt.to_irc_auth_command\r
862 \r
863         chan = channel\r
864         case chan\r
865         when User\r
866           chan = "?"\r
867         when Channel\r
868           chan = chan.name\r
869         end\r
870 \r
871         allow = nil\r
872 \r
873         allow = botuser.permit?(cmd, chan) if chan\r
874         return allow unless allow.nil?\r
875         allow = botuser.permit?(cmd)\r
876         return allow unless allow.nil?\r
877 \r
878         unless botuser == everyone\r
879           allow = everyone.permit?(cmd, chan) if chan\r
880           return allow unless allow.nil?\r
881           allow = everyone.permit?(cmd)\r
882           return allow unless allow.nil?\r
883         end\r
884 \r
885         raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"\r
886       end\r
887 \r
888       # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally\r
889       # telling if the user is authorized\r
890       #\r
891       def allow?(cmdtxt, user, chan=nil)\r
892         if permit?(user, cmdtxt, chan)\r
893           return true\r
894         else\r
895           # cmds = cmdtxt.split('::')\r
896           # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan\r
897           @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %\r
898                         {:user=>user, :command=>cmdtxt} if chan\r
899           return false\r
900         end\r
901       end\r
902 \r
903     end\r
904 \r
905     # Returns the only instance of ManagerClass\r
906     #\r
907     def Auth.manager\r
908       return ManagerClass.instance\r
909     end\r
910 \r
911   end\r
912 end\r
913 \r
914   class User\r
915 \r
916     # A convenience method to automatically found the botuser\r
917     # associated with the receiver\r
918     #\r
919     def botuser\r
920       Irc::Bot::Auth.manager.irc_to_botuser(self)\r
921     end\r
922   end\r
923 \r
924 end\r