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