3 # :title: User management
6 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
7 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta
14 # This would be a good idea if it was failproof, but the truth
15 # is that other methods can indirectly modify the hash. *sigh*
17 # class AuthNotifyingHash < Hash
18 # %w(clear default= delete delete_if replace invert
19 # merge! update rehash reject! replace shift []= store).each { |m|
21 # define_method(m) { |*a|
23 # Irc::Bot::Auth.manager.set_changed
35 # This module contains the actual Authentication stuff
39 Config.register Config::StringValue.new( 'auth.password',
40 :default => 'rbotauth', :wizard => true,
41 :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},
42 :desc => _('Password for the bot owner'))
43 Config.register Config::BooleanValue.new( 'auth.login_by_mask',
45 :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))
46 Config.register Config::BooleanValue.new( 'auth.autologin',
48 :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))
49 Config.register Config::BooleanValue.new( 'auth.autouser',
51 :desc => _('Set true to allow new botusers to be created automatically'))
52 # Config.register Config::IntegerValue.new( 'auth.default_level',
53 # :default => 10, :wizard => true,
54 # :desc => 'The default level for new/unknown users' )
56 # Generate a random password of length _l_
58 def Auth.random_password(l=8)
61 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
67 # An Irc::Bot::Auth::Command defines a command by its "path":
69 # base::command::subcommand::subsubcommand::subsubsubcommand
73 attr_reader :command, :path
75 # A method that checks if a given _cmd_ is in a form that can be
76 # reduced into a canonical command path, and if so, returns it
78 def sanitize_command_path(cmd)
79 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
80 return pre if pre.empty?
81 return pre if pre =~ /^\S+(::\S+)*$/
82 raise TypeError, "#{cmd.inspect} is not a valid command"
85 # Creates a new Command from a given string; you can then access
86 # the command as a symbol with the :command method and the whole
89 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
91 # Command.new("core::auth::save").command => :"core::auth::save"
94 cmdpath = sanitize_command_path(cmd).split('::')
95 seq = cmdpath.inject(["*"]) { |list, cmd|
96 list << (list.length > 1 ? list.last + "::" : "") + cmd
102 debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"
106 def to_irc_auth_command
120 # Returns an Irc::Bot::Auth::Comand from the receiver
121 def to_irc_auth_command
122 Irc::Bot::Auth::Command.new(self)
130 # Returns an Irc::Bot::Auth::Comand from the receiver
131 def to_irc_auth_command
132 Irc::Bot::Auth::Command.new(self)
145 # This class describes a permission set
149 # Create a new (empty) PermissionSet
155 # Inspection simply inspects the internal hash
160 # Sets the permission for command _cmd_ to _val_,
162 def set_permission(str, val)
163 cmd = str.to_irc_auth_command
166 @perm[cmd.command] = val
168 @perm.delete(cmd.command)
170 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
174 # Resets the permission for command _cmd_
176 def reset_permission(cmd)
177 set_permission(cmd, nil)
180 # Tells if command _cmd_ is permitted. We do this by returning
181 # the value of the deepest Command#path that matches.
184 cmd = str.to_irc_auth_command
185 # TODO user-configurable list of always-allowed commands,
186 # for admins that want to set permissions -* for everybody
187 return true if cmd.command == :login
189 cmd.path.reverse.each { |k|
201 # This is the error that gets raised when an invalid password is met
203 class InvalidPassword < RuntimeError
207 # This is the basic class for bot users: they have a username, a
208 # password, a list of netmasks to match against, and a list of
209 # permissions. A BotUser can be marked as 'transient', usually meaning
210 # it's not intended for permanent storage. Transient BotUsers have lower
211 # priority than nontransient ones for autologin purposes.
213 # To initialize a BotUser, you pass a _username_ and an optional
214 # hash of options. Currently, only two options are recognized:
216 # transient:: true or false, determines if the BotUser is transient or
217 # permanent (default is false, permanent BotUser).
219 # Transient BotUsers are initialized by prepending an
220 # asterisk (*) to the username, and appending a sanitized
221 # version of the object_id. The username can be empty.
222 # A random password is generated.
224 # Permanent Botusers need the username as is, and no
225 # password is generated.
227 # masks:: an array of Netmasks to initialize the NetmaskList. This
228 # list is used as-is for permanent BotUsers.
230 # Transient BotUsers will alter the list elements which are
231 # Irc::User by globbing the nick and any initial nonletter
234 # The masks option is optional for permanent BotUsers, but
235 # obligatory (non-empty) for transients.
239 attr_reader :username
240 attr_reader :password
241 attr_reader :netmasks
243 attr_writer :login_by_mask
244 attr_writer :transient
250 @netmasks.each { |n| Auth.manager.maskdb.remove(self, n) }
252 @netmasks.each { |n| Auth.manager.maskdb.add(self, n) }
256 # Checks if the BotUser is transient
261 # Checks if the BotUser is permanent (not transient)
266 # Sets if the BotUser is permanent or not
271 # Make the BotUser permanent
272 def make_permanent(name)
273 raise TypeError, "permanent already" if permanent?
274 @username = BotUser.sanitize_username(name)
277 reset_password # or not?
278 @netmasks.dup.each do |m|
280 add_netmask(m.generalize)
284 # Create a new BotUser with given username
285 def initialize(username, options={})
286 opts = {:transient => false}.merge(options)
287 @transient = opts[:transient]
291 @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?
292 @username << BotUser.sanitize_username(object_id)
297 @username = BotUser.sanitize_username(username)
303 @netmasks = NetmaskList.new
304 if opts.key?(:masks) and opts[:masks]
306 masks = [masks] unless masks.respond_to?(:each)
308 mask = m.to_irc_netmask
309 if @transient and User === m
311 mask.host = m.host.dup
312 mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')
314 add_netmask(mask) unless mask.to_s == "*"
317 raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?
324 str = self.__to_s__[0..-2]
325 str << " (transient)" if @transient
327 str << " @username=#{@username.inspect}"
328 str << " @netmasks=#{@netmasks.inspect}"
329 str << " @perm=#{@perm.inspect}"
330 str << " @login_by_mask=#{@login_by_mask}"
331 str << " @autologin=#{@autologin}"
340 # Convert into a hash
343 :username => @username,
344 :password => @password,
345 :netmasks => @netmasks,
347 :login_by_mask => @login_by_mask,
348 :autologin => @autologin,
352 # Do we allow logging in without providing the password?
358 # Reset the login-by-mask option
360 def reset_login_by_mask
361 @login_by_mask = Auth.manager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
364 # Reset the autologin option
367 @autologin = Auth.manager.bot.config['auth.autologin'] unless defined?(@autologin)
370 # Do we allow automatic logging in?
378 @username = h[:username] if h.has_key?(:username)
379 @password = h[:password] if h.has_key?(:password)
380 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
381 @autologin = h[:autologin] if h.has_key?(:autologin)
382 if h.has_key?(:netmasks)
383 @netmasks = h[:netmasks]
385 @netmasks.each { |n| Auth.manager.maskdb.add(self, n) } if @autologin
388 @perm = h[:perm] if h.has_key?(:perm)
391 # This method sets the password if the proposed new password
393 def password=(pwd=nil)
399 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
400 raise InvalidPassword, "#{pass} too short" if pass.length < 4
402 rescue InvalidPassword => e
405 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
410 # Resets the password by creating a new onw
412 @password = Auth.random_password
415 # Sets the permission for command _cmd_ to _val_ on channel _chan_
417 def set_permission(cmd, val, chan="*")
419 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
420 @perm[k].set_permission(cmd, val)
423 # Resets the permission for command _cmd_ on channel _chan_
425 def reset_permission(cmd, chan ="*")
426 set_permission(cmd, nil, chan)
429 # Checks if BotUser is allowed to do something on channel _chan_,
430 # or on all channels if _chan_ is nil
432 def permit?(cmd, chan=nil)
440 allow = @perm[k].permit?(cmd)
447 def add_netmask(mask)
448 m = mask.to_irc_netmask
451 Auth.manager.maskdb.add(self, m)
452 Auth.manager.logout_transients(m) if self.permanent?
458 def delete_netmask(mask)
459 m = mask.to_irc_netmask
461 Auth.manager.maskdb.remove(self, m) if self.autologin?
464 # Reset Netmasks, clearing @netmasks
468 Auth.manager.maskdb.remove(self, m) if self.autologin?
473 # This method checks if BotUser has a Netmask that matches _user_
476 user = usr.to_irc_user
477 !!@netmasks.find { |n| user.matches? n }
480 # This method gets called when User _user_ wants to log in.
481 # It returns true or false depending on whether the password
482 # is right. If it is, the Netmask of the user is added to the
483 # list of acceptable Netmask unless it's already matched.
484 def login(user, password=nil)
485 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
486 add_netmask(user) unless knows?(user)
487 debug "#{user} logged in as #{self.inspect}"
494 # # This method gets called when User _user_ has logged out as this BotUser
496 # delete_netmask(user) if knows?(user)
499 # This method sanitizes a username by chomping, downcasing
500 # and replacing any nonalphanumeric character with _
502 def BotUser.sanitize_username(name)
503 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
504 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
510 # This is the default BotUser: it's used for all users which haven't
511 # identified with the bot
513 class DefaultBotUserClass < BotUser
515 private :add_netmask, :delete_netmask
519 # The default BotUser is named 'everyone'
525 @default_perm = PermissionSet.new
528 # This method returns without changing anything
530 def login_by_mask=(val)
531 debug "Tried to change the login-by-mask for default bot user, ignoring"
532 return @login_by_mask
535 # The default botuser allows logins by mask
537 def reset_login_by_mask
538 @login_by_mask = true
541 # This method returns without changing anything
544 debug "Tried to change the autologin for default bot user, ignoring"
548 # The default botuser doesn't allow autologin (meaningless)
554 # Sets the default permission for the default user (i.e. the ones
555 # set by the BotModule writers) on all channels
557 def set_default_permission(cmd, val)
558 @default_perm.set_permission(Command.new(cmd), val)
559 debug "Default permissions now: #{@default_perm.pretty_inspect}"
562 # default knows everybody
565 return true if user.to_irc_user
568 # We always allow logging in as the default user
569 def login(user, password)
573 # DefaultBotUser will check the default_perm after checking
575 # or on all channels if _chan_ is nil
577 def permit?(cmd, chan=nil)
578 allow = super(cmd, chan)
579 if allow.nil? && chan.nil?
580 allow = @default_perm.permit?(cmd)
587 # Returns the only instance of DefaultBotUserClass
589 def Auth.defaultbotuser
590 return DefaultBotUserClass.instance
593 # This is the BotOwner: he can do everything
595 class BotOwnerClass < BotUser
600 @login_by_mask = false
605 def permit?(cmd, chan=nil)
611 # Returns the only instance of BotOwnerClass
614 return BotOwnerClass.instance
619 # Check if the current BotUser is the default one
621 return DefaultBotUserClass === self
624 # Check if the current BotUser is the owner
626 return BotOwnerClass === self
631 # This is the ManagerClass singleton, used to manage
632 # Irc::User/Irc::Bot::Auth::BotUser connections and everything
639 attr_reader :everyone
640 attr_reader :botowner
643 # The instance manages two <code>Hash</code>es: one that maps
644 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
645 # usernames onto <code>BotUser</code>
647 @everyone = Auth::defaultbotuser
648 @botowner = Auth::botowner
652 def bot_associate(bot)
653 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
660 # This variable is set to true when there have been changes
661 # to the botusers list, so that we know when to save
680 @maskdb = NetmaskDb.new
681 @allbotusers = Hash.new
682 [everyone, botowner].each do |x|
683 @allbotusers[x.username.to_sym] = x
687 def load_array(ary, forced)
689 warning "Tried to load an empty array"
692 raise "Won't load with unsaved changes" if @has_changes and not forced
695 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
700 get_botuser(u).from_hash(x)
701 get_botuser(u).transient = false
707 @allbotusers.values.map { |x|
708 x.transient? ? nil : x.to_hash
712 # checks if we know about a certain BotUser username
713 def include?(botusername)
714 @allbotusers.has_key?(botusername.to_sym)
717 # Maps <code>Irc::User</code> to BotUser
718 def irc_to_botuser(ircuser)
719 logged = @botusers[ircuser.to_irc_user]
720 return logged if logged
721 return autologin(ircuser)
724 # creates a new BotUser
725 def create_botuser(name, password=nil)
726 n = BotUser.sanitize_username(name)
728 raise "botuser #{n} exists" if include?(k)
730 bu.password = password
735 # returns the botuser with name _name_
736 def get_botuser(name)
737 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
740 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
742 # raises an error if _botusername_ is not a known BotUser username
744 # It is possible to autologin by Netmask, on request
746 def login(user, botusername, pwd=nil)
747 ircuser = user.to_irc_user
748 n = BotUser.sanitize_username(botusername)
750 raise "No such BotUser #{n}" unless include?(k)
751 if @botusers.has_key?(ircuser)
752 return true if @botusers[ircuser].username == n
754 # @botusers[ircuser].logout(ircuser)
757 if bu.login(ircuser, pwd)
758 @botusers[ircuser] = bu
764 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
765 # and trying to login without a password
768 ircuser = user.to_irc_user
769 debug "Trying to autologin #{ircuser}"
770 return @botusers[ircuser] if @botusers.has_key?(ircuser)
771 bu = maskdb.find(ircuser)
774 bu.login(ircuser) or raise '...what?!'
775 @botusers[ircuser] = bu
778 # Finally, create a transient if we're set to allow it
779 if @bot.config['auth.autouser']
780 bu = create_transient_botuser(ircuser)
781 @botusers[ircuser] = bu
787 # Creates a new transient BotUser associated with Irc::User _user_,
788 # automatically logging him in. Note that transient botuser creation can
789 # fail, typically if we don't have the complete user netmask (e.g. for
790 # messages coming in from a linkbot)
792 def create_transient_botuser(user)
793 ircuser = user.to_irc_user
796 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
799 warning "failed to create transient for #{user}"
805 # Logs out any Irc::User matching Irc::Netmask _m_ and logged in
806 # to a transient BotUser
808 def logout_transients(m)
809 debug "to check: #{@botusers.keys.join ' '}"
810 @botusers.keys.each do |iu|
811 debug "checking #{iu.fullform} against #{m.fullform}"
813 bu.transient? or next
814 iu.matches?(m) or next
815 @botusers.delete(iu).autologin = false
819 # Makes transient BotUser _user_ into a permanent BotUser
820 # named _name_; if _user_ is an Irc::User, act on the transient
821 # BotUser (if any) it's logged in as
823 def make_permanent(user, name)
824 buname = BotUser.sanitize_username(name)
825 # TODO merge BotUser instead?
826 raise "there's already a BotUser called #{name}" if include?(buname)
830 when String, Irc::User
831 tuser = irc_to_botuser(user)
835 raise TypeError, "sorry, don't know how to make #{user.class} into a permanent BotUser"
837 return nil unless tuser
838 raise TypeError, "#{tuser} is not transient" unless tuser.transient?
840 tuser.make_permanent(buname)
841 @allbotusers[tuser.username.to_sym] = tuser
846 # Checks if User _user_ can do _cmd_ on _chan_.
848 # Permission are checked in this order, until a true or false
850 # * associated BotUser on _chan_
851 # * associated BotUser on all channels
852 # * everyone on _chan_
853 # * everyone on all channels
855 def permit?(user, cmdtxt, channel=nil)
856 if user.class <= BotUser
859 botuser = irc_to_botuser(user)
861 cmd = cmdtxt.to_irc_auth_command
873 allow = botuser.permit?(cmd, chan) if chan
874 return allow unless allow.nil?
875 allow = botuser.permit?(cmd)
876 return allow unless allow.nil?
878 unless botuser == everyone
879 allow = everyone.permit?(cmd, chan) if chan
880 return allow unless allow.nil?
881 allow = everyone.permit?(cmd)
882 return allow unless allow.nil?
885 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
888 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
889 # telling if the user is authorized
891 def allow?(cmdtxt, user, chan=nil)
892 if permit?(user, cmdtxt, chan)
895 # cmds = cmdtxt.split('::')
896 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
897 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
898 {:user=>user, :command=>cmdtxt} if chan
905 # Returns the only instance of ManagerClass
908 return ManagerClass.instance
916 # A convenience method to automatically found the botuser
917 # associated with the receiver
920 Irc::Bot::Auth.manager.irc_to_botuser(self)