3 # :title: User management
\r
5 # rbot user management
\r
6 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
\r
7 # Copyright:: Copyright (c) 2006 Giuseppe Bilotta
\r
13 # This would be a good idea if it was failproof, but the truth
\r
14 # is that other methods can indirectly modify the hash. *sigh*
\r
16 # class AuthNotifyingHash < Hash
\r
17 # %w(clear default= delete delete_if replace invert
\r
18 # merge! update rehash reject! replace shift []= store).each { |m|
\r
20 # define_method(m) { |*a|
\r
22 # Irc::Auth.authmanager.set_changed
\r
33 # This module contains the actual Authentication stuff
\r
37 BotConfig.register BotConfigStringValue.new( 'auth.password',
\r
38 :default => 'rbotauth', :wizard => true,
\r
39 :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},
\r
40 :desc => _('Password for the bot owner'))
\r
41 BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',
\r
43 :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))
\r
44 BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',
\r
46 :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))
\r
47 BotConfig.register BotConfigBooleanValue.new( 'auth.autouser',
\r
48 :default => 'false',
\r
49 :desc => _('Set true to allow new botusers to be created automatically'))
\r
50 # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',
\r
51 # :default => 10, :wizard => true,
\r
52 # :desc => 'The default level for new/unknown users' )
\r
54 # Generate a random password of length _l_
\r
56 def Auth.random_password(l=8)
\r
59 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
\r
65 # An Irc::Auth::Command defines a command by its "path":
\r
67 # base::command::subcommand::subsubcommand::subsubsubcommand
\r
71 attr_reader :command, :path
\r
73 # A method that checks if a given _cmd_ is in a form that can be
\r
74 # reduced into a canonical command path, and if so, returns it
\r
76 def sanitize_command_path(cmd)
\r
77 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
\r
78 return pre if pre.empty?
\r
79 return pre if pre =~ /^\S+(::\S+)*$/
\r
80 raise TypeError, "#{cmd.inspect} is not a valid command"
\r
83 # Creates a new Command from a given string; you can then access
\r
84 # the command as a symbol with the :command method and the whole
\r
87 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
\r
89 # Command.new("core::auth::save").command => :"core::auth::save"
\r
92 cmdpath = sanitize_command_path(cmd).split('::')
\r
93 seq = cmdpath.inject(["*"]) { |list, cmd|
\r
94 list << (list.length > 1 ? list.last + "::" : "") + cmd
\r
96 @path = seq.map { |k|
\r
99 @command = path.last
\r
100 debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"
\r
104 def to_irc_auth_command
\r
117 # Returns an Irc::Auth::Comand from the receiver
\r
118 def to_irc_auth_command
\r
119 Irc::Auth::Command.new(self)
\r
127 # Returns an Irc::Auth::Comand from the receiver
\r
128 def to_irc_auth_command
\r
129 Irc::Auth::Command.new(self)
\r
141 # This class describes a permission set
\r
142 class PermissionSet
\r
145 # Create a new (empty) PermissionSet
\r
151 # Inspection simply inspects the internal hash
\r
156 # Sets the permission for command _cmd_ to _val_,
\r
158 def set_permission(str, val)
\r
159 cmd = str.to_irc_auth_command
\r
162 @perm[cmd.command] = val
\r
164 @perm.delete(cmd.command)
\r
166 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
\r
170 # Resets the permission for command _cmd_
\r
172 def reset_permission(cmd)
\r
173 set_permission(cmd, nil)
\r
176 # Tells if command _cmd_ is permitted. We do this by returning
\r
177 # the value of the deepest Command#path that matches.
\r
180 cmd = str.to_irc_auth_command
\r
182 cmd.path.reverse.each { |k|
\r
183 if @perm.has_key?(k)
\r
194 # This is the error that gets raised when an invalid password is met
\r
196 class InvalidPassword < RuntimeError
\r
200 # This is the basic class for bot users: they have a username, a
\r
201 # password, a list of netmasks to match against, and a list of
\r
202 # permissions. A BotUser can be marked as 'transient', usually meaning
\r
203 # it's not intended for permanent storage. Transient BotUsers have lower
\r
204 # priority than nontransient ones for autologin purposes.
\r
206 # To initialize a BotUser, you pass a _username_ and an optional
\r
207 # hash of options. Currently, only two options are recognized:
\r
209 # transient:: true or false, determines if the BotUser is transient or
\r
210 # permanent (default is false, permanent BotUser).
\r
212 # Transient BotUsers are initialized by prepending an
\r
213 # asterisk (*) to the username, and appending a sanitized
\r
214 # version of the object_id. The username can be empty.
\r
215 # A random password is generated.
\r
217 # Permanent Botusers need the username as is, and no
\r
218 # password is generated.
\r
220 # masks:: an array of Netmasks to initialize the NetmaskList. This
\r
221 # list is used as-is for permanent BotUsers.
\r
223 # Transient BotUsers will alter the list elements which are
\r
224 # Irc::User by globbing the nick and any initial nonletter
\r
225 # part of the ident.
\r
227 # The masks option is optional for permanent BotUsers, but
\r
228 # obligatory (non-empty) for transients.
\r
232 attr_reader :username
\r
233 attr_reader :password
\r
234 attr_reader :netmasks
\r
236 # Please remember to #set_changed() the authmanager
\r
237 # when modifying data
\r
239 attr_writer :login_by_mask
\r
240 attr_writer :autologin
\r
241 attr_writer :transient
\r
243 # Checks if the BotUser is transient
\r
248 # Checks if the BotUser is permanent (not transient)
\r
253 # Sets if the BotUser is permanent or not
\r
254 def permanent=(bool)
\r
258 # Create a new BotUser with given username
\r
259 def initialize(username, options={})
\r
260 opts = {:transient => false}.merge(options)
\r
261 @transient = opts[:transient]
\r
265 @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?
\r
266 @username << BotUser.sanitize_username(object_id)
\r
268 @login_by_mask=true
\r
271 @username = BotUser.sanitize_username(username)
\r
273 reset_login_by_mask
\r
277 @netmasks = NetmaskList.new
\r
278 if opts.key?(:masks) and opts[:masks]
\r
279 masks = opts[:masks]
\r
280 masks = [masks] unless masks.respond_to?(:each)
\r
282 mask = m.to_irc_netmask
\r
283 if @transient and User === m
\r
285 mask.host = m.host.dup
\r
286 mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')
\r
288 add_netmask(mask) unless mask.to_s == "*"
\r
291 raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?
\r
295 # @data = AuthNotifyingHash.new
\r
301 str = "<#{self.class}:#{'0x%08x' % self.object_id}"
\r
302 str << " (transient)" if @transient
\r
304 str << " @username=#{@username.inspect}"
\r
305 str << " @netmasks=#{@netmasks.inspect}"
\r
306 str << " @perm=#{@perm.inspect}"
\r
307 str << " @login_by_mask=#{@login_by_mask}"
\r
308 str << " @autologin=#{@autologin}"
\r
312 str << " data for #{@data.keys.join(', ')}"
\r
322 # Convert into a hash
\r
325 :username => @username,
\r
326 :password => @password,
\r
327 :netmasks => @netmasks,
\r
329 :login_by_mask => @login_by_mask,
\r
330 :autologin => @autologin,
\r
335 # Do we allow logging in without providing the password?
\r
341 # Reset the login-by-mask option
\r
343 def reset_login_by_mask
\r
344 @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
\r
347 # Reset the autologin option
\r
349 def reset_autologin
\r
350 @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)
\r
353 # Do we allow automatic logging in?
\r
359 # Restore from hash
\r
361 @username = h[:username] if h.has_key?(:username)
\r
362 @password = h[:password] if h.has_key?(:password)
\r
363 @netmasks = h[:netmasks] if h.has_key?(:netmasks)
\r
364 @perm = h[:perm] if h.has_key?(:perm)
\r
365 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
\r
366 @autologin = h[:autologin] if h.has_key?(:autologin)
\r
367 @data.replace(h[:data]) if h.has_key?(:data)
\r
370 # This method sets the password if the proposed new password
\r
372 def password=(pwd=nil)
\r
378 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
\r
379 raise InvalidPassword, "#{pass} too short" if pass.length < 4
\r
381 rescue InvalidPassword => e
\r
384 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
\r
389 # Resets the password by creating a new onw
\r
391 @password = Auth.random_password
\r
394 # Sets the permission for command _cmd_ to _val_ on channel _chan_
\r
396 def set_permission(cmd, val, chan="*")
\r
397 k = chan.to_s.to_sym
\r
398 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
\r
399 @perm[k].set_permission(cmd, val)
\r
402 # Resets the permission for command _cmd_ on channel _chan_
\r
404 def reset_permission(cmd, chan ="*")
\r
405 set_permission(cmd, nil, chan)
\r
408 # Checks if BotUser is allowed to do something on channel _chan_,
\r
409 # or on all channels if _chan_ is nil
\r
411 def permit?(cmd, chan=nil)
\r
413 k = chan.to_s.to_sym
\r
418 if @perm.has_key?(k)
\r
419 allow = @perm[k].permit?(cmd)
\r
426 def add_netmask(mask)
\r
427 @netmasks << mask.to_irc_netmask
\r
430 # Removes a Netmask
\r
432 def delete_netmask(mask)
\r
433 m = mask.to_irc_netmask
\r
434 @netmasks.delete(m)
\r
437 # Removes all <code>Netmask</code>s
\r
440 @netmasks = NetmaskList.new
\r
443 # This method checks if BotUser has a Netmask that matches _user_
\r
446 user = usr.to_irc_user
\r
448 @netmasks.each { |n|
\r
449 if user.matches?(n)
\r
457 # This method gets called when User _user_ wants to log in.
\r
458 # It returns true or false depending on whether the password
\r
459 # is right. If it is, the Netmask of the user is added to the
\r
460 # list of acceptable Netmask unless it's already matched.
\r
461 def login(user, password=nil)
\r
462 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
\r
463 add_netmask(user) unless knows?(user)
\r
464 debug "#{user} logged in as #{self.inspect}"
\r
471 # # This method gets called when User _user_ has logged out as this BotUser
\r
473 # delete_netmask(user) if knows?(user)
\r
476 # This method sanitizes a username by chomping, downcasing
\r
477 # and replacing any nonalphanumeric character with _
\r
479 def BotUser.sanitize_username(name)
\r
480 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
\r
481 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
\r
487 # This is the default BotUser: it's used for all users which haven't
\r
488 # identified with the bot
\r
490 class DefaultBotUserClass < BotUser
\r
492 private :add_netmask, :delete_netmask
\r
496 # The default BotUser is named 'everyone'
\r
499 reset_login_by_mask
\r
502 @default_perm = PermissionSet.new
\r
505 # This method returns without changing anything
\r
507 def login_by_mask=(val)
\r
508 debug "Tried to change the login-by-mask for default bot user, ignoring"
\r
509 return @login_by_mask
\r
512 # The default botuser allows logins by mask
\r
514 def reset_login_by_mask
\r
515 @login_by_mask = true
\r
518 # This method returns without changing anything
\r
520 def autologin=(val)
\r
521 debug "Tried to change the autologin for default bot user, ignoring"
\r
525 # The default botuser doesn't allow autologin (meaningless)
\r
527 def reset_autologin
\r
531 # Sets the default permission for the default user (i.e. the ones
\r
532 # set by the BotModule writers) on all channels
\r
534 def set_default_permission(cmd, val)
\r
535 @default_perm.set_permission(Command.new(cmd), val)
\r
536 debug "Default permissions now: #{@default_perm.pretty_inspect}"
\r
539 # default knows everybody
\r
542 return true if user.to_irc_user
\r
545 # We always allow logging in as the default user
\r
546 def login(user, password)
\r
550 # Resets the NetmaskList
\r
553 add_netmask("*!*@*")
\r
556 # DefaultBotUser will check the default_perm after checking
\r
558 # or on all channels if _chan_ is nil
\r
560 def permit?(cmd, chan=nil)
\r
561 allow = super(cmd, chan)
\r
562 if allow.nil? && chan.nil?
\r
563 allow = @default_perm.permit?(cmd)
\r
570 # Returns the only instance of DefaultBotUserClass
\r
572 def Auth.defaultbotuser
\r
573 return DefaultBotUserClass.instance
\r
576 # This is the BotOwner: he can do everything
\r
578 class BotOwnerClass < BotUser
\r
583 @login_by_mask = false
\r
588 def permit?(cmd, chan=nil)
\r
594 # Returns the only instance of BotOwnerClass
\r
597 return BotOwnerClass.instance
\r
601 # This is the AuthManagerClass singleton, used to manage User/BotUser connections and
\r
604 class AuthManagerClass
\r
608 attr_reader :everyone
\r
609 attr_reader :botowner
\r
612 # The instance manages two <code>Hash</code>es: one that maps
\r
613 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
\r
614 # usernames onto <code>BotUser</code>
\r
616 @everyone = Auth::defaultbotuser
\r
617 @botowner = Auth::botowner
\r
621 def bot_associate(bot)
\r
622 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
\r
629 # This variable is set to true when there have been changes
\r
630 # to the botusers list, so that we know when to save
\r
631 @has_changes = false
\r
635 @has_changes = true
\r
639 @has_changes = false
\r
646 # resets the hashes
\r
648 @botusers = Hash.new
\r
649 @allbotusers = Hash.new
\r
650 [everyone, botowner].each { |x|
\r
651 @allbotusers[x.username.to_sym] = x
\r
653 @transients = Set.new
\r
656 def load_array(ary, forced)
\r
658 warning "Tried to load an empty array"
\r
661 raise "Won't load with unsaved changes" if @has_changes and not forced
\r
664 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
\r
669 get_botuser(u).from_hash(x)
\r
670 get_botuser(u).transient = false
\r
676 @allbotusers.values.map { |x|
\r
677 x.transient? ? nil : x.to_hash
\r
681 # checks if we know about a certain BotUser username
\r
682 def include?(botusername)
\r
683 @allbotusers.has_key?(botusername.to_sym)
\r
686 # Maps <code>Irc::User</code> to BotUser
\r
687 def irc_to_botuser(ircuser)
\r
688 logged = @botusers[ircuser.to_irc_user]
\r
689 return logged if logged
\r
690 return autologin(ircuser)
\r
693 # creates a new BotUser
\r
694 def create_botuser(name, password=nil)
\r
695 n = BotUser.sanitize_username(name)
\r
697 raise "botuser #{n} exists" if include?(k)
\r
698 bu = BotUser.new(n)
\r
699 bu.password = password
\r
700 @allbotusers[k] = bu
\r
704 # returns the botuser with name _name_
\r
705 def get_botuser(name)
\r
706 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
\r
709 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
\r
711 # raises an error if _botusername_ is not a known BotUser username
\r
713 # It is possible to autologin by Netmask, on request
\r
715 def login(user, botusername, pwd=nil)
\r
716 ircuser = user.to_irc_user
\r
717 n = BotUser.sanitize_username(botusername)
\r
719 raise "No such BotUser #{n}" unless include?(k)
\r
720 if @botusers.has_key?(ircuser)
\r
721 return true if @botusers[ircuser].username == n
\r
723 # @botusers[ircuser].logout(ircuser)
\r
725 bu = @allbotusers[k]
\r
726 if bu.login(ircuser, pwd)
\r
727 @botusers[ircuser] = bu
\r
733 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
\r
734 # and trying to login without a password
\r
736 def autologin(user)
\r
737 ircuser = user.to_irc_user
\r
738 debug "Trying to autologin #{ircuser}"
\r
739 return @botusers[ircuser] if @botusers.has_key?(ircuser)
\r
740 @allbotusers.each { |n, bu|
\r
741 debug "Checking with #{n}"
\r
742 return bu if bu.autologin? and login(ircuser, n)
\r
744 # Check with transient users
\r
745 @transients.each { |bu|
\r
746 return bu if bu.login(ircuser)
\r
748 # Finally, create a transient if we're set to allow it
\r
749 if @bot.config['auth.autouser']
\r
750 bu = create_transient_botuser(ircuser)
\r
756 # Creates a new transient BotUser associated with Irc::User _user_,
\r
757 # automatically logging him in
\r
759 def create_transient_botuser(user)
\r
760 ircuser = user.to_irc_user
\r
761 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
\r
767 # Checks if User _user_ can do _cmd_ on _chan_.
\r
769 # Permission are checked in this order, until a true or false
\r
771 # * associated BotUser on _chan_
\r
772 # * associated BotUser on all channels
\r
773 # * everyone on _chan_
\r
774 # * everyone on all channels
\r
776 def permit?(user, cmdtxt, channel=nil)
\r
777 if user.class <= BotUser
\r
780 botuser = irc_to_botuser(user)
\r
782 cmd = cmdtxt.to_irc_auth_command
\r
794 allow = botuser.permit?(cmd, chan) if chan
\r
795 return allow unless allow.nil?
\r
796 allow = botuser.permit?(cmd)
\r
797 return allow unless allow.nil?
\r
799 unless botuser == everyone
\r
800 allow = everyone.permit?(cmd, chan) if chan
\r
801 return allow unless allow.nil?
\r
802 allow = everyone.permit?(cmd)
\r
803 return allow unless allow.nil?
\r
806 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
\r
809 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
\r
810 # telling if the user is authorized
\r
812 def allow?(cmdtxt, user, chan=nil)
\r
813 if permit?(user, cmdtxt, chan)
\r
816 # cmds = cmdtxt.split('::')
\r
817 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
\r
818 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
\r
819 {:user=>user, :command=>cmdtxt} if chan
\r
826 # Returns the only instance of AuthManagerClass
\r
828 def Auth.authmanager
\r
829 return AuthManagerClass.instance
\r
836 # A convenience method to automatically found the botuser
\r
837 # associated with the receiver
\r
840 Irc::Auth.authmanager.irc_to_botuser(self)
\r
843 # Bot-specific data can be stored with Irc::Users. This is
\r
844 # internally obtained by storing data to the associated BotUser,
\r
845 # but this is a detail plugin writers shouldn't care about.
\r
846 # bot_data(:key) can be used to retrieve a particular data set.
\r
847 # This method is intended for data retrieval, and if the retrieved
\r
848 # data is modified directly there is no guarantee the changes will
\r
849 # be saved back. Use #set_bot_data() for that.
\r
851 def bot_data(key=nil)
\r
852 return self.botuser.data if key.nil?
\r
853 return self.botuser.data[key]
\r
856 # This method is used to store bot-specific data for the receiver.
\r
857 # If no block is passed, _value_ is stored for the key _key_;
\r
858 # if a block is passed, it will be called with the previous
\r
859 # _key_ value as parameter, and its return value will be stored
\r
860 # as the new value. If _value_ is present in the block form, it
\r
861 # will be used to initialize _key_ if it's missing
\r
863 def set_bot_data(key,value=nil,&block)
\r
864 if not block_given?
\r
865 self.botuser.data[key]=value
\r
866 Irc::Auth.authmanager.set_changed
\r
869 if value and not bot_data.has_key?(key)
\r
870 set_bot_data(key, value)
\r
874 r = yield bot_data(key)
\r
876 Irc::Auth.authmanager.set_changed
\r