3 # :title: User management
6 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
12 # This would be a good idea if it was failproof, but the truth
13 # is that other methods can indirectly modify the hash. *sigh*
15 # class AuthNotifyingHash < Hash
16 # %w(clear default= delete delete_if replace invert
17 # merge! update rehash reject! replace shift []= store).each { |m|
19 # define_method(m) { |*a|
21 # Irc::Bot::Auth.manager.set_changed
33 # This module contains the actual Authentication stuff
37 Config.register Config::StringValue.new( 'auth.password',
38 :default => [*?a..?z,*?A..?Z,*?0..?9].sample(8).join, :store_default => true,
40 :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},
41 :desc => _('Password for the bot owner'))
42 Config.register Config::BooleanValue.new( 'auth.login_by_mask',
44 :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))
45 Config.register Config::BooleanValue.new( 'auth.autologin',
47 :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))
48 Config.register Config::BooleanValue.new( 'auth.autouser',
50 :desc => _('Set true to allow new botusers to be created automatically'))
51 # Config.register Config::IntegerValue.new( 'auth.default_level',
52 # :default => 10, :wizard => true,
53 # :desc => 'The default level for new/unknown users' )
55 # Generate a random password of length _l_
57 def Auth.random_password(l=8)
60 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
66 # An Irc::Bot::Auth::Command defines a command by its "path":
68 # base::command::subcommand::subsubcommand::subsubsubcommand
72 attr_reader :command, :path
74 # A method that checks if a given _cmd_ is in a form that can be
75 # reduced into a canonical command path, and if so, returns it
77 def sanitize_command_path(cmd)
78 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
79 return pre if pre.empty?
80 return pre if pre =~ /^\S+(::\S+)*$/
81 raise TypeError, "#{cmd.inspect} is not a valid command"
84 # Creates a new Command from a given string; you can then access
85 # the command as a symbol with the :command method and the whole
88 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
90 # Command.new("core::auth::save").command => :"core::auth::save"
93 cmdpath = sanitize_command_path(cmd).split('::')
94 seq = cmdpath.inject(["*"]) { |list, cc|
95 list << (list.length > 1 ? list.last + "::" : "") + cc
101 debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"
105 def to_irc_auth_command
119 # Returns an Irc::Bot::Auth::Comand from the receiver
120 def to_irc_auth_command
121 Irc::Bot::Auth::Command.new(self)
129 # Returns an Irc::Bot::Auth::Comand from the receiver
130 def to_irc_auth_command
131 Irc::Bot::Auth::Command.new(self)
144 # This class describes a permission set
148 # Create a new (empty) PermissionSet
154 # Inspection simply inspects the internal hash
159 # Sets the permission for command _cmd_ to _val_,
161 def set_permission(str, val)
162 cmd = str.to_irc_auth_command
165 @perm[cmd.command] = val
167 @perm.delete(cmd.command)
169 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
173 # Resets the permission for command _cmd_
175 def reset_permission(cmd)
176 set_permission(cmd, nil)
179 # Tells if command _cmd_ is permitted. We do this by returning
180 # the value of the deepest Command#path that matches.
183 cmd = str.to_irc_auth_command
184 # TODO user-configurable list of always-allowed commands,
185 # for admins that want to set permissions -* for everybody
186 return true if cmd.command == :login
188 cmd.path.reverse.each { |k|
200 # This is the error that gets raised when an invalid password is met
202 class InvalidPassword < RuntimeError
206 # This is the basic class for bot users: they have a username, a
207 # password, a list of netmasks to match against, and a list of
208 # permissions. A BotUser can be marked as 'transient', usually meaning
209 # it's not intended for permanent storage. Transient BotUsers have lower
210 # priority than nontransient ones for autologin purposes.
212 # To initialize a BotUser, you pass a _username_ and an optional
213 # hash of options. Currently, only two options are recognized:
215 # transient:: true or false, determines if the BotUser is transient or
216 # permanent (default is false, permanent BotUser).
218 # Transient BotUsers are initialized by prepending an
219 # asterisk (*) to the username, and appending a sanitized
220 # version of the object_id. The username can be empty.
221 # A random password is generated.
223 # Permanent Botusers need the username as is, and no
224 # password is generated.
226 # masks:: an array of Netmasks to initialize the NetmaskList. This
227 # list is used as-is for permanent BotUsers.
229 # Transient BotUsers will alter the list elements which are
230 # Irc::User by globbing the nick and any initial nonletter
233 # The masks option is optional for permanent BotUsers, but
234 # obligatory (non-empty) for transients.
238 attr_reader :username
239 attr_reader :password
240 attr_reader :netmasks
242 attr_reader :perm_temp
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?
325 str = self.__to_s__[0..-2]
326 str << " (transient)" if @transient
328 str << " @username=#{@username.inspect}"
329 str << " @netmasks=#{@netmasks.inspect}"
330 str << " @perm=#{@perm.inspect}"
331 str << " @perm_temp=#{@perm_temp.inspect}" unless @perm_temp.empty?
332 str << " @login_by_mask=#{@login_by_mask}"
333 str << " @autologin=#{@autologin}"
342 # Convert into a hash
345 :username => @username,
346 :password => @password,
347 :netmasks => @netmasks,
349 :login_by_mask => @login_by_mask,
350 :autologin => @autologin,
354 # Do we allow logging in without providing the password?
360 # Reset the login-by-mask option
362 def reset_login_by_mask
363 @login_by_mask = Auth.manager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
366 # Reset the autologin option
369 @autologin = Auth.manager.bot.config['auth.autologin'] unless defined?(@autologin)
372 # Do we allow automatic logging in?
380 @username = h[:username] if h.has_key?(:username)
381 @password = h[:password] if h.has_key?(:password)
382 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
383 @autologin = h[:autologin] if h.has_key?(:autologin)
384 if h.has_key?(:netmasks)
385 @netmasks = h[:netmasks]
387 @netmasks.each { |n| Auth.manager.maskdb.add(self, n) } if @autologin
390 @perm = h[:perm] if h.has_key?(:perm)
393 # This method sets the password if the proposed new password
395 def password=(pwd=nil)
401 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
402 raise InvalidPassword, "#{pass} too short" if pass.length < 4
404 rescue InvalidPassword => e
407 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
412 # Resets the password by creating a new onw
414 @password = Auth.random_password
417 # Sets the permission for command _cmd_ to _val_ on channel _chan_
419 def set_permission(cmd, val, chan="*")
421 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
422 @perm[k].set_permission(cmd, val)
425 # Resets the permission for command _cmd_ on channel _chan_
427 def reset_permission(cmd, chan ="*")
428 set_permission(cmd, nil, chan)
431 # Sets the temporary permission for command _cmd_ to _val_ on channel _chan_
433 def set_temp_permission(cmd, val, chan="*")
435 @perm_temp[k] = PermissionSet.new unless @perm_temp.has_key?(k)
436 @perm_temp[k].set_permission(cmd, val)
439 # Resets the temporary permission for command _cmd_ on channel _chan_
441 def reset_temp_permission(cmd, chan ="*")
442 set_temp_permission(cmd, nil, chan)
445 # Checks if BotUser is allowed to do something on channel _chan_,
446 # or on all channels if _chan_ is nil
448 def permit?(cmd, chan=nil)
455 pt = @perm.merge @perm_temp
457 allow = pt[k].permit?(cmd)
464 def add_netmask(mask)
465 m = mask.to_irc_netmask
468 Auth.manager.maskdb.add(self, m)
469 Auth.manager.logout_transients(m) if self.permanent?
475 def delete_netmask(mask)
476 m = mask.to_irc_netmask
478 Auth.manager.maskdb.remove(self, m) if self.autologin?
481 # Reset Netmasks, clearing @netmasks
485 Auth.manager.maskdb.remove(self, m) if self.autologin?
490 # This method checks if BotUser has a Netmask that matches _user_
493 user = usr.to_irc_user
494 !!@netmasks.find { |n| user.matches? n }
497 # This method gets called when User _user_ wants to log in.
498 # It returns true or false depending on whether the password
499 # is right. If it is, the Netmask of the user is added to the
500 # list of acceptable Netmask unless it's already matched.
501 def login(user, password=nil)
502 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
503 add_netmask(user) unless knows?(user)
504 debug "#{user} logged in as #{self.inspect}"
511 # # This method gets called when User _user_ has logged out as this BotUser
513 # delete_netmask(user) if knows?(user)
516 # This method sanitizes a username by chomping, downcasing
517 # and replacing any nonalphanumeric character with _
519 def BotUser.sanitize_username(name)
520 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
521 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
527 # This is the default BotUser: it's used for all users which haven't
528 # identified with the bot
530 class DefaultBotUserClass < BotUser
532 private :add_netmask, :delete_netmask
536 # The default BotUser is named 'everyone'
542 @default_perm = PermissionSet.new
545 # This method returns without changing anything
547 def login_by_mask=(val)
548 debug "Tried to change the login-by-mask for default bot user, ignoring"
549 return @login_by_mask
552 # The default botuser allows logins by mask
554 def reset_login_by_mask
555 @login_by_mask = true
558 # This method returns without changing anything
561 debug "Tried to change the autologin for default bot user, ignoring"
565 # The default botuser doesn't allow autologin (meaningless)
571 # Sets the default permission for the default user (i.e. the ones
572 # set by the BotModule writers) on all channels
574 def set_default_permission(cmd, val)
575 @default_perm.set_permission(Command.new(cmd), val)
576 debug "Default permissions now: #{@default_perm.pretty_inspect}"
579 # default knows everybody
582 return true if user.to_irc_user
585 # We always allow logging in as the default user
586 def login(user, password)
590 # DefaultBotUser will check the default_perm after checking
592 # or on all channels if _chan_ is nil
594 def permit?(cmd, chan=nil)
595 allow = super(cmd, chan)
596 if allow.nil? && chan.nil?
597 allow = @default_perm.permit?(cmd)
604 # Returns the only instance of DefaultBotUserClass
606 def Auth.defaultbotuser
607 return DefaultBotUserClass.instance
610 # This is the BotOwner: he can do everything
612 class BotOwnerClass < BotUser
617 @login_by_mask = false
622 def permit?(cmd, chan=nil)
628 # Returns the only instance of BotOwnerClass
631 return BotOwnerClass.instance
636 # Check if the current BotUser is the default one
638 return DefaultBotUserClass === self
641 # Check if the current BotUser is the owner
643 return BotOwnerClass === self
648 # This is the ManagerClass singleton, used to manage
649 # Irc::User/Irc::Bot::Auth::BotUser connections and everything
656 attr_reader :everyone
657 attr_reader :botowner
660 # The instance manages two <code>Hash</code>es: one that maps
661 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
662 # usernames onto <code>BotUser</code>
664 @everyone = Auth::defaultbotuser
665 @botowner = Auth::botowner
669 def bot_associate(bot)
670 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
677 # This variable is set to true when there have been changes
678 # to the botusers list, so that we know when to save
697 @maskdb = NetmaskDb.new
698 @allbotusers = Hash.new
699 [everyone, botowner].each do |x|
700 @allbotusers[x.username.to_sym] = x
704 def load_array(ary, forced)
706 warning "Tried to load an empty array"
709 raise "Won't load with unsaved changes" if @has_changes and not forced
712 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
717 get_botuser(u).from_hash(x)
718 get_botuser(u).transient = false
724 @allbotusers.values.map { |x|
725 x.transient? ? nil : x.to_hash
729 # checks if we know about a certain BotUser username
730 def include?(botusername)
731 @allbotusers.has_key?(botusername.to_sym)
734 # Maps <code>Irc::User</code> to BotUser
735 def irc_to_botuser(ircuser)
736 logged = @botusers[ircuser.to_irc_user]
737 return logged if logged
738 return autologin(ircuser)
741 # creates a new BotUser
742 def create_botuser(name, password=nil)
743 n = BotUser.sanitize_username(name)
745 raise "botuser #{n} exists" if include?(k)
747 bu.password = password
752 # returns the botuser with name _name_
753 def get_botuser(name)
754 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
757 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
759 # raises an error if _botusername_ is not a known BotUser username
761 # It is possible to autologin by Netmask, on request
763 def login(user, botusername, pwd=nil)
764 ircuser = user.to_irc_user
765 n = BotUser.sanitize_username(botusername)
767 raise "No such BotUser #{n}" unless include?(k)
768 if @botusers.has_key?(ircuser)
769 return true if @botusers[ircuser].username == n
771 # @botusers[ircuser].logout(ircuser)
774 if bu.login(ircuser, pwd)
775 @botusers[ircuser] = bu
781 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
782 # and trying to login without a password
785 ircuser = user.to_irc_user
786 debug "Trying to autologin #{ircuser}"
787 return @botusers[ircuser] if @botusers.has_key?(ircuser)
788 bu = maskdb.find(ircuser)
791 bu.login(ircuser) or raise '...what?!'
792 @botusers[ircuser] = bu
795 # Finally, create a transient if we're set to allow it
796 if @bot.config['auth.autouser']
797 bu = create_transient_botuser(ircuser)
798 @botusers[ircuser] = bu
804 # Creates a new transient BotUser associated with Irc::User _user_,
805 # automatically logging him in. Note that transient botuser creation can
806 # fail, typically if we don't have the complete user netmask (e.g. for
807 # messages coming in from a linkbot)
809 def create_transient_botuser(user)
810 ircuser = user.to_irc_user
813 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
816 warning "failed to create transient for #{user}"
822 # Logs out any Irc::User matching Irc::Netmask _m_ and logged in
823 # to a transient BotUser
825 def logout_transients(m)
826 debug "to check: #{@botusers.keys.join ' '}"
827 @botusers.keys.each do |iu|
828 debug "checking #{iu.fullform} against #{m.fullform}"
830 bu.transient? or next
831 iu.matches?(m) or next
832 @botusers.delete(iu).autologin = false
836 # Makes transient BotUser _user_ into a permanent BotUser
837 # named _name_; if _user_ is an Irc::User, act on the transient
838 # BotUser (if any) it's logged in as
840 def make_permanent(user, name)
841 buname = BotUser.sanitize_username(name)
842 # TODO merge BotUser instead?
843 raise "there's already a BotUser called #{name}" if include?(buname)
847 when String, Irc::User
848 tuser = irc_to_botuser(user)
852 raise TypeError, "sorry, don't know how to make #{user.class} into a permanent BotUser"
854 return nil unless tuser
855 raise TypeError, "#{tuser} is not transient" unless tuser.transient?
857 tuser.make_permanent(buname)
858 @allbotusers[tuser.username.to_sym] = tuser
863 # Checks if User _user_ can do _cmd_ on _chan_.
865 # Permission are checked in this order, until a true or false
867 # * associated BotUser on _chan_
868 # * associated BotUser on all channels
869 # * everyone on _chan_
870 # * everyone on all channels
872 def permit?(user, cmdtxt, channel=nil)
873 if user.class <= BotUser
876 botuser = user.botuser
878 cmd = cmdtxt.to_irc_auth_command
890 allow = botuser.permit?(cmd, chan) if chan
891 return allow unless allow.nil?
892 allow = botuser.permit?(cmd)
893 return allow unless allow.nil?
895 unless botuser == everyone
896 allow = everyone.permit?(cmd, chan) if chan
897 return allow unless allow.nil?
898 allow = everyone.permit?(cmd)
899 return allow unless allow.nil?
902 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
905 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
906 # telling if the user is authorized
908 def allow?(cmdtxt, user, chan=nil)
909 if permit?(user, cmdtxt, chan)
912 # cmds = cmdtxt.split('::')
913 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
914 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
915 {:user=>user, :command=>cmdtxt} if chan
922 # Returns the only instance of ManagerClass
925 return ManagerClass.instance
933 # A convenience method to automatically found the botuser
934 # associated with the receiver
937 Irc::Bot::Auth.manager.irc_to_botuser(self)