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
237 attr_writer :login_by_mask
\r
238 attr_writer :autologin
\r
239 attr_writer :transient
\r
241 # Checks if the BotUser is transient
\r
246 # Checks if the BotUser is permanent (not transient)
\r
251 # Sets if the BotUser is permanent or not
\r
252 def permanent=(bool)
\r
256 # Create a new BotUser with given username
\r
257 def initialize(username, options={})
\r
258 opts = {:transient => false}.merge(options)
\r
259 @transient = opts[:transient]
\r
263 @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?
\r
264 @username << BotUser.sanitize_username(object_id)
\r
266 @login_by_mask=true
\r
269 @username = BotUser.sanitize_username(username)
\r
271 reset_login_by_mask
\r
275 @netmasks = NetmaskList.new
\r
276 if opts.key?(:masks) and opts[:masks]
\r
277 masks = opts[:masks]
\r
278 masks = [masks] unless masks.respond_to?(:each)
\r
280 mask = m.to_irc_netmask
\r
281 if @transient and User === m
\r
283 mask.host = m.host.dup
\r
284 mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')
\r
286 add_netmask(mask) unless mask.to_s == "*"
\r
289 raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?
\r
293 # @data = AuthNotifyingHash.new
\r
299 str = "<#{self.class}:#{'0x%08x' % self.object_id}"
\r
300 str << " (transient)" if @transient
\r
302 str << " @username=#{@username.inspect}"
\r
303 str << " @netmasks=#{@netmasks.inspect}"
\r
304 str << " @perm=#{@perm.inspect}"
\r
305 str << " @login_by_mask=#{@login_by_mask}"
\r
306 str << " @autologin=#{@autologin}"
\r
310 str << " data for #{@data.keys.join(', ')}"
\r
320 # Convert into a hash
\r
323 :username => @username,
\r
324 :password => @password,
\r
325 :netmasks => @netmasks,
\r
327 :login_by_mask => @login_by_mask,
\r
328 :autologin => @autologin,
\r
333 # Do we allow logging in without providing the password?
\r
339 # Reset the login-by-mask option
\r
341 def reset_login_by_mask
\r
342 @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
\r
345 # Reset the autologin option
\r
347 def reset_autologin
\r
348 @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)
\r
351 # Do we allow automatic logging in?
\r
357 # Restore from hash
\r
359 @username = h[:username] if h.has_key?(:username)
\r
360 @password = h[:password] if h.has_key?(:password)
\r
361 @netmasks = h[:netmasks] if h.has_key?(:netmasks)
\r
362 @perm = h[:perm] if h.has_key?(:perm)
\r
363 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
\r
364 @autologin = h[:autologin] if h.has_key?(:autologin)
\r
365 @data.replace(h[:data]) if h.has_key?(:data)
\r
368 # This method sets the password if the proposed new password
\r
370 def password=(pwd=nil)
\r
376 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
\r
377 raise InvalidPassword, "#{pass} too short" if pass.length < 4
\r
379 rescue InvalidPassword => e
\r
382 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
\r
387 # Resets the password by creating a new onw
\r
389 @password = Auth.random_password
\r
392 # Sets the permission for command _cmd_ to _val_ on channel _chan_
\r
394 def set_permission(cmd, val, chan="*")
\r
395 k = chan.to_s.to_sym
\r
396 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
\r
397 @perm[k].set_permission(cmd, val)
\r
400 # Resets the permission for command _cmd_ on channel _chan_
\r
402 def reset_permission(cmd, chan ="*")
\r
403 set_permission(cmd, nil, chan)
\r
406 # Checks if BotUser is allowed to do something on channel _chan_,
\r
407 # or on all channels if _chan_ is nil
\r
409 def permit?(cmd, chan=nil)
\r
411 k = chan.to_s.to_sym
\r
416 if @perm.has_key?(k)
\r
417 allow = @perm[k].permit?(cmd)
\r
424 def add_netmask(mask)
\r
425 @netmasks << mask.to_irc_netmask
\r
428 # Removes a Netmask
\r
430 def delete_netmask(mask)
\r
431 m = mask.to_irc_netmask
\r
432 @netmasks.delete(m)
\r
435 # Removes all <code>Netmask</code>s
\r
438 @netmasks = NetmaskList.new
\r
441 # This method checks if BotUser has a Netmask that matches _user_
\r
444 user = usr.to_irc_user
\r
446 @netmasks.each { |n|
\r
447 if user.matches?(n)
\r
455 # This method gets called when User _user_ wants to log in.
\r
456 # It returns true or false depending on whether the password
\r
457 # is right. If it is, the Netmask of the user is added to the
\r
458 # list of acceptable Netmask unless it's already matched.
\r
459 def login(user, password=nil)
\r
460 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
\r
461 add_netmask(user) unless knows?(user)
\r
462 debug "#{user} logged in as #{self.inspect}"
\r
469 # # This method gets called when User _user_ has logged out as this BotUser
\r
471 # delete_netmask(user) if knows?(user)
\r
474 # This method sanitizes a username by chomping, downcasing
\r
475 # and replacing any nonalphanumeric character with _
\r
477 def BotUser.sanitize_username(name)
\r
478 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
\r
479 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
\r
485 # This is the default BotUser: it's used for all users which haven't
\r
486 # identified with the bot
\r
488 class DefaultBotUserClass < BotUser
\r
490 private :add_netmask, :delete_netmask
\r
494 # The default BotUser is named 'everyone'
\r
497 reset_login_by_mask
\r
500 @default_perm = PermissionSet.new
\r
503 # This method returns without changing anything
\r
505 def login_by_mask=(val)
\r
506 debug "Tried to change the login-by-mask for default bot user, ignoring"
\r
507 return @login_by_mask
\r
510 # The default botuser allows logins by mask
\r
512 def reset_login_by_mask
\r
513 @login_by_mask = true
\r
516 # This method returns without changing anything
\r
518 def autologin=(val)
\r
519 debug "Tried to change the autologin for default bot user, ignoring"
\r
523 # The default botuser doesn't allow autologin (meaningless)
\r
525 def reset_autologin
\r
529 # Sets the default permission for the default user (i.e. the ones
\r
530 # set by the BotModule writers) on all channels
\r
532 def set_default_permission(cmd, val)
\r
533 @default_perm.set_permission(Command.new(cmd), val)
\r
534 debug "Default permissions now: #{@default_perm.pretty_inspect}"
\r
537 # default knows everybody
\r
540 return true if user.to_irc_user
\r
543 # We always allow logging in as the default user
\r
544 def login(user, password)
\r
548 # Resets the NetmaskList
\r
551 add_netmask("*!*@*")
\r
554 # DefaultBotUser will check the default_perm after checking
\r
556 # or on all channels if _chan_ is nil
\r
558 def permit?(cmd, chan=nil)
\r
559 allow = super(cmd, chan)
\r
560 if allow.nil? && chan.nil?
\r
561 allow = @default_perm.permit?(cmd)
\r
568 # Returns the only instance of DefaultBotUserClass
\r
570 def Auth.defaultbotuser
\r
571 return DefaultBotUserClass.instance
\r
574 # This is the BotOwner: he can do everything
\r
576 class BotOwnerClass < BotUser
\r
581 @login_by_mask = false
\r
586 def permit?(cmd, chan=nil)
\r
592 # Returns the only instance of BotOwnerClass
\r
595 return BotOwnerClass.instance
\r
599 # This is the AuthManagerClass singleton, used to manage User/BotUser connections and
\r
602 class AuthManagerClass
\r
606 attr_reader :everyone
\r
607 attr_reader :botowner
\r
610 # The instance manages two <code>Hash</code>es: one that maps
\r
611 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
\r
612 # usernames onto <code>BotUser</code>
\r
614 @everyone = Auth::defaultbotuser
\r
615 @botowner = Auth::botowner
\r
619 def bot_associate(bot)
\r
620 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
\r
627 # This variable is set to true when there have been changes
\r
628 # to the botusers list, so that we know when to save
\r
629 @has_changes = false
\r
633 @has_changes = true
\r
637 @has_changes = false
\r
644 # resets the hashes
\r
646 @botusers = Hash.new
\r
647 @allbotusers = Hash.new
\r
648 [everyone, botowner].each { |x|
\r
649 @allbotusers[x.username.to_sym] = x
\r
651 @transients = Set.new
\r
654 def load_array(ary, forced)
\r
656 warning "Tried to load an empty array"
\r
659 raise "Won't load with unsaved changes" if @has_changes and not forced
\r
662 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
\r
667 get_botuser(u).from_hash(x)
\r
668 get_botuser(u).transient = false
\r
674 @allbotusers.values.map { |x|
\r
675 x.transient? ? nil : x.to_hash
\r
679 # checks if we know about a certain BotUser username
\r
680 def include?(botusername)
\r
681 @allbotusers.has_key?(botusername.to_sym)
\r
684 # Maps <code>Irc::User</code> to BotUser
\r
685 def irc_to_botuser(ircuser)
\r
686 logged = @botusers[ircuser.to_irc_user]
\r
687 return logged if logged
\r
688 return autologin(ircuser)
\r
691 # creates a new BotUser
\r
692 def create_botuser(name, password=nil)
\r
693 n = BotUser.sanitize_username(name)
\r
695 raise "botuser #{n} exists" if include?(k)
\r
696 bu = BotUser.new(n)
\r
697 bu.password = password
\r
698 @allbotusers[k] = bu
\r
702 # returns the botuser with name _name_
\r
703 def get_botuser(name)
\r
704 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
\r
707 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
\r
709 # raises an error if _botusername_ is not a known BotUser username
\r
711 # It is possible to autologin by Netmask, on request
\r
713 def login(user, botusername, pwd=nil)
\r
714 ircuser = user.to_irc_user
\r
715 n = BotUser.sanitize_username(botusername)
\r
717 raise "No such BotUser #{n}" unless include?(k)
\r
718 if @botusers.has_key?(ircuser)
\r
719 return true if @botusers[ircuser].username == n
\r
721 # @botusers[ircuser].logout(ircuser)
\r
723 bu = @allbotusers[k]
\r
724 if bu.login(ircuser, pwd)
\r
725 @botusers[ircuser] = bu
\r
731 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
\r
732 # and trying to login without a password
\r
734 def autologin(user)
\r
735 ircuser = user.to_irc_user
\r
736 debug "Trying to autologin #{ircuser}"
\r
737 return @botusers[ircuser] if @botusers.has_key?(ircuser)
\r
738 @allbotusers.each { |n, bu|
\r
739 debug "Checking with #{n}"
\r
740 return bu if bu.autologin? and login(ircuser, n)
\r
742 # Check with transient users
\r
743 @transients.each { |bu|
\r
744 return bu if bu.login(ircuser)
\r
746 # Finally, create a transient if we're set to allow it
\r
747 if @bot.config['auth.autouser']
\r
748 bu = create_transient_botuser(ircuser)
\r
754 # Creates a new transient BotUser associated with Irc::User _user_,
\r
755 # automatically logging him in
\r
757 def create_transient_botuser(user)
\r
758 ircuser = user.to_irc_user
\r
759 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
\r
765 # Checks if User _user_ can do _cmd_ on _chan_.
\r
767 # Permission are checked in this order, until a true or false
\r
769 # * associated BotUser on _chan_
\r
770 # * associated BotUser on all channels
\r
771 # * everyone on _chan_
\r
772 # * everyone on all channels
\r
774 def permit?(user, cmdtxt, channel=nil)
\r
775 if user.class <= BotUser
\r
778 botuser = irc_to_botuser(user)
\r
780 cmd = cmdtxt.to_irc_auth_command
\r
792 allow = botuser.permit?(cmd, chan) if chan
\r
793 return allow unless allow.nil?
\r
794 allow = botuser.permit?(cmd)
\r
795 return allow unless allow.nil?
\r
797 unless botuser == everyone
\r
798 allow = everyone.permit?(cmd, chan) if chan
\r
799 return allow unless allow.nil?
\r
800 allow = everyone.permit?(cmd)
\r
801 return allow unless allow.nil?
\r
804 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
\r
807 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
\r
808 # telling if the user is authorized
\r
810 def allow?(cmdtxt, user, chan=nil)
\r
811 if permit?(user, cmdtxt, chan)
\r
814 # cmds = cmdtxt.split('::')
\r
815 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
\r
816 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
\r
817 {:user=>user, :command=>cmdtxt} if chan
\r
824 # Returns the only instance of AuthManagerClass
\r
826 def Auth.authmanager
\r
827 return AuthManagerClass.instance
\r
834 # A convenience method to automatically found the botuser
\r
835 # associated with the receiver
\r
838 Irc::Auth.authmanager.irc_to_botuser(self)
\r
841 # The botuser is used to store data associated with the
\r