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