]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/botuser.rb
Use rbot's own warning() command instead of Ruby built-in warn()
[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 \r
12 \r
13 module Irc\r
14 \r
15 \r
16   # This module contains the actual Authentication stuff\r
17   #\r
18   module Auth\r
19 \r
20     BotConfig.register BotConfigStringValue.new( 'auth.password',\r
21       :default => 'rbotauth', :wizard => true,\r
22       :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},\r
23       :desc => _('Password for the bot owner'))\r
24     BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',\r
25       :default => 'true',\r
26       :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))\r
27     BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',\r
28       :default => 'true',\r
29       :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))\r
30     # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',\r
31     #   :default => 10, :wizard => true,\r
32     #   :desc => 'The default level for new/unknown users' )\r
33 \r
34     # Generate a random password of length _l_\r
35     #\r
36     def Auth.random_password(l=8)\r
37       pwd = ""\r
38       l.times do\r
39         pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr\r
40       end\r
41       return pwd\r
42     end\r
43 \r
44 \r
45     # An Irc::Auth::Command defines a command by its "path":\r
46     #\r
47     #   base::command::subcommand::subsubcommand::subsubsubcommand\r
48     #\r
49     class Command\r
50 \r
51       attr_reader :command, :path\r
52 \r
53       # A method that checks if a given _cmd_ is in a form that can be\r
54       # reduced into a canonical command path, and if so, returns it\r
55       #\r
56       def sanitize_command_path(cmd)\r
57         pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")\r
58         return pre if pre.empty?\r
59         return pre if pre =~ /^\S+(::\S+)*$/\r
60         raise TypeError, "#{cmd.inspect} is not a valid command"\r
61       end\r
62 \r
63       # Creates a new Command from a given string; you can then access\r
64       # the command as a symbol with the :command method and the whole\r
65       # path as :path\r
66       #\r
67       #   Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]\r
68       #\r
69       #   Command.new("core::auth::save").command => :"core::auth::save"\r
70       #\r
71       def initialize(cmd)\r
72         cmdpath = sanitize_command_path(cmd).split('::')\r
73         seq = cmdpath.inject(["*"]) { |list, cmd|\r
74           list << (list.length > 1 ? list.last + "::" : "") + cmd\r
75         }\r
76         @path = seq.map { |k|\r
77           k.to_sym\r
78         }\r
79         @command = path.last\r
80         debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"\r
81       end\r
82 \r
83       # Returs self\r
84       def to_irc_auth_command\r
85         self\r
86       end\r
87 \r
88     end\r
89 \r
90   end\r
91 \r
92 end\r
93 \r
94 \r
95 class String\r
96 \r
97   # Returns an Irc::Auth::Comand from the receiver\r
98   def to_irc_auth_command\r
99     Irc::Auth::Command.new(self)\r
100   end\r
101 \r
102 end\r
103 \r
104 \r
105 class Symbol\r
106 \r
107   # Returns an Irc::Auth::Comand from the receiver\r
108   def to_irc_auth_command\r
109     Irc::Auth::Command.new(self)\r
110   end\r
111 \r
112 end\r
113 \r
114 \r
115 module Irc\r
116 \r
117 \r
118   module Auth\r
119 \r
120 \r
121     # This class describes a permission set\r
122     class PermissionSet\r
123 \r
124       attr_reader :perm\r
125       # Create a new (empty) PermissionSet\r
126       #\r
127       def initialize\r
128         @perm = {}\r
129       end\r
130 \r
131       # Inspection simply inspects the internal hash\r
132       def inspect\r
133         @perm.inspect\r
134       end\r
135 \r
136       # Sets the permission for command _cmd_ to _val_,\r
137       #\r
138       def set_permission(str, val)\r
139         cmd = str.to_irc_auth_command\r
140         case val\r
141         when true, false\r
142           @perm[cmd.command] = val\r
143         when nil\r
144           @perm.delete(cmd.command)\r
145         else\r
146           raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)\r
147         end\r
148       end\r
149 \r
150       # Resets the permission for command _cmd_\r
151       #\r
152       def reset_permission(cmd)\r
153         set_permission(cmd, nil)\r
154       end\r
155 \r
156       # Tells if command _cmd_ is permitted. We do this by returning\r
157       # the value of the deepest Command#path that matches.\r
158       #\r
159       def permit?(str)\r
160         cmd = str.to_irc_auth_command\r
161         allow = nil\r
162         cmd.path.reverse.each { |k|\r
163           if @perm.has_key?(k)\r
164             allow = @perm[k]\r
165             break\r
166           end\r
167         }\r
168         return allow\r
169       end\r
170 \r
171     end\r
172 \r
173 \r
174     # This is the error that gets raised when an invalid password is met\r
175     #\r
176     class InvalidPassword < RuntimeError\r
177     end\r
178 \r
179 \r
180     # This is the basic class for bot users: they have a username, a password,\r
181     # a list of netmasks to match against, and a list of permissions.\r
182     #\r
183     class BotUser\r
184 \r
185       attr_reader :username\r
186       attr_reader :password\r
187       attr_reader :netmasks\r
188       attr_reader :perm\r
189       attr_writer :login_by_mask\r
190       attr_writer :autologin\r
191 \r
192       # Create a new BotUser with given username\r
193       def initialize(username)\r
194         @username = BotUser.sanitize_username(username)\r
195         @password = nil\r
196         @netmasks = NetmaskList.new\r
197         @perm = {}\r
198         reset_login_by_mask\r
199         reset_autologin\r
200       end\r
201 \r
202       # Inspection\r
203       def inspect\r
204         str = "<#{self.class}:#{'0x%08x' % self.object_id}:"\r
205         str << " @username=#{@username.inspect}"\r
206         str << " @netmasks=#{@netmasks.inspect}"\r
207         str << " @perm=#{@perm.inspect}"\r
208         str << " @login_by_mask=#{@login_by_mask}"\r
209         str << " @autologin=#{@autologin}"\r
210         str << ">"\r
211       end\r
212 \r
213       # In strings\r
214       def to_s\r
215         @username\r
216       end\r
217 \r
218       # Convert into a hash\r
219       def to_hash\r
220         {\r
221           :username => @username,\r
222           :password => @password,\r
223           :netmasks => @netmasks,\r
224           :perm => @perm,\r
225           :login_by_mask => @login_by_mask,\r
226           :autologin => @autologin\r
227         }\r
228       end\r
229 \r
230       # Do we allow logging in without providing the password?\r
231       #\r
232       def login_by_mask?\r
233         @login_by_mask\r
234       end\r
235 \r
236       # Reset the login-by-mask option\r
237       #\r
238       def reset_login_by_mask\r
239         @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)\r
240       end\r
241 \r
242       # Reset the autologin option\r
243       #\r
244       def reset_autologin\r
245         @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)\r
246       end\r
247 \r
248       # Do we allow automatic logging in?\r
249       #\r
250       def autologin?\r
251         @autologin\r
252       end\r
253 \r
254       # Restore from hash\r
255       def from_hash(h)\r
256         @username = h[:username] if h.has_key?(:username)\r
257         @password = h[:password] if h.has_key?(:password)\r
258         @netmasks = h[:netmasks] if h.has_key?(:netmasks)\r
259         @perm = h[:perm] if h.has_key?(:perm)\r
260         @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)\r
261         @autologin = h[:autologin] if h.has_key?(:autologin)\r
262       end\r
263 \r
264       # This method sets the password if the proposed new password\r
265       # is valid\r
266       def password=(pwd=nil)\r
267         pass = pwd.to_s\r
268         if pass.empty?\r
269           reset_password\r
270         else\r
271           begin\r
272             raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/\r
273             raise InvalidPassword, "#{pass} too short" if pass.length < 4\r
274             @password = pass\r
275           rescue InvalidPassword => e\r
276             raise e\r
277           rescue => e\r
278             raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"\r
279           end\r
280         end\r
281       end\r
282 \r
283       # Resets the password by creating a new onw\r
284       def reset_password\r
285         @password = Auth.random_password\r
286       end\r
287 \r
288       # Sets the permission for command _cmd_ to _val_ on channel _chan_\r
289       #\r
290       def set_permission(cmd, val, chan="*")\r
291         k = chan.to_s.to_sym\r
292         @perm[k] = PermissionSet.new unless @perm.has_key?(k)\r
293         @perm[k].set_permission(cmd, val)\r
294       end\r
295 \r
296       # Resets the permission for command _cmd_ on channel _chan_\r
297       #\r
298       def reset_permission(cmd, chan ="*")\r
299         set_permission(cmd, nil, chan)\r
300       end\r
301 \r
302       # Checks if BotUser is allowed to do something on channel _chan_,\r
303       # or on all channels if _chan_ is nil\r
304       #\r
305       def permit?(cmd, chan=nil)\r
306         if chan\r
307           k = chan.to_s.to_sym\r
308         else\r
309           k = :*\r
310         end\r
311         allow = nil\r
312         if @perm.has_key?(k)\r
313           allow = @perm[k].permit?(cmd)\r
314         end\r
315         return allow\r
316       end\r
317 \r
318       # Adds a Netmask\r
319       #\r
320       def add_netmask(mask)\r
321         @netmasks << mask.to_irc_netmask\r
322       end\r
323 \r
324       # Removes a Netmask\r
325       #\r
326       def delete_netmask(mask)\r
327         m = mask.to_irc_netmask\r
328         @netmasks.delete(m)\r
329       end\r
330 \r
331       # Removes all <code>Netmask</code>s\r
332       #\r
333       def reset_netmasks\r
334         @netmasks = NetmaskList.new\r
335       end\r
336 \r
337       # This method checks if BotUser has a Netmask that matches _user_\r
338       #\r
339       def knows?(usr)\r
340         user = usr.to_irc_user\r
341         known = false\r
342         @netmasks.each { |n|\r
343           if user.matches?(n)\r
344             known = true\r
345             break\r
346           end\r
347         }\r
348         return known\r
349       end\r
350 \r
351       # This method gets called when User _user_ wants to log in.\r
352       # It returns true or false depending on whether the password\r
353       # is right. If it is, the Netmask of the user is added to the\r
354       # list of acceptable Netmask unless it's already matched.\r
355       def login(user, password)\r
356         if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))\r
357           add_netmask(user) unless knows?(user)\r
358           debug "#{user} logged in as #{self.inspect}"\r
359           return true\r
360         else\r
361           return false\r
362         end\r
363       end\r
364 \r
365       # # This method gets called when User _user_ has logged out as this BotUser\r
366       # def logout(user)\r
367       #   delete_netmask(user) if knows?(user)\r
368       # end\r
369 \r
370       # This method sanitizes a username by chomping, downcasing\r
371       # and replacing any nonalphanumeric character with _\r
372       #\r
373       def BotUser.sanitize_username(name)\r
374         candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")\r
375         raise "sanitized botusername #{candidate} too short" if candidate.length < 3\r
376         return candidate\r
377       end\r
378 \r
379     end\r
380 \r
381 \r
382     # This is the default BotUser: it's used for all users which haven't\r
383     # identified with the bot\r
384     #\r
385     class DefaultBotUserClass < BotUser\r
386 \r
387       private :add_netmask, :delete_netmask\r
388 \r
389       include Singleton\r
390 \r
391       # The default BotUser is named 'everyone'\r
392       #\r
393       def initialize\r
394         reset_login_by_mask\r
395         reset_autologin\r
396         super("everyone")\r
397         @default_perm = PermissionSet.new\r
398       end\r
399 \r
400       # This method returns without changing anything\r
401       #\r
402       def login_by_mask=(val)\r
403         debug "Tried to change the login-by-mask for default bot user, ignoring"\r
404         return @login_by_mask\r
405       end\r
406 \r
407       # The default botuser allows logins by mask\r
408       #\r
409       def reset_login_by_mask\r
410         @login_by_mask = true\r
411       end\r
412 \r
413       # This method returns without changing anything\r
414       #\r
415       def autologin=(val)\r
416         debug "Tried to change the autologin for default bot user, ignoring"\r
417         return\r
418       end\r
419 \r
420       # The default botuser doesn't allow autologin (meaningless)\r
421       #\r
422       def reset_autologin\r
423         @autologin = false\r
424       end\r
425 \r
426       # Sets the default permission for the default user (i.e. the ones\r
427       # set by the BotModule writers) on all channels\r
428       #\r
429       def set_default_permission(cmd, val)\r
430         @default_perm.set_permission(Command.new(cmd), val)\r
431         debug "Default permissions now: #{@default_perm.pretty_inspect}"\r
432       end\r
433 \r
434       # default knows everybody\r
435       #\r
436       def knows?(user)\r
437         return true if user.to_irc_user\r
438       end\r
439 \r
440       # We always allow logging in as the default user\r
441       def login(user, password)\r
442         return true\r
443       end\r
444 \r
445       # Resets the NetmaskList\r
446       def reset_netmasks\r
447         super\r
448         add_netmask("*!*@*")\r
449       end\r
450 \r
451       # DefaultBotUser will check the default_perm after checking\r
452       # the global ones\r
453       # or on all channels if _chan_ is nil\r
454       #\r
455       def permit?(cmd, chan=nil)\r
456         allow = super(cmd, chan)\r
457         if allow.nil? && chan.nil?\r
458           allow = @default_perm.permit?(cmd)\r
459         end\r
460         return allow\r
461       end\r
462 \r
463     end\r
464 \r
465     # Returns the only instance of DefaultBotUserClass\r
466     #\r
467     def Auth.defaultbotuser\r
468       return DefaultBotUserClass.instance\r
469     end\r
470 \r
471     # This is the BotOwner: he can do everything\r
472     #\r
473     class BotOwnerClass < BotUser\r
474 \r
475       include Singleton\r
476 \r
477       def initialize\r
478         @login_by_mask = false\r
479         @autologin = true\r
480         super("owner")\r
481       end\r
482 \r
483       def permit?(cmd, chan=nil)\r
484         return true\r
485       end\r
486 \r
487     end\r
488 \r
489     # Returns the only instance of BotOwnerClass\r
490     #\r
491     def Auth.botowner\r
492       return BotOwnerClass.instance\r
493     end\r
494 \r
495 \r
496     # This is the AuthManagerClass singleton, used to manage User/BotUser connections and\r
497     # everything\r
498     #\r
499     class AuthManagerClass\r
500 \r
501       include Singleton\r
502 \r
503       attr_reader :everyone\r
504       attr_reader :botowner\r
505       attr_reader :bot\r
506 \r
507       # The instance manages two <code>Hash</code>es: one that maps\r
508       # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps\r
509       # usernames onto <code>BotUser</code>\r
510       def initialize\r
511         @everyone = Auth::defaultbotuser\r
512         @botowner = Auth::botowner\r
513         bot_associate(nil)\r
514       end\r
515 \r
516       def bot_associate(bot)\r
517         raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes\r
518 \r
519         reset_hashes\r
520 \r
521         # Associated bot\r
522         @bot = bot\r
523 \r
524         # This variable is set to true when there have been changes\r
525         # to the botusers list, so that we know when to save\r
526         @has_changes = false\r
527       end\r
528 \r
529       def set_changed\r
530         @has_changes = true\r
531       end\r
532 \r
533       def reset_changed\r
534         @has_changes = false\r
535       end\r
536 \r
537       def changed?\r
538         @has_changes\r
539       end\r
540 \r
541       # resets the hashes\r
542       def reset_hashes\r
543         @botusers = Hash.new\r
544         @allbotusers = Hash.new\r
545         [everyone, botowner].each { |x|\r
546           @allbotusers[x.username.to_sym] = x\r
547         }\r
548       end\r
549 \r
550       def load_array(ary, forced)\r
551         unless ary\r
552           warning "Tried to load an empty array"\r
553           return\r
554         end\r
555         raise "Won't load with unsaved changes" if @has_changes and not forced\r
556         reset_hashes\r
557         ary.each { |x|\r
558           raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)\r
559           u = x[:username]\r
560           unless include?(u)\r
561             create_botuser(u)\r
562           end\r
563           get_botuser(u).from_hash(x)\r
564         }\r
565         @has_changes=false\r
566       end\r
567 \r
568       def save_array\r
569         @allbotusers.values.map { |x|\r
570           x.to_hash\r
571         }\r
572       end\r
573 \r
574       # checks if we know about a certain BotUser username\r
575       def include?(botusername)\r
576         @allbotusers.has_key?(botusername.to_sym)\r
577       end\r
578 \r
579       # Maps <code>Irc::User</code> to BotUser\r
580       def irc_to_botuser(ircuser)\r
581         logged = @botusers[ircuser.to_irc_user]\r
582         return logged if logged\r
583         return autologin(ircuser)\r
584       end\r
585 \r
586       # creates a new BotUser\r
587       def create_botuser(name, password=nil)\r
588         n = BotUser.sanitize_username(name)\r
589         k = n.to_sym\r
590         raise "botuser #{n} exists" if include?(k)\r
591         bu = BotUser.new(n)\r
592         bu.password = password\r
593         @allbotusers[k] = bu\r
594         return bu\r
595       end\r
596 \r
597       # returns the botuser with name _name_\r
598       def get_botuser(name)\r
599         @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)\r
600       end\r
601 \r
602       # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_\r
603       #\r
604       # raises an error if _botusername_ is not a known BotUser username\r
605       #\r
606       # It is possible to autologin by Netmask, on request\r
607       #\r
608       def login(user, botusername, pwd=nil)\r
609         ircuser = user.to_irc_user\r
610         n = BotUser.sanitize_username(botusername)\r
611         k = n.to_sym\r
612         raise "No such BotUser #{n}" unless include?(k)\r
613         if @botusers.has_key?(ircuser)\r
614           return true if @botusers[ircuser].username == n\r
615           # TODO\r
616           # @botusers[ircuser].logout(ircuser)\r
617         end\r
618         bu = @allbotusers[k]\r
619         if bu.login(ircuser, pwd)\r
620           @botusers[ircuser] = bu\r
621           return true\r
622         end\r
623         return false\r
624       end\r
625 \r
626       # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin\r
627       # and trying to login without a password\r
628       #\r
629       def autologin(user)\r
630         ircuser = user.to_irc_user\r
631         debug "Trying to autlogin #{ircuser}"\r
632         return @botusers[ircuser] if @botusers.has_key?(ircuser)\r
633         @allbotusers.each { |n, bu|\r
634           debug "Checking with #{n}"\r
635           return bu if bu.autologin? and login(ircuser, n)\r
636         }\r
637         return everyone\r
638       end\r
639 \r
640       # Checks if User _user_ can do _cmd_ on _chan_.\r
641       #\r
642       # Permission are checked in this order, until a true or false\r
643       # is returned:\r
644       # * associated BotUser on _chan_\r
645       # * associated BotUser on all channels\r
646       # * everyone on _chan_\r
647       # * everyone on all channels\r
648       #\r
649       def permit?(user, cmdtxt, channel=nil)\r
650         if user.class <= BotUser\r
651           botuser = user\r
652         else\r
653           botuser = irc_to_botuser(user)\r
654         end\r
655         cmd = cmdtxt.to_irc_auth_command\r
656 \r
657         chan = channel\r
658         case chan\r
659         when User\r
660           chan = "?"\r
661         when Channel\r
662           chan = chan.name\r
663         end\r
664 \r
665         allow = nil\r
666 \r
667         allow = botuser.permit?(cmd, chan) if chan\r
668         return allow unless allow.nil?\r
669         allow = botuser.permit?(cmd)\r
670         return allow unless allow.nil?\r
671 \r
672         unless botuser == everyone\r
673           allow = everyone.permit?(cmd, chan) if chan\r
674           return allow unless allow.nil?\r
675           allow = everyone.permit?(cmd)\r
676           return allow unless allow.nil?\r
677         end\r
678 \r
679         raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"\r
680       end\r
681 \r
682       # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally\r
683       # telling if the user is authorized\r
684       #\r
685       def allow?(cmdtxt, user, chan=nil)\r
686         if permit?(user, cmdtxt, chan)\r
687           return true\r
688         else\r
689           # cmds = cmdtxt.split('::')\r
690           # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan\r
691           @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %\r
692                         {:user=>user, :command=>cmdtxt} if chan\r
693           return false\r
694         end\r
695       end\r
696 \r
697     end\r
698 \r
699     # Returns the only instance of AuthManagerClass\r
700     #\r
701     def Auth.authmanager\r
702       return AuthManagerClass.instance\r
703     end\r
704 \r
705   end\r
706 \r
707 end\r