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