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