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