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