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