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_reader :perm_temp
244 attr_writer :login_by_mask
245 attr_writer :transient
251 @netmasks.each { |n| Auth.manager.maskdb.remove(self, n) }
253 @netmasks.each { |n| Auth.manager.maskdb.add(self, n) }
257 # Checks if the BotUser is transient
262 # Checks if the BotUser is permanent (not transient)
267 # Sets if the BotUser is permanent or not
272 # Make the BotUser permanent
273 def make_permanent(name)
274 raise TypeError, "permanent already" if permanent?
275 @username = BotUser.sanitize_username(name)
278 reset_password # or not?
279 @netmasks.dup.each do |m|
281 add_netmask(m.generalize)
285 # Create a new BotUser with given username
286 def initialize(username, options={})
287 opts = {:transient => false}.merge(options)
288 @transient = opts[:transient]
292 @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?
293 @username << BotUser.sanitize_username(object_id)
298 @username = BotUser.sanitize_username(username)
304 @netmasks = NetmaskList.new
305 if opts.key?(:masks) and opts[:masks]
307 masks = [masks] unless masks.respond_to?(:each)
309 mask = m.to_irc_netmask
310 if @transient and User === m
312 mask.host = m.host.dup
313 mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')
315 add_netmask(mask) unless mask.to_s == "*"
318 raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?
326 str = self.__to_s__[0..-2]
327 str << " (transient)" if @transient
329 str << " @username=#{@username.inspect}"
330 str << " @netmasks=#{@netmasks.inspect}"
331 str << " @perm=#{@perm.inspect}"
332 str << " @perm_temp=#{@perm_temp.inspect}" unless @perm_temp.empty?
333 str << " @login_by_mask=#{@login_by_mask}"
334 str << " @autologin=#{@autologin}"
343 # Convert into a hash
346 :username => @username,
347 :password => @password,
348 :netmasks => @netmasks,
350 :login_by_mask => @login_by_mask,
351 :autologin => @autologin,
355 # Do we allow logging in without providing the password?
361 # Reset the login-by-mask option
363 def reset_login_by_mask
364 @login_by_mask = Auth.manager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
367 # Reset the autologin option
370 @autologin = Auth.manager.bot.config['auth.autologin'] unless defined?(@autologin)
373 # Do we allow automatic logging in?
381 @username = h[:username] if h.has_key?(:username)
382 @password = h[:password] if h.has_key?(:password)
383 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
384 @autologin = h[:autologin] if h.has_key?(:autologin)
385 if h.has_key?(:netmasks)
386 @netmasks = h[:netmasks]
388 @netmasks.each { |n| Auth.manager.maskdb.add(self, n) } if @autologin
391 @perm = h[:perm] if h.has_key?(:perm)
394 # This method sets the password if the proposed new password
396 def password=(pwd=nil)
402 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
403 raise InvalidPassword, "#{pass} too short" if pass.length < 4
405 rescue InvalidPassword => e
408 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
413 # Resets the password by creating a new onw
415 @password = Auth.random_password
418 # Sets the permission for command _cmd_ to _val_ on channel _chan_
420 def set_permission(cmd, val, chan="*")
422 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
423 @perm[k].set_permission(cmd, val)
426 # Resets the permission for command _cmd_ on channel _chan_
428 def reset_permission(cmd, chan ="*")
429 set_permission(cmd, nil, chan)
432 # Sets the temporary permission for command _cmd_ to _val_ on channel _chan_
434 def set_temp_permission(cmd, val, chan="*")
436 @perm_temp[k] = PermissionSet.new unless @perm_temp.has_key?(k)
437 @perm_temp[k].set_permission(cmd, val)
440 # Resets the temporary permission for command _cmd_ on channel _chan_
442 def reset_temp_permission(cmd, chan ="*")
443 set_temp_permission(cmd, nil, chan)
446 # Checks if BotUser is allowed to do something on channel _chan_,
447 # or on all channels if _chan_ is nil
449 def permit?(cmd, chan=nil)
456 pt = @perm.merge @perm_temp
458 allow = pt[k].permit?(cmd)
465 def add_netmask(mask)
466 m = mask.to_irc_netmask
469 Auth.manager.maskdb.add(self, m)
470 Auth.manager.logout_transients(m) if self.permanent?
476 def delete_netmask(mask)
477 m = mask.to_irc_netmask
479 Auth.manager.maskdb.remove(self, m) if self.autologin?
482 # Reset Netmasks, clearing @netmasks
486 Auth.manager.maskdb.remove(self, m) if self.autologin?
491 # This method checks if BotUser has a Netmask that matches _user_
494 user = usr.to_irc_user
495 !!@netmasks.find { |n| user.matches? n }
498 # This method gets called when User _user_ wants to log in.
499 # It returns true or false depending on whether the password
500 # is right. If it is, the Netmask of the user is added to the
501 # list of acceptable Netmask unless it's already matched.
502 def login(user, password=nil)
503 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
504 add_netmask(user) unless knows?(user)
505 debug "#{user} logged in as #{self.inspect}"
512 # # This method gets called when User _user_ has logged out as this BotUser
514 # delete_netmask(user) if knows?(user)
517 # This method sanitizes a username by chomping, downcasing
518 # and replacing any nonalphanumeric character with _
520 def BotUser.sanitize_username(name)
521 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
522 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
528 # This is the default BotUser: it's used for all users which haven't
529 # identified with the bot
531 class DefaultBotUserClass < BotUser
533 private :add_netmask, :delete_netmask
537 # The default BotUser is named 'everyone'
543 @default_perm = PermissionSet.new
546 # This method returns without changing anything
548 def login_by_mask=(val)
549 debug "Tried to change the login-by-mask for default bot user, ignoring"
550 return @login_by_mask
553 # The default botuser allows logins by mask
555 def reset_login_by_mask
556 @login_by_mask = true
559 # This method returns without changing anything
562 debug "Tried to change the autologin for default bot user, ignoring"
566 # The default botuser doesn't allow autologin (meaningless)
572 # Sets the default permission for the default user (i.e. the ones
573 # set by the BotModule writers) on all channels
575 def set_default_permission(cmd, val)
576 @default_perm.set_permission(Command.new(cmd), val)
577 debug "Default permissions now: #{@default_perm.pretty_inspect}"
580 # default knows everybody
583 return true if user.to_irc_user
586 # We always allow logging in as the default user
587 def login(user, password)
591 # DefaultBotUser will check the default_perm after checking
593 # or on all channels if _chan_ is nil
595 def permit?(cmd, chan=nil)
596 allow = super(cmd, chan)
597 if allow.nil? && chan.nil?
598 allow = @default_perm.permit?(cmd)
605 # Returns the only instance of DefaultBotUserClass
607 def Auth.defaultbotuser
608 return DefaultBotUserClass.instance
611 # This is the BotOwner: he can do everything
613 class BotOwnerClass < BotUser
618 @login_by_mask = false
623 def permit?(cmd, chan=nil)
629 # Returns the only instance of BotOwnerClass
632 return BotOwnerClass.instance
637 # Check if the current BotUser is the default one
639 return DefaultBotUserClass === self
642 # Check if the current BotUser is the owner
644 return BotOwnerClass === self
649 # This is the ManagerClass singleton, used to manage
650 # Irc::User/Irc::Bot::Auth::BotUser connections and everything
657 attr_reader :everyone
658 attr_reader :botowner
661 # The instance manages two <code>Hash</code>es: one that maps
662 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
663 # usernames onto <code>BotUser</code>
665 @everyone = Auth::defaultbotuser
666 @botowner = Auth::botowner
670 def bot_associate(bot)
671 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
678 # This variable is set to true when there have been changes
679 # to the botusers list, so that we know when to save
698 @maskdb = NetmaskDb.new
699 @allbotusers = Hash.new
700 [everyone, botowner].each do |x|
701 @allbotusers[x.username.to_sym] = x
705 def load_array(ary, forced)
707 warning "Tried to load an empty array"
710 raise "Won't load with unsaved changes" if @has_changes and not forced
713 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
718 get_botuser(u).from_hash(x)
719 get_botuser(u).transient = false
725 @allbotusers.values.map { |x|
726 x.transient? ? nil : x.to_hash
730 # checks if we know about a certain BotUser username
731 def include?(botusername)
732 @allbotusers.has_key?(botusername.to_sym)
735 # Maps <code>Irc::User</code> to BotUser
736 def irc_to_botuser(ircuser)
737 logged = @botusers[ircuser.to_irc_user]
738 return logged if logged
739 return autologin(ircuser)
742 # creates a new BotUser
743 def create_botuser(name, password=nil)
744 n = BotUser.sanitize_username(name)
746 raise "botuser #{n} exists" if include?(k)
748 bu.password = password
753 # returns the botuser with name _name_
754 def get_botuser(name)
755 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
758 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
760 # raises an error if _botusername_ is not a known BotUser username
762 # It is possible to autologin by Netmask, on request
764 def login(user, botusername, pwd=nil)
765 ircuser = user.to_irc_user
766 n = BotUser.sanitize_username(botusername)
768 raise "No such BotUser #{n}" unless include?(k)
769 if @botusers.has_key?(ircuser)
770 return true if @botusers[ircuser].username == n
772 # @botusers[ircuser].logout(ircuser)
775 if bu.login(ircuser, pwd)
776 @botusers[ircuser] = bu
782 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
783 # and trying to login without a password
786 ircuser = user.to_irc_user
787 debug "Trying to autologin #{ircuser}"
788 return @botusers[ircuser] if @botusers.has_key?(ircuser)
789 bu = maskdb.find(ircuser)
792 bu.login(ircuser) or raise '...what?!'
793 @botusers[ircuser] = bu
796 # Finally, create a transient if we're set to allow it
797 if @bot.config['auth.autouser']
798 bu = create_transient_botuser(ircuser)
799 @botusers[ircuser] = bu
805 # Creates a new transient BotUser associated with Irc::User _user_,
806 # automatically logging him in. Note that transient botuser creation can
807 # fail, typically if we don't have the complete user netmask (e.g. for
808 # messages coming in from a linkbot)
810 def create_transient_botuser(user)
811 ircuser = user.to_irc_user
814 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
817 warning "failed to create transient for #{user}"
823 # Logs out any Irc::User matching Irc::Netmask _m_ and logged in
824 # to a transient BotUser
826 def logout_transients(m)
827 debug "to check: #{@botusers.keys.join ' '}"
828 @botusers.keys.each do |iu|
829 debug "checking #{iu.fullform} against #{m.fullform}"
831 bu.transient? or next
832 iu.matches?(m) or next
833 @botusers.delete(iu).autologin = false
837 # Makes transient BotUser _user_ into a permanent BotUser
838 # named _name_; if _user_ is an Irc::User, act on the transient
839 # BotUser (if any) it's logged in as
841 def make_permanent(user, name)
842 buname = BotUser.sanitize_username(name)
843 # TODO merge BotUser instead?
844 raise "there's already a BotUser called #{name}" if include?(buname)
848 when String, Irc::User
849 tuser = irc_to_botuser(user)
853 raise TypeError, "sorry, don't know how to make #{user.class} into a permanent BotUser"
855 return nil unless tuser
856 raise TypeError, "#{tuser} is not transient" unless tuser.transient?
858 tuser.make_permanent(buname)
859 @allbotusers[tuser.username.to_sym] = tuser
864 # Checks if User _user_ can do _cmd_ on _chan_.
866 # Permission are checked in this order, until a true or false
868 # * associated BotUser on _chan_
869 # * associated BotUser on all channels
870 # * everyone on _chan_
871 # * everyone on all channels
873 def permit?(user, cmdtxt, channel=nil)
874 if user.class <= BotUser
877 botuser = irc_to_botuser(user)
879 cmd = cmdtxt.to_irc_auth_command
891 allow = botuser.permit?(cmd, chan) if chan
892 return allow unless allow.nil?
893 allow = botuser.permit?(cmd)
894 return allow unless allow.nil?
896 unless botuser == everyone
897 allow = everyone.permit?(cmd, chan) if chan
898 return allow unless allow.nil?
899 allow = everyone.permit?(cmd)
900 return allow unless allow.nil?
903 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
906 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
907 # telling if the user is authorized
909 def allow?(cmdtxt, user, chan=nil)
910 if permit?(user, cmdtxt, chan)
913 # cmds = cmdtxt.split('::')
914 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
915 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
916 {:user=>user, :command=>cmdtxt} if chan
923 # Returns the only instance of ManagerClass
926 return ManagerClass.instance
934 # A convenience method to automatically found the botuser
935 # associated with the receiver
938 Irc::Bot::Auth.manager.irc_to_botuser(self)