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
17 # This module contains the actual Authentication stuff
\r
21 BotConfig.register BotConfigStringValue.new( 'auth.password',
\r
22 :default => 'rbotauth', :wizard => true,
\r
23 :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},
\r
24 :desc => _('Password for the bot owner'))
\r
25 BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',
\r
27 :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))
\r
28 BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',
\r
30 :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))
\r
31 BotConfig.register BotConfigBooleanValue.new( 'auth.autouser',
\r
32 :default => 'false',
\r
33 :desc => _('Set true to allow new botusers to be created automatically'))
\r
34 # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',
\r
35 # :default => 10, :wizard => true,
\r
36 # :desc => 'The default level for new/unknown users' )
\r
38 # Generate a random password of length _l_
\r
40 def Auth.random_password(l=8)
\r
43 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
\r
49 # An Irc::Auth::Command defines a command by its "path":
\r
51 # base::command::subcommand::subsubcommand::subsubsubcommand
\r
55 attr_reader :command, :path
\r
57 # A method that checks if a given _cmd_ is in a form that can be
\r
58 # reduced into a canonical command path, and if so, returns it
\r
60 def sanitize_command_path(cmd)
\r
61 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
\r
62 return pre if pre.empty?
\r
63 return pre if pre =~ /^\S+(::\S+)*$/
\r
64 raise TypeError, "#{cmd.inspect} is not a valid command"
\r
67 # Creates a new Command from a given string; you can then access
\r
68 # the command as a symbol with the :command method and the whole
\r
71 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
\r
73 # Command.new("core::auth::save").command => :"core::auth::save"
\r
76 cmdpath = sanitize_command_path(cmd).split('::')
\r
77 seq = cmdpath.inject(["*"]) { |list, cmd|
\r
78 list << (list.length > 1 ? list.last + "::" : "") + cmd
\r
80 @path = seq.map { |k|
\r
83 @command = path.last
\r
84 debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"
\r
88 def to_irc_auth_command
\r
101 # Returns an Irc::Auth::Comand from the receiver
\r
102 def to_irc_auth_command
\r
103 Irc::Auth::Command.new(self)
\r
111 # Returns an Irc::Auth::Comand from the receiver
\r
112 def to_irc_auth_command
\r
113 Irc::Auth::Command.new(self)
\r
125 # This class describes a permission set
\r
126 class PermissionSet
\r
129 # Create a new (empty) PermissionSet
\r
135 # Inspection simply inspects the internal hash
\r
140 # Sets the permission for command _cmd_ to _val_,
\r
142 def set_permission(str, val)
\r
143 cmd = str.to_irc_auth_command
\r
146 @perm[cmd.command] = val
\r
148 @perm.delete(cmd.command)
\r
150 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
\r
154 # Resets the permission for command _cmd_
\r
156 def reset_permission(cmd)
\r
157 set_permission(cmd, nil)
\r
160 # Tells if command _cmd_ is permitted. We do this by returning
\r
161 # the value of the deepest Command#path that matches.
\r
164 cmd = str.to_irc_auth_command
\r
166 cmd.path.reverse.each { |k|
\r
167 if @perm.has_key?(k)
\r
178 # This is the error that gets raised when an invalid password is met
\r
180 class InvalidPassword < RuntimeError
\r
184 # This is the basic class for bot users: they have a username, a
\r
185 # password, a list of netmasks to match against, and a list of
\r
186 # permissions. A BotUser can be marked as 'transient', usually meaning
\r
187 # it's not intended for permanent storage. Transient BotUsers have lower
\r
188 # priority than nontransient ones for autologin purposes.
\r
190 # To initialize a BotUser, you pass a _username_ and an optional
\r
191 # hash of options. Currently, only two options are recognized:
\r
193 # transient:: true or false, determines if the BotUser is transient or
\r
194 # permanent (default is false, permanent BotUser).
\r
196 # Transient BotUsers are initialized by prepending an
\r
197 # asterisk (*) to the username, and appending a sanitized
\r
198 # version of the object_id. The username can be empty.
\r
199 # A random password is generated.
\r
201 # Permanent Botusers need the username as is, and no
\r
202 # password is generated.
\r
204 # masks:: an array of Netmasks to initialize the NetmaskList. This
\r
205 # list is used as-is for permanent BotUsers.
\r
207 # Transient BotUsers will alter the list elements which are
\r
208 # Irc::User by globbing the nick and any initial nonletter
\r
209 # part of the ident.
\r
211 # The masks option is optional for permanent BotUsers, but
\r
212 # obligatory (non-empty) for transients.
\r
216 attr_reader :username
\r
217 attr_reader :password
\r
218 attr_reader :netmasks
\r
221 attr_writer :login_by_mask
\r
222 attr_writer :autologin
\r
223 attr_writer :transient
\r
225 # Checks if the BotUser is transient
\r
230 # Checks if the BotUser is permanent (not transient)
\r
235 # Sets if the BotUser is permanent or not
\r
236 def permanent=(bool)
\r
240 # Create a new BotUser with given username
\r
241 def initialize(username, options={})
\r
242 opts = {:transient => false}.merge(options)
\r
243 @transient = opts[:transient]
\r
247 @username << BotUser.sanitize_username(username) if username and not username.to_s.empty?
\r
248 @username << BotUser.sanitize_username(object_id)
\r
250 @login_by_mask=true
\r
253 @username = BotUser.sanitize_username(username)
\r
255 reset_login_by_mask
\r
259 @netmasks = NetmaskList.new
\r
260 if opts.key?(:masks) and opts[:masks]
\r
261 masks = opts[:masks]
\r
262 masks = [masks] unless masks.respond_to?(:each)
\r
264 mask = m.to_irc_netmask
\r
265 if @transient and User === m
\r
267 mask.host = m.host.dup
\r
268 mask.user = "*" + m.user.sub(/^\w?[^\w]+/,'')
\r
270 add_netmask(mask) unless mask.to_s == "*"
\r
273 raise "must provide a usable mask for transient BotUser #{@username}" if @transient and @netmasks.empty?
\r
282 str = "<#{self.class}:#{'0x%08x' % self.object_id}"
\r
283 str << " (transient)" if @transient
\r
285 str << " @username=#{@username.inspect}"
\r
286 str << " @netmasks=#{@netmasks.inspect}"
\r
287 str << " @perm=#{@perm.inspect}"
\r
288 str << " @login_by_mask=#{@login_by_mask}"
\r
289 str << " @autologin=#{@autologin}"
\r
293 str << " data for #{@data.keys.join(', ')}"
\r
303 # Convert into a hash
\r
306 :username => @username,
\r
307 :password => @password,
\r
308 :netmasks => @netmasks,
\r
310 :login_by_mask => @login_by_mask,
\r
311 :autologin => @autologin,
\r
316 # Do we allow logging in without providing the password?
\r
322 # Reset the login-by-mask option
\r
324 def reset_login_by_mask
\r
325 @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
\r
328 # Reset the autologin option
\r
330 def reset_autologin
\r
331 @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)
\r
334 # Do we allow automatic logging in?
\r
340 # Restore from hash
\r
342 @username = h[:username] if h.has_key?(:username)
\r
343 @password = h[:password] if h.has_key?(:password)
\r
344 @netmasks = h[:netmasks] if h.has_key?(:netmasks)
\r
345 @perm = h[:perm] if h.has_key?(:perm)
\r
346 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
\r
347 @autologin = h[:autologin] if h.has_key?(:autologin)
\r
348 @data = h[:data] if h.has_key?(:data)
\r
351 # This method sets the password if the proposed new password
\r
353 def password=(pwd=nil)
\r
359 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
\r
360 raise InvalidPassword, "#{pass} too short" if pass.length < 4
\r
362 rescue InvalidPassword => e
\r
365 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
\r
370 # Resets the password by creating a new onw
\r
372 @password = Auth.random_password
\r
375 # Sets the permission for command _cmd_ to _val_ on channel _chan_
\r
377 def set_permission(cmd, val, chan="*")
\r
378 k = chan.to_s.to_sym
\r
379 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
\r
380 @perm[k].set_permission(cmd, val)
\r
383 # Resets the permission for command _cmd_ on channel _chan_
\r
385 def reset_permission(cmd, chan ="*")
\r
386 set_permission(cmd, nil, chan)
\r
389 # Checks if BotUser is allowed to do something on channel _chan_,
\r
390 # or on all channels if _chan_ is nil
\r
392 def permit?(cmd, chan=nil)
\r
394 k = chan.to_s.to_sym
\r
399 if @perm.has_key?(k)
\r
400 allow = @perm[k].permit?(cmd)
\r
407 def add_netmask(mask)
\r
408 @netmasks << mask.to_irc_netmask
\r
411 # Removes a Netmask
\r
413 def delete_netmask(mask)
\r
414 m = mask.to_irc_netmask
\r
415 @netmasks.delete(m)
\r
418 # Removes all <code>Netmask</code>s
\r
421 @netmasks = NetmaskList.new
\r
424 # This method checks if BotUser has a Netmask that matches _user_
\r
427 user = usr.to_irc_user
\r
429 @netmasks.each { |n|
\r
430 if user.matches?(n)
\r
438 # This method gets called when User _user_ wants to log in.
\r
439 # It returns true or false depending on whether the password
\r
440 # is right. If it is, the Netmask of the user is added to the
\r
441 # list of acceptable Netmask unless it's already matched.
\r
442 def login(user, password=nil)
\r
443 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
\r
444 add_netmask(user) unless knows?(user)
\r
445 debug "#{user} logged in as #{self.inspect}"
\r
452 # # This method gets called when User _user_ has logged out as this BotUser
\r
454 # delete_netmask(user) if knows?(user)
\r
457 # This method sanitizes a username by chomping, downcasing
\r
458 # and replacing any nonalphanumeric character with _
\r
460 def BotUser.sanitize_username(name)
\r
461 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
\r
462 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
\r
468 # This is the default BotUser: it's used for all users which haven't
\r
469 # identified with the bot
\r
471 class DefaultBotUserClass < BotUser
\r
473 private :add_netmask, :delete_netmask
\r
477 # The default BotUser is named 'everyone'
\r
480 reset_login_by_mask
\r
483 @default_perm = PermissionSet.new
\r
486 # This method returns without changing anything
\r
488 def login_by_mask=(val)
\r
489 debug "Tried to change the login-by-mask for default bot user, ignoring"
\r
490 return @login_by_mask
\r
493 # The default botuser allows logins by mask
\r
495 def reset_login_by_mask
\r
496 @login_by_mask = true
\r
499 # This method returns without changing anything
\r
501 def autologin=(val)
\r
502 debug "Tried to change the autologin for default bot user, ignoring"
\r
506 # The default botuser doesn't allow autologin (meaningless)
\r
508 def reset_autologin
\r
512 # Sets the default permission for the default user (i.e. the ones
\r
513 # set by the BotModule writers) on all channels
\r
515 def set_default_permission(cmd, val)
\r
516 @default_perm.set_permission(Command.new(cmd), val)
\r
517 debug "Default permissions now: #{@default_perm.pretty_inspect}"
\r
520 # default knows everybody
\r
523 return true if user.to_irc_user
\r
526 # We always allow logging in as the default user
\r
527 def login(user, password)
\r
531 # Resets the NetmaskList
\r
534 add_netmask("*!*@*")
\r
537 # DefaultBotUser will check the default_perm after checking
\r
539 # or on all channels if _chan_ is nil
\r
541 def permit?(cmd, chan=nil)
\r
542 allow = super(cmd, chan)
\r
543 if allow.nil? && chan.nil?
\r
544 allow = @default_perm.permit?(cmd)
\r
551 # Returns the only instance of DefaultBotUserClass
\r
553 def Auth.defaultbotuser
\r
554 return DefaultBotUserClass.instance
\r
557 # This is the BotOwner: he can do everything
\r
559 class BotOwnerClass < BotUser
\r
564 @login_by_mask = false
\r
569 def permit?(cmd, chan=nil)
\r
575 # Returns the only instance of BotOwnerClass
\r
578 return BotOwnerClass.instance
\r
582 # This is the AuthManagerClass singleton, used to manage User/BotUser connections and
\r
585 class AuthManagerClass
\r
589 attr_reader :everyone
\r
590 attr_reader :botowner
\r
593 # The instance manages two <code>Hash</code>es: one that maps
\r
594 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
\r
595 # usernames onto <code>BotUser</code>
\r
597 @everyone = Auth::defaultbotuser
\r
598 @botowner = Auth::botowner
\r
602 def bot_associate(bot)
\r
603 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
\r
610 # This variable is set to true when there have been changes
\r
611 # to the botusers list, so that we know when to save
\r
612 @has_changes = false
\r
616 @has_changes = true
\r
620 @has_changes = false
\r
627 # resets the hashes
\r
629 @botusers = Hash.new
\r
630 @allbotusers = Hash.new
\r
631 [everyone, botowner].each { |x|
\r
632 @allbotusers[x.username.to_sym] = x
\r
634 @transients = Set.new
\r
637 def load_array(ary, forced)
\r
639 warning "Tried to load an empty array"
\r
642 raise "Won't load with unsaved changes" if @has_changes and not forced
\r
645 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
\r
650 get_botuser(u).from_hash(x)
\r
651 get_botuser(u).transient = false
\r
657 @allbotusers.values.map { |x|
\r
658 x.transient? ? nil : x.to_hash
\r
662 # checks if we know about a certain BotUser username
\r
663 def include?(botusername)
\r
664 @allbotusers.has_key?(botusername.to_sym)
\r
667 # Maps <code>Irc::User</code> to BotUser
\r
668 def irc_to_botuser(ircuser)
\r
669 logged = @botusers[ircuser.to_irc_user]
\r
670 return logged if logged
\r
671 return autologin(ircuser)
\r
674 # creates a new BotUser
\r
675 def create_botuser(name, password=nil)
\r
676 n = BotUser.sanitize_username(name)
\r
678 raise "botuser #{n} exists" if include?(k)
\r
679 bu = BotUser.new(n)
\r
680 bu.password = password
\r
681 @allbotusers[k] = bu
\r
685 # returns the botuser with name _name_
\r
686 def get_botuser(name)
\r
687 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
\r
690 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
\r
692 # raises an error if _botusername_ is not a known BotUser username
\r
694 # It is possible to autologin by Netmask, on request
\r
696 def login(user, botusername, pwd=nil)
\r
697 ircuser = user.to_irc_user
\r
698 n = BotUser.sanitize_username(botusername)
\r
700 raise "No such BotUser #{n}" unless include?(k)
\r
701 if @botusers.has_key?(ircuser)
\r
702 return true if @botusers[ircuser].username == n
\r
704 # @botusers[ircuser].logout(ircuser)
\r
706 bu = @allbotusers[k]
\r
707 if bu.login(ircuser, pwd)
\r
708 @botusers[ircuser] = bu
\r
714 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
\r
715 # and trying to login without a password
\r
717 def autologin(user)
\r
718 ircuser = user.to_irc_user
\r
719 debug "Trying to autologin #{ircuser}"
\r
720 return @botusers[ircuser] if @botusers.has_key?(ircuser)
\r
721 @allbotusers.each { |n, bu|
\r
722 debug "Checking with #{n}"
\r
723 return bu if bu.autologin? and login(ircuser, n)
\r
725 # Check with transient users
\r
726 @transients.each { |bu|
\r
727 return bu if bu.login(ircuser)
\r
729 # Finally, create a transient if we're set to allow it
\r
730 if @bot.config['auth.autouser']
\r
731 bu = create_transient_botuser(ircuser)
\r
737 # Creates a new transient BotUser associated with Irc::User _user_,
\r
738 # automatically logging him in
\r
740 def create_transient_botuser(user)
\r
741 ircuser = user.to_irc_user
\r
742 bu = BotUser.new(ircuser, :transient => true, :masks => ircuser)
\r
748 # Checks if User _user_ can do _cmd_ on _chan_.
\r
750 # Permission are checked in this order, until a true or false
\r
752 # * associated BotUser on _chan_
\r
753 # * associated BotUser on all channels
\r
754 # * everyone on _chan_
\r
755 # * everyone on all channels
\r
757 def permit?(user, cmdtxt, channel=nil)
\r
758 if user.class <= BotUser
\r
761 botuser = irc_to_botuser(user)
\r
763 cmd = cmdtxt.to_irc_auth_command
\r
775 allow = botuser.permit?(cmd, chan) if chan
\r
776 return allow unless allow.nil?
\r
777 allow = botuser.permit?(cmd)
\r
778 return allow unless allow.nil?
\r
780 unless botuser == everyone
\r
781 allow = everyone.permit?(cmd, chan) if chan
\r
782 return allow unless allow.nil?
\r
783 allow = everyone.permit?(cmd)
\r
784 return allow unless allow.nil?
\r
787 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
\r
790 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
\r
791 # telling if the user is authorized
\r
793 def allow?(cmdtxt, user, chan=nil)
\r
794 if permit?(user, cmdtxt, chan)
\r
797 # cmds = cmdtxt.split('::')
\r
798 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
\r
799 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
\r
800 {:user=>user, :command=>cmdtxt} if chan
\r
807 # Returns the only instance of AuthManagerClass
\r
809 def Auth.authmanager
\r
810 return AuthManagerClass.instance
\r
817 # A convenience method to automatically found the botuser
\r
818 # associated with the receiver
\r
821 Irc::Auth.authmanager.irc_to_botuser(self)
\r
824 # The botuser is used to store data associated with the
\r