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 :on_change => Proc.new {|bot, v| bot.auth.botowner.password = v},
\r
23 :desc => _('Password for the bot owner'))
\r
24 BotConfig.register BotConfigBooleanValue.new( 'auth.login_by_mask',
\r
26 :desc => _('Set false to prevent new botusers from logging in without a password when the user netmask is known'))
\r
27 BotConfig.register BotConfigBooleanValue.new( 'auth.autologin',
\r
29 :desc => _('Set false to prevent new botusers from recognizing IRC users without a need to manually login'))
\r
30 # BotConfig.register BotConfigIntegerValue.new( 'auth.default_level',
\r
31 # :default => 10, :wizard => true,
\r
32 # :desc => 'The default level for new/unknown users' )
\r
34 # Generate a random password of length _l_
\r
36 def Auth.random_password(l=8)
\r
39 pwd << (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr
\r
45 # An Irc::Auth::Command defines a command by its "path":
\r
47 # base::command::subcommand::subsubcommand::subsubsubcommand
\r
51 attr_reader :command, :path
\r
53 # A method that checks if a given _cmd_ is in a form that can be
\r
54 # reduced into a canonical command path, and if so, returns it
\r
56 def sanitize_command_path(cmd)
\r
57 pre = cmd.to_s.downcase.gsub(/^\*?(?:::)?/,"").gsub(/::$/,"")
\r
58 return pre if pre.empty?
\r
59 return pre if pre =~ /^\S+(::\S+)*$/
\r
60 raise TypeError, "#{cmd.inspect} is not a valid command"
\r
63 # Creates a new Command from a given string; you can then access
\r
64 # the command as a symbol with the :command method and the whole
\r
67 # Command.new("core::auth::save").path => [:"*", :"core", :"core::auth", :"core::auth::save"]
\r
69 # Command.new("core::auth::save").command => :"core::auth::save"
\r
72 cmdpath = sanitize_command_path(cmd).split('::')
\r
73 seq = cmdpath.inject(["*"]) { |list, cmd|
\r
74 list << (list.length > 1 ? list.last + "::" : "") + cmd
\r
76 @path = seq.map { |k|
\r
79 @command = path.last
\r
80 debug "Created command #{@command.inspect} with path #{@path.pretty_inspect}"
\r
84 def to_irc_auth_command
\r
97 # Returns an Irc::Auth::Comand from the receiver
\r
98 def to_irc_auth_command
\r
99 Irc::Auth::Command.new(self)
\r
107 # Returns an Irc::Auth::Comand from the receiver
\r
108 def to_irc_auth_command
\r
109 Irc::Auth::Command.new(self)
\r
121 # This class describes a permission set
\r
122 class PermissionSet
\r
125 # Create a new (empty) PermissionSet
\r
131 # Inspection simply inspects the internal hash
\r
136 # Sets the permission for command _cmd_ to _val_,
\r
138 def set_permission(str, val)
\r
139 cmd = str.to_irc_auth_command
\r
142 @perm[cmd.command] = val
\r
144 @perm.delete(cmd.command)
\r
146 raise TypeError, "#{val.inspect} must be true or false" unless [true,false].include?(val)
\r
150 # Resets the permission for command _cmd_
\r
152 def reset_permission(cmd)
\r
153 set_permission(cmd, nil)
\r
156 # Tells if command _cmd_ is permitted. We do this by returning
\r
157 # the value of the deepest Command#path that matches.
\r
160 cmd = str.to_irc_auth_command
\r
162 cmd.path.reverse.each { |k|
\r
163 if @perm.has_key?(k)
\r
174 # This is the error that gets raised when an invalid password is met
\r
176 class InvalidPassword < RuntimeError
\r
180 # This is the basic class for bot users: they have a username, a password,
\r
181 # a list of netmasks to match against, and a list of permissions.
\r
185 attr_reader :username
\r
186 attr_reader :password
\r
187 attr_reader :netmasks
\r
189 attr_writer :login_by_mask
\r
190 attr_writer :autologin
\r
192 # Create a new BotUser with given username
\r
193 def initialize(username)
\r
194 @username = BotUser.sanitize_username(username)
\r
196 @netmasks = NetmaskList.new
\r
198 reset_login_by_mask
\r
204 str = "<#{self.class}:#{'0x%08x' % self.object_id}:"
\r
205 str << " @username=#{@username.inspect}"
\r
206 str << " @netmasks=#{@netmasks.inspect}"
\r
207 str << " @perm=#{@perm.inspect}"
\r
208 str << " @login_by_mask=#{@login_by_mask}"
\r
209 str << " @autologin=#{@autologin}"
\r
218 # Convert into a hash
\r
221 :username => @username,
\r
222 :password => @password,
\r
223 :netmasks => @netmasks,
\r
225 :login_by_mask => @login_by_mask,
\r
226 :autologin => @autologin
\r
230 # Do we allow logging in without providing the password?
\r
236 # Reset the login-by-mask option
\r
238 def reset_login_by_mask
\r
239 @login_by_mask = Auth.authmanager.bot.config['auth.login_by_mask'] unless defined?(@login_by_mask)
\r
242 # Reset the autologin option
\r
244 def reset_autologin
\r
245 @autologin = Auth.authmanager.bot.config['auth.autologin'] unless defined?(@autologin)
\r
248 # Do we allow automatic logging in?
\r
254 # Restore from hash
\r
256 @username = h[:username] if h.has_key?(:username)
\r
257 @password = h[:password] if h.has_key?(:password)
\r
258 @netmasks = h[:netmasks] if h.has_key?(:netmasks)
\r
259 @perm = h[:perm] if h.has_key?(:perm)
\r
260 @login_by_mask = h[:login_by_mask] if h.has_key?(:login_by_mask)
\r
261 @autologin = h[:autologin] if h.has_key?(:autologin)
\r
264 # This method sets the password if the proposed new password
\r
266 def password=(pwd=nil)
\r
272 raise InvalidPassword, "#{pass} contains invalid characters" if pass !~ /^[\x21-\x7e]+$/
\r
273 raise InvalidPassword, "#{pass} too short" if pass.length < 4
\r
275 rescue InvalidPassword => e
\r
278 raise InvalidPassword, "Exception #{e.inspect} while checking #{pass.inspect} (#{pwd.inspect})"
\r
283 # Resets the password by creating a new onw
\r
285 @password = Auth.random_password
\r
288 # Sets the permission for command _cmd_ to _val_ on channel _chan_
\r
290 def set_permission(cmd, val, chan="*")
\r
291 k = chan.to_s.to_sym
\r
292 @perm[k] = PermissionSet.new unless @perm.has_key?(k)
\r
293 @perm[k].set_permission(cmd, val)
\r
296 # Resets the permission for command _cmd_ on channel _chan_
\r
298 def reset_permission(cmd, chan ="*")
\r
299 set_permission(cmd, nil, chan)
\r
302 # Checks if BotUser is allowed to do something on channel _chan_,
\r
303 # or on all channels if _chan_ is nil
\r
305 def permit?(cmd, chan=nil)
\r
307 k = chan.to_s.to_sym
\r
312 if @perm.has_key?(k)
\r
313 allow = @perm[k].permit?(cmd)
\r
320 def add_netmask(mask)
\r
321 @netmasks << mask.to_irc_netmask
\r
324 # Removes a Netmask
\r
326 def delete_netmask(mask)
\r
327 m = mask.to_irc_netmask
\r
328 @netmasks.delete(m)
\r
331 # Removes all <code>Netmask</code>s
\r
334 @netmasks = NetmaskList.new
\r
337 # This method checks if BotUser has a Netmask that matches _user_
\r
340 user = usr.to_irc_user
\r
342 @netmasks.each { |n|
\r
343 if user.matches?(n)
\r
351 # This method gets called when User _user_ wants to log in.
\r
352 # It returns true or false depending on whether the password
\r
353 # is right. If it is, the Netmask of the user is added to the
\r
354 # list of acceptable Netmask unless it's already matched.
\r
355 def login(user, password)
\r
356 if password == @password or (password.nil? and (@login_by_mask || @autologin) and knows?(user))
\r
357 add_netmask(user) unless knows?(user)
\r
358 debug "#{user} logged in as #{self.inspect}"
\r
365 # # This method gets called when User _user_ has logged out as this BotUser
\r
367 # delete_netmask(user) if knows?(user)
\r
370 # This method sanitizes a username by chomping, downcasing
\r
371 # and replacing any nonalphanumeric character with _
\r
373 def BotUser.sanitize_username(name)
\r
374 candidate = name.to_s.chomp.downcase.gsub(/[^a-z0-9]/,"_")
\r
375 raise "sanitized botusername #{candidate} too short" if candidate.length < 3
\r
382 # This is the default BotUser: it's used for all users which haven't
\r
383 # identified with the bot
\r
385 class DefaultBotUserClass < BotUser
\r
387 private :add_netmask, :delete_netmask
\r
391 # The default BotUser is named 'everyone'
\r
394 reset_login_by_mask
\r
397 @default_perm = PermissionSet.new
\r
400 # This method returns without changing anything
\r
402 def login_by_mask=(val)
\r
403 debug "Tried to change the login-by-mask for default bot user, ignoring"
\r
404 return @login_by_mask
\r
407 # The default botuser allows logins by mask
\r
409 def reset_login_by_mask
\r
410 @login_by_mask = true
\r
413 # This method returns without changing anything
\r
415 def autologin=(val)
\r
416 debug "Tried to change the autologin for default bot user, ignoring"
\r
420 # The default botuser doesn't allow autologin (meaningless)
\r
422 def reset_autologin
\r
426 # Sets the default permission for the default user (i.e. the ones
\r
427 # set by the BotModule writers) on all channels
\r
429 def set_default_permission(cmd, val)
\r
430 @default_perm.set_permission(Command.new(cmd), val)
\r
431 debug "Default permissions now: #{@default_perm.pretty_inspect}"
\r
434 # default knows everybody
\r
437 return true if user.to_irc_user
\r
440 # We always allow logging in as the default user
\r
441 def login(user, password)
\r
445 # Resets the NetmaskList
\r
448 add_netmask("*!*@*")
\r
451 # DefaultBotUser will check the default_perm after checking
\r
453 # or on all channels if _chan_ is nil
\r
455 def permit?(cmd, chan=nil)
\r
456 allow = super(cmd, chan)
\r
457 if allow.nil? && chan.nil?
\r
458 allow = @default_perm.permit?(cmd)
\r
465 # Returns the only instance of DefaultBotUserClass
\r
467 def Auth.defaultbotuser
\r
468 return DefaultBotUserClass.instance
\r
471 # This is the BotOwner: he can do everything
\r
473 class BotOwnerClass < BotUser
\r
478 @login_by_mask = false
\r
483 def permit?(cmd, chan=nil)
\r
489 # Returns the only instance of BotOwnerClass
\r
492 return BotOwnerClass.instance
\r
496 # This is the AuthManagerClass singleton, used to manage User/BotUser connections and
\r
499 class AuthManagerClass
\r
503 attr_reader :everyone
\r
504 attr_reader :botowner
\r
507 # The instance manages two <code>Hash</code>es: one that maps
\r
508 # <code>Irc::User</code>s onto <code>BotUser</code>s, and the other that maps
\r
509 # usernames onto <code>BotUser</code>
\r
511 @everyone = Auth::defaultbotuser
\r
512 @botowner = Auth::botowner
\r
516 def bot_associate(bot)
\r
517 raise "Cannot associate with a new bot! Save first" if defined?(@has_changes) && @has_changes
\r
524 # This variable is set to true when there have been changes
\r
525 # to the botusers list, so that we know when to save
\r
526 @has_changes = false
\r
530 @has_changes = true
\r
534 @has_changes = false
\r
541 # resets the hashes
\r
543 @botusers = Hash.new
\r
544 @allbotusers = Hash.new
\r
545 [everyone, botowner].each { |x|
\r
546 @allbotusers[x.username.to_sym] = x
\r
550 def load_array(ary, forced)
\r
552 warning "Tried to load an empty array"
\r
555 raise "Won't load with unsaved changes" if @has_changes and not forced
\r
558 raise TypeError, "#{x} should be a Hash" unless x.kind_of?(Hash)
\r
563 get_botuser(u).from_hash(x)
\r
569 @allbotusers.values.map { |x|
\r
574 # checks if we know about a certain BotUser username
\r
575 def include?(botusername)
\r
576 @allbotusers.has_key?(botusername.to_sym)
\r
579 # Maps <code>Irc::User</code> to BotUser
\r
580 def irc_to_botuser(ircuser)
\r
581 logged = @botusers[ircuser.to_irc_user]
\r
582 return logged if logged
\r
583 return autologin(ircuser)
\r
586 # creates a new BotUser
\r
587 def create_botuser(name, password=nil)
\r
588 n = BotUser.sanitize_username(name)
\r
590 raise "botuser #{n} exists" if include?(k)
\r
591 bu = BotUser.new(n)
\r
592 bu.password = password
\r
593 @allbotusers[k] = bu
\r
597 # returns the botuser with name _name_
\r
598 def get_botuser(name)
\r
599 @allbotusers.fetch(BotUser.sanitize_username(name).to_sym)
\r
602 # Logs Irc::User _user_ in to BotUser _botusername_ with password _pwd_
\r
604 # raises an error if _botusername_ is not a known BotUser username
\r
606 # It is possible to autologin by Netmask, on request
\r
608 def login(user, botusername, pwd=nil)
\r
609 ircuser = user.to_irc_user
\r
610 n = BotUser.sanitize_username(botusername)
\r
612 raise "No such BotUser #{n}" unless include?(k)
\r
613 if @botusers.has_key?(ircuser)
\r
614 return true if @botusers[ircuser].username == n
\r
616 # @botusers[ircuser].logout(ircuser)
\r
618 bu = @allbotusers[k]
\r
619 if bu.login(ircuser, pwd)
\r
620 @botusers[ircuser] = bu
\r
626 # Tries to auto-login Irc::User _user_ by looking at the known botusers that allow autologin
\r
627 # and trying to login without a password
\r
629 def autologin(user)
\r
630 ircuser = user.to_irc_user
\r
631 debug "Trying to autlogin #{ircuser}"
\r
632 return @botusers[ircuser] if @botusers.has_key?(ircuser)
\r
633 @allbotusers.each { |n, bu|
\r
634 debug "Checking with #{n}"
\r
635 return bu if bu.autologin? and login(ircuser, n)
\r
640 # Checks if User _user_ can do _cmd_ on _chan_.
\r
642 # Permission are checked in this order, until a true or false
\r
644 # * associated BotUser on _chan_
\r
645 # * associated BotUser on all channels
\r
646 # * everyone on _chan_
\r
647 # * everyone on all channels
\r
649 def permit?(user, cmdtxt, channel=nil)
\r
650 if user.class <= BotUser
\r
653 botuser = irc_to_botuser(user)
\r
655 cmd = cmdtxt.to_irc_auth_command
\r
667 allow = botuser.permit?(cmd, chan) if chan
\r
668 return allow unless allow.nil?
\r
669 allow = botuser.permit?(cmd)
\r
670 return allow unless allow.nil?
\r
672 unless botuser == everyone
\r
673 allow = everyone.permit?(cmd, chan) if chan
\r
674 return allow unless allow.nil?
\r
675 allow = everyone.permit?(cmd)
\r
676 return allow unless allow.nil?
\r
679 raise "Could not check permission for user #{user.inspect} to run #{cmdtxt.inspect} on #{chan.inspect}"
\r
682 # Checks if command _cmd_ is allowed to User _user_ on _chan_, optionally
\r
683 # telling if the user is authorized
\r
685 def allow?(cmdtxt, user, chan=nil)
\r
686 if permit?(user, cmdtxt, chan)
\r
689 # cmds = cmdtxt.split('::')
\r
690 # @bot.say chan, "you don't have #{cmds.last} (#{cmds.first}) permissions here" if chan
\r
691 @bot.say chan, _("%{user}, you don't have '%{command}' permissions here") %
\r
692 {:user=>user, :command=>cmdtxt} if chan
\r
699 # Returns the only instance of AuthManagerClass
\r
701 def Auth.authmanager
\r
702 return AuthManagerClass.instance
\r