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
16 # This module contains the actual Authentication stuff
\r
20 BotConfig.register BotConfigStringValue.new( 'auth.password',
\r
21 :default => 'rbotauth', :wizard => true,
\r
22 :desc => 'Password for the bot owner' )
\r
23 BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',
\r
25 :desc => 'Set false to prevent new botusers from logging in without a password when the user netmask is known')
\r
26 BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',
\r
28 :desc => 'Set false to prevent new botusers from recognizing IRC users without a need to manually login')
\r
29 # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',
\r
30 # :default => 10, :wizard => true,
\r
31 # :desc => 'The default level for new/unknown users' )
\r
33 # Generate a random password of length _l_
\r
35 def Auth.random_password(l=8)
\r
38 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
\r
44 # An Irc::Auth::Command defines a command by its "path":
\r
46 # base::command::subcommand::subsubcommand::subsubsubcommand
\r
50 attr_reader :command, :path
\r
52 # A method that checks if a given _cmd_ is in a form that can be
\r
53 # reduced into a canonical command path, and if so, returns it
\r
55 def sanitize_command_path(cmd)
\r
56 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
\r
57 return pre if pre.empty?
\r
58 return pre if pre =~ /^\S+(::\S+)*$/
\r
59 raise TypeError, "#{cmd.inspect} is not a valid command"
\r
62 # Creates a new Command from a given string; you can then access
\r
63 # the command as a symbol with the :command method and the whole
\r
66 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
\r
68 # Command.new("core::auth::save").command => :"core::auth::save"
\r
71 cmdpath = sanitize_command_path(cmd).split('::')
\r
72 seq = cmdpath.inject(["*"]) { |list, cmd|
\r
73 list << (list.length > 1 ? list.last + "::" : "") + cmd
\r
75 @path = seq.map { |k|
\r
78 @command = path.last
\r
79 debug "Created command #{@command.inspect} with path #{@path.join(', ')}"
\r
83 def to_irc_auth_command
\r
96 # Returns an Irc::Auth::Comand from the receiver
\r
97 def to_irc_auth_command
\r
98 Irc::Auth::Command.new(self)
\r
106 # Returns an Irc::Auth::Comand from the receiver
\r
107 def to_irc_auth_command
\r
108 Irc::Auth::Command.new(self)
\r
120 # This class describes a permission set
\r
121 class PermissionSet
\r
124 # Create a new (empty) PermissionSet
\r
130 # Inspection simply inspects the internal hash
\r
135 # Sets the permission for command _cmd_ to _val_,
\r
137 def set_permission(str, val)
\r
138 cmd = str.to_irc_auth_command
\r
141 @perm[cmd.command] = val
\r
143 @perm.delete(cmd.command)
\r
145 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
\r
149 # Resets the permission for command _cmd_
\r
151 def reset_permission(cmd)
\r
152 set_permission(cmd, nil)
\r
155 # Tells if command _cmd_ is permitted. We do this by returning
\r
156 # the value of the deepest Command#path that matches.
\r
159 cmd = str.to_irc_auth_command
\r
161 cmd.path.reverse.each { |k|
\r
162 if @perm.has_key?(k)
\r
173 # This is the error that gets raised when an invalid password is met
\r
175 class InvalidPassword < RuntimeError
\r
179 # This is the basic class for bot users: they have a username, a password,
\r
180 # a list of netmasks to match against, and a list of permissions.
\r
184 attr_reader :username
\r
185 attr_reader :password
\r
186 attr_reader :netmasks
\r
188 attr_writer :login_by_mask
\r
189 attr_writer :autologin
\r
191 # Create a new BotUser with given username
\r
192 def initialize(username)
\r
193 @username = BotUser.sanitize_username(username)
\r
195 @netmasks = NetmaskList.new
\r
197 reset_login_by_mask
\r
203 str = "<#{self.class}:#{'0x%08x' % self.object_id}:"
\r
204 str << " @username=#{@username.inspect}"
\r
205 str << " @netmasks=#{@netmasks.inspect}"
\r
206 str << " @perm=#{@perm.inspect}"
\r
207 str << " @login_by_mask=#{@login_by_mask}"
\r
208 str << " @autologin=#{@autologin}"
\r
217 # Convert into a hash
\r
220 :username => @username,
\r
221 :password => @password,
\r
222 :netmasks => @netmasks,
\r
224 :login_by_mask => @login_by_mask,
\r
225 :autologin => @autologin
\r
229 # Do we allow logging in without providing the password?
\r
235 # Reset the login-by-mask option
\r
237 def reset_login_by_mask
\r
238 @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
\r
241 # Reset the autologin option
\r
243 def reset_autologin
\r
244 @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)
\r
247 # Do we allow automatic logging in?
\r
253 # Restore from hash
\r
255 @username = h[:username] if h.has_key?(:username)
\r
256 @password = h[:password] if h.has_key?(:password)
\r
257 @netmasks = h[:netmasks] if h.has_key?(:netmasks)
\r
258 @perm = h[:perm] if h.has_key?(:perm)
\r
259 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
\r
260 @autologin = h[:autologin] if h.has_key?(:autologin)
\r
263 # This method sets the password if the proposed new password
\r
265 def password=(pwd=nil)
\r
271 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
\r
272 raise InvalidPassword, "#{pass} too short" if pass.length < 4
\r
274 rescue InvalidPassword => e
\r
277 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
\r
282 # Resets the password by creating a new onw
\r
284 @password = Auth.random_password
\r
287 # Sets the permission for command _cmd_ to _val_ on channel _chan_
\r
289 def set_permission(cmd, val, chan="*")
\r
290 k = chan.to_s.to_sym
\r
291 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
\r
292 @perm[k].set_permission(cmd, val)
\r
295 # Resets the permission for command _cmd_ on channel _chan_
\r
297 def reset_permission(cmd, chan ="*")
\r
298 set_permission(cmd, nil, chan)
\r
301 # Checks if BotUser is allowed to do something on channel _chan_,
\r
302 # or on all channels if _chan_ is nil
\r
304 def permit?(cmd, chan=nil)
\r
306 k = chan.to_s.to_sym
\r
311 if @perm.has_key?(k)
\r
312 allow = @perm[k].permit?(cmd)
\r
319 def add_netmask(mask)
\r
320 @netmasks << mask.to_irc_netmask
\r
323 # Removes a Netmask
\r
325 def delete_netmask(mask)
\r
326 m = mask.to_irc_netmask
\r
327 @netmasks.delete(m)
\r
330 # Removes all <code>Netmask</code>s
\r
333 @netmasks = NetmaskList.new
\r
336 # This method checks if BotUser has a Netmask that matches _user_
\r
339 user = usr.to_irc_user
\r
341 @netmasks.each { |n|
\r
342 if user.matches?(n)
\r
350 # This method gets called when User _user_ wants to log in.
\r
351 # It returns true or false depending on whether the password
\r
352 # is right. If it is, the Netmask of the user is added to the
\r
353 # list of acceptable Netmask unless it's already matched.
\r
354 def login(user, password)
\r
355 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
\r
356 add_netmask(user) unless knows?(user)
\r
357 debug "#{user} logged in as #{self.inspect}"
\r
364 # # This method gets called when User _user_ has logged out as this BotUser
\r
366 # delete_netmask(user) if knows?(user)
\r
369 # This method sanitizes a username by chomping, downcasing
\r
370 # and replacing any nonalphanumeric character with _
\r
372 def BotUser.sanitize_username(name)
\r
373 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
\r
374 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
\r
381 # This is the default BotUser: it's used for all users which haven't
\r
382 # identified with the bot
\r
384 class DefaultBotUserClass < BotUser
\r
386 private :add_netmask, :delete_netmask
\r
390 # The default BotUser is named 'everyone'
\r
393 reset_login_by_mask
\r
396 @default_perm = PermissionSet.new
\r
399 # This method returns without changing anything
\r
401 def login_by_mask=(val)
\r
402 debug "Tried to change the login-by-mask for default bot user, ignoring"
\r
403 return @login_by_mask
\r
406 # The default botuser allows logins by mask
\r
408 def reset_login_by_mask
\r
409 @login_by_mask = true
\r
412 # This method returns without changing anything
\r
414 def autologin=(val)
\r
415 debug "Tried to change the autologin for default bot user, ignoring"
\r
419 # The default botuser doesn't allow autologin (meaningless)
\r
421 def reset_autologin
\r
425 # Sets the default permission for the default user (i.e. the ones
\r
426 # set by the BotModule writers) on all channels
\r
428 def set_default_permission(cmd, val)
\r
429 @default_perm.set_permission(Command.new(cmd), val)
\r
430 debug "Default permissions now:\n#{@default_perm.inspect}"
\r
433 # default knows everybody
\r
436 return true if user.to_irc_user
\r
439 # We always allow logging in as the default user
\r
440 def login(user, password)
\r
444 # Resets the NetmaskList
\r
447 add_netmask("*!*@*")
\r
450 # DefaultBotUser will check the default_perm after checking
\r
452 # or on all channels if _chan_ is nil
\r
454 def permit?(cmd, chan=nil)
\r
455 allow = super(cmd, chan)
\r
456 if allow.nil? && chan.nil?
\r
457 allow = @default_perm.permit?(cmd)
\r
464 # Returns the only instance of DefaultBotUserClass
\r
466 def Auth.defaultbotuser
\r
467 return DefaultBotUserClass.instance
\r
470 # This is the BotOwner: he can do everything
\r
472 class BotOwnerClass < BotUser
\r
477 @login_by_mask = false
\r
482 def permit?(cmd, chan=nil)
\r
488 # Returns the only instance of BotOwnerClass
\r
491 return BotOwnerClass.instance
\r
495 # This is the AuthManagerClass singleton, used to manage User/BotUser connections and
\r
498 class AuthManagerClass
\r
502 attr_reader :everyone
\r
503 attr_reader :botowner
\r
506 # The instance manages two <code>Hash</code>es: one that maps
\r
507 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
\r
508 # usernames onto <code>BotUser</code>
\r
510 @everyone = Auth::defaultbotuser
\r
511 @botowner = Auth::botowner
\r
515 def bot_associate(bot)
\r
516 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
\r
523 # This variable is set to true when there have been changes
\r
524 # to the botusers list, so that we know when to save
\r
525 @has_changes = false
\r
529 @has_changes = true
\r
533 @has_changes = false
\r
540 # resets the hashes
\r
542 @botusers = Hash.new
\r
543 @allbotusers = Hash.new
\r
544 [everyone, botowner].each { |x|
\r
545 @allbotusers[x.username.to_sym] = x
\r
549 def load_array(ary, forced)
\r
550 raise "Won't load with unsaved changes" if @has_changes and not forced
\r
553 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
\r
558 get_botuser(u).from_hash(x)
\r
564 @allbotusers.values.map { |x|
\r
569 # checks if we know about a certain BotUser username
\r
570 def include?(botusername)
\r
571 @allbotusers.has_key?(botusername.to_sym)
\r
574 # Maps <code>Irc::User</code> to BotUser
\r
575 def irc_to_botuser(ircuser)
\r
576 logged = @botusers[ircuser.to_irc_user]
\r
577 return logged if logged
\r
578 return autologin(ircuser)
\r
581 # creates a new BotUser
\r
582 def create_botuser(name, password=nil)
\r
583 n = BotUser.sanitize_username(name)
\r
585 raise "botuser #{n} exists" if include?(k)
\r
586 bu = BotUser.new(n)
\r
587 bu.password = password
\r
588 @allbotusers[k] = bu
\r
592 # returns the botuser with name _name_
\r
593 def get_botuser(name)
\r
594 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
\r
597 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
\r
599 # raises an error if _botusername_ is not a known BotUser username
\r
601 # It is possible to autologin by Netmask, on request
\r
603 def login(user, botusername, pwd=nil)
\r
604 ircuser = user.to_irc_user
\r
605 n = BotUser.sanitize_username(botusername)
\r
607 raise "No such BotUser #{n}" unless include?(k)
\r
608 if @botusers.has_key?(ircuser)
\r
609 return true if @botusers[ircuser].username == n
\r
611 # @botusers[ircuser].logout(ircuser)
\r
613 bu = @allbotusers[k]
\r
614 if bu.login(ircuser, pwd)
\r
615 @botusers[ircuser] = bu
\r
621 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
\r
622 # and trying to login without a password
\r
624 def autologin(user)
\r
625 ircuser = user.to_irc_user
\r
626 debug "Trying to autlogin #{ircuser}"
\r
627 return @botusers[ircuser] if @botusers.has_key?(ircuser)
\r
628 @allbotusers.each { |n, bu|
\r
629 debug "Checking with #{n}"
\r
630 return bu if bu.autologin? and login(ircuser, n)
\r
635 # Checks if User _user_ can do _cmd_ on _chan_.
\r
637 # Permission are checked in this order, until a true or false
\r
639 # * associated BotUser on _chan_
\r
640 # * associated BotUser on all channels
\r
641 # * everyone on _chan_
\r
642 # * everyone on all channels
\r
644 def permit?(user, cmdtxt, channel=nil)
\r
645 if user.class <= BotUser
\r
648 botuser = irc_to_botuser(user)
\r
650 cmd = cmdtxt.to_irc_auth_command
\r
662 allow = botuser.permit?(cmd, chan) if chan
\r
663 return allow unless allow.nil?
\r
664 allow = botuser.permit?(cmd)
\r
665 return allow unless allow.nil?
\r
667 unless botuser == everyone
\r
668 allow = everyone.permit?(cmd, chan) if chan
\r
669 return allow unless allow.nil?
\r
670 allow = everyone.permit?(cmd)
\r
671 return allow unless allow.nil?
\r
674 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
\r
677 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
\r
678 # telling if the user is authorized
\r
680 def allow?(cmdtxt, user, chan=nil)
\r
681 if permit?(user, cmdtxt, chan)
\r
684 # cmds = cmdtxt.split('::')
\r
685 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
\r
686 @bot.say chan, "#{user}, you don't have '#{cmdtxt}' permissions here" if chan
\r
693 # Returns the only instance of AuthManagerClass
\r
695 def Auth.authmanager
\r
696 return AuthManagerClass.instance
\r