]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/auth.rb
irclog core module: skip, don't die when unable to open logfile
[user/henk/code/ruby/rbot.git] / lib / rbot / core / auth.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot auth management from IRC
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7
8 class AuthModule < CoreBotModule
9
10   def initialize
11     super
12
13     # The namespace migration causes each Irc::Auth::PermissionSet to be
14     # unrecoverable, and we have to rename their class name to
15     # Irc::Bot::Auth::PermissionSet
16     @registry.recovery = Proc.new { |val|
17       patched = val.sub("o:\035Irc::Auth::PermissionSet", "o:\042Irc::Bot::Auth::PermissionSet")
18       Marshal.restore(patched)
19     }
20
21     load_array(:default, true)
22     debug "initialized auth. Botusers: #{@bot.auth.save_array.pretty_inspect}"
23   end
24
25   def save
26     save_array
27   end
28
29   def save_array(key=:default)
30     if @bot.auth.changed?
31       @registry[key] = @bot.auth.save_array
32       @bot.auth.reset_changed
33       debug "saved botusers (#{key}): #{@registry[key].pretty_inspect}"
34     end
35   end
36
37   def load_array(key=:default, forced=false)
38     debug "loading botusers (#{key}): #{@registry[key].pretty_inspect}"
39     @bot.auth.load_array(@registry[key], forced) if @registry.has_key?(key)
40     if @bot.auth.botowner.password != @bot.config['auth.password']
41       error "Master password is out of sync!"
42       debug "  db password: #{@bot.auth.botowner.password}"
43       debug "conf password: #{@bot.config['auth.password']}"
44       error "Using conf password"
45       @bot.auth.botowner.password = @bot.config['auth.password']
46     end
47   end
48
49   # The permission parameters accept arguments with the following syntax:
50   #   cmd_path... [on #chan .... | in here | in private]
51   # This auxiliary method scans the array _ar_ to see if it matches
52   # the given syntax: it expects + or - signs in front of _cmd_path_
53   # elements when _setting_ = true
54   #
55   # It returns an array whose first element is the array of cmd_path,
56   # the second element is an array of locations and third an array of
57   # warnings occurred while parsing the strings
58   #
59   def parse_args(ar, setting)
60     cmds = []
61     locs = []
62     warns = []
63     doing_cmds = true
64     next_must_be_chan = false
65     want_more = false
66     last_idx = 0
67     ar.each_with_index { |x, i|
68       if doing_cmds # parse cmd_path
69         # check if the list is done
70         if x == "on" or x == "in"
71           doing_cmds = false
72           next_must_be_chan = true if x == "on"
73           next
74         end
75         if "+-".include?(x[0])
76           warns << ArgumentError.new(_("please do not use + or - in front of command %{command} when resetting") % {:command => x}) unless setting
77         else
78           warns << ArgumentError.new(_("+ or - expected in front of %{string}") % {:string => x}) if setting
79         end
80         cmds << x
81       else # parse locations
82         if x[-1].chr == ','
83           want_more = true
84         else
85           want_more = false
86         end
87         case next_must_be_chan
88         when false
89           locs << x.gsub(/^here$/,'_').gsub(/^private$/,'?')
90         else
91           warns << ArgumentError.new(_("'%{string}' doesn't look like a channel name") % {:string => x}) unless @bot.server.supports[:chantypes].include?(x[0])
92           locs << x
93         end
94         unless want_more
95           last_idx = i
96           break
97         end
98       end
99     }
100     warns << _("trailing comma") if want_more
101     warns << _("you probably forgot a comma") unless last_idx == ar.length - 1
102     return cmds, locs, warns
103   end
104
105   def auth_edit_perm(m, params)
106
107     setting = m.message.split[1] == "set"
108     splits = params[:args]
109
110     has_for = splits[-2] == "for"
111     return usage(m) unless has_for
112
113     begin
114       user = @bot.auth.get_botuser(splits[-1].sub(/^all$/,"everyone"))
115     rescue
116       return m.reply(_("couldn't find botuser %{name}") % {:name => splits[-1]})
117     end
118     return m.reply(_("you can't change permissions for %{username}") % {:username => user.username}) if user.owner?
119     splits.slice!(-2,2) if has_for
120
121     cmds, locs, warns = parse_args(splits, setting)
122     errs = warns.select { |w| w.kind_of?(Exception) }
123
124     unless errs.empty?
125       m.reply _("couldn't satisfy your request: %{errors}") % {:errors => errs.join(',')}
126       return
127     end
128
129     if locs.empty?
130       locs << "*"
131     end
132     begin
133       locs.each { |loc|
134         ch = loc
135         if m.private?
136           ch = "?" if loc == "_"
137         else
138           ch = m.target.to_s if loc == "_"
139         end
140         cmds.each { |setval|
141           if setting
142             val = setval[0].chr == '+'
143             cmd = setval[1..-1]
144             user.set_permission(cmd, val, ch)
145           else
146             cmd = setval
147             user.reset_permission(cmd, ch)
148           end
149         }
150       }
151     rescue => e
152       m.reply "something went wrong while trying to set the permissions"
153       raise
154     end
155     @bot.auth.set_changed
156     debug "user #{user} permissions changed"
157     m.okay
158   end
159
160   def auth_view_perm(m, params)
161     begin
162       if params[:user].nil?
163         user = get_botusername_for(m.source)
164         return m.reply(_("you are owner, you can do anything")) if user.owner?
165       else
166         user = @bot.auth.get_botuser(params[:user].sub(/^all$/,"everyone"))
167         return m.reply(_("owner can do anything")) if user.owner?
168       end
169     rescue
170       return m.reply(_("couldn't find botuser %{name}") % {:name => params[:user]})
171     end
172     perm = user.perm
173     str = []
174     perm.each { |k, val|
175       next if val.perm.empty?
176       case k
177       when :*
178         str << _("on any channel: ")
179       when :"?"
180         str << _("in private: ")
181       else
182         str << _("on #{k}: ")
183       end
184       sub = []
185       val.perm.each { |cmd, bool|
186         sub << (bool ? "+" : "-")
187         sub.last << cmd.to_s
188       }
189       str.last << sub.join(', ')
190     }
191     if str.empty?
192       m.reply _("no permissions set for %{user}") % {:user => user.username}
193     else
194       m.reply _("permissions for %{user}:: %{permissions}") %
195               { :user => user.username, :permissions => str.join('; ')}
196     end
197   end
198
199   def auth_search_perm(m, p)
200     pattern = Regexp.new(p[:pattern].to_s)
201     results = @bot.plugins.maps.select { |k, v| k.match(pattern) }
202     count = results.length
203     max = @bot.config['send.max_lines']
204     extra = (count > max ? _(". only %{max} will be shown") : "") % { :max => max }
205     m.reply _("%{count} commands found matching %{pattern}%{extra}") % {
206       :count => count, :pattern => pattern, :extra => extra
207     }
208     return if count == 0
209     results[0,max].each { |cmd, hash|
210       m.reply _("%{cmd}: %{perms}") % {
211         :cmd => cmd,
212         :perms => hash[:auth].join(", ")
213       }
214     }
215   end
216
217   def find_auth(pseudo)
218     k = pseudo.plugin.intern
219     cmds = @bot.plugins.commands
220     auth = nil
221     if cmds.has_key?(k)
222       cmds[k][:botmodule].handler.each do |tmpl|
223         options, failure = tmpl.recognize(pseudo)
224         next if options.nil?
225         auth = tmpl.options[:full_auth_path]
226         break
227       end
228     end
229     return auth
230   end
231
232   def auth_allow_deny(m, p)
233     begin
234       botuser = @bot.auth.get_botuser(p[:user].sub(/^all$/,"everyone"))
235     rescue
236       return m.reply(_("couldn't find botuser %{name}") % {:name => p[:user]})
237     end
238
239     if p[:where].to_s.empty?
240       where = :*
241     else
242       where = m.parse_channel_list(p[:where].to_s).first # should only be one anyway
243     end
244
245     # pseudo-message to find the template. The source is ignored, and the
246     # target is set according to where the template should be checked
247     # (public or private)
248     # This might still fail in the case of 'everywhere' for commands there are
249     # really only private
250     case where
251     when :"?"
252       pseudo_target = @bot.myself
253     when :*
254       pseudo_target = m.channel
255     else
256       pseudo_target = m.server.channel(where)
257     end
258
259     pseudo = PrivMessage.new(bot, m.server, m.source, pseudo_target, p[:stuff].to_s)
260
261     auth_path = find_auth(pseudo)
262     debug auth_path
263
264     if auth_path
265       allow = p[:allow]
266       if @bot.auth.permit?(botuser, auth_path, where)
267         return m.reply(_("%{user} can already do that") % {:user => botuser}) if allow
268       else
269         return m.reply(_("%{user} can't do that already") % {:user => botuser}) if !allow
270       end
271       cmd = PrivMessage.new(bot, m.server, m.source, m.target, "permissions set %{sign}%{path} %{where} for %{user}" % {
272         :path => auth_path,
273         :user => p[:user],
274         :sign => (allow ? '+' : '-'),
275         :where => p[:where].to_s
276       })
277       handle(cmd)
278     else
279       m.reply(_("sorry, %{cmd} doesn't look like a valid command. maybe you misspelled it, or you need to specify it should be in private?") % {
280         :cmd => p[:stuff].to_s
281       })
282     end
283   end
284
285   def auth_allow(m, p)
286     auth_allow_deny(m, p.merge(:allow => true))
287   end
288
289   def auth_deny(m, p)
290     auth_allow_deny(m, p.merge(:allow => false))
291   end
292
293   def get_botuser_for(user)
294     @bot.auth.irc_to_botuser(user)
295   end
296
297   def get_botusername_for(user)
298     get_botuser_for(user).username
299   end
300
301   def say_welcome(m)
302     m.reply _("welcome, %{user}") % {:user => get_botusername_for(m.source)}
303   end
304
305   def auth_auth(m, params)
306     params[:botuser] = 'owner'
307     auth_login(m,params)
308   end
309
310   def auth_login(m, params)
311     begin
312       case @bot.auth.login(m.source, params[:botuser], params[:password])
313       when true
314         say_welcome(m)
315         @bot.auth.set_changed
316       else
317         m.reply _("sorry, can't do")
318       end
319     rescue => e
320       m.reply _("couldn't login: %{exception}") % {:exception => e}
321       raise
322     end
323   end
324
325   def auth_autologin(m, params)
326     u = do_autologin(m.source)
327     if u.default?
328       m.reply _("I couldn't find anything to let you login automatically")
329     else
330       say_welcome(m)
331     end
332   end
333
334   def do_autologin(user)
335     @bot.auth.autologin(user)
336   end
337
338   def auth_whoami(m, params)
339     m.reply _("you are %{who}") % {
340       :who => get_botusername_for(m.source).gsub(
341                 /^everyone$/, _("no one that I know")).gsub(
342                 /^owner$/, _("my boss"))
343     }
344   end
345
346   def auth_whois(m, params)
347     return auth_whoami(m, params) if !m.public?
348     u = m.channel.users[params[:user]]
349
350     return m.reply("I don't see anyone named '#{params[:user]}' here") unless u
351
352     m.reply _("#{params[:user]} is %{who}") % {
353       :who => get_botusername_for(u).gsub(
354                 /^everyone$/, _("no one that I know")).gsub(
355                 /^owner$/, _("my boss"))
356     }
357   end
358
359   def help(cmd, topic="")
360     case cmd
361     when "login"
362       return _("login [<botuser>] [<pass>]: logs in to the bot as botuser <botuser> with password <pass>. When using the full form, you must contact the bot in private. <pass> can be omitted if <botuser> allows login-by-mask and your netmask is among the known ones. if <botuser> is omitted too autologin will be attempted")
363     when "whoami"
364       return _("whoami: names the botuser you're linked to")
365     when "who"
366       return _("who is <user>: names the botuser <user> is linked to")
367     when /^permission/
368       case topic
369       when "syntax"
370         return _("a permission is specified as module::path::to::cmd; when you want to enable it, prefix it with +; when you want to disable it, prefix it with -; when using the +reset+ command, do not use any prefix")
371       when "set", "reset", "[re]set", "(re)set"
372         return _("permissions [re]set <permission> [in <channel>] for <user>: sets or resets the permissions for botuser <user> in channel <channel> (use ? to change the permissions for private addressing)")
373       when "view"
374         return _("permissions view [for <user>]: display the permissions for user <user>")
375       when "search"
376         return _("permissions search <pattern>: display the permissions associated with the commands matching <pattern>")
377       else
378         return _("permission topics: syntax, (re)set, view, search")
379       end
380     when "user"
381       case topic
382       when "show"
383         return _("user show <what> : shows info about the user; <what> can be any of autologin, login-by-mask, netmasks")
384       when /^(en|dis)able/
385         return _("user enable|disable <what> : turns on or off <what> (autologin, login-by-mask)")
386       when "set"
387         return _("user set password <blah> : sets the user password to <blah>; passwords can only contain upper and lowercase letters and numbers, and must be at least 4 characters long")
388       when "add", "rm"
389         return _("user add|rm netmask <mask> : adds/removes netmask <mask> from the list of netmasks known to the botuser you're linked to")
390       when "reset"
391         return _("user reset <what> : resets <what> to the default values. <what> can be +netmasks+ (the list will be emptied), +autologin+ or +login-by-mask+ (will be reset to the default value) or +password+ (a new one will be generated and you'll be told in private)")
392       when "tell"
393         return _("user tell <who> the password for <botuser> : contacts <who> in private to tell him/her the password for <botuser>")
394       when "create"
395         return _("user create <name> <password> : create botuser named <name> with password <password>. The password can be omitted, in which case a random one will be generated. The <name> should only contain alphanumeric characters and the underscore (_)")
396       when "list"
397         return _("user list : lists all the botusers")
398       when "destroy"
399         return _("user destroy <botuser> : destroys <botuser>. This function %{highlight}must%{highlight} be called in two steps. On the first call <botuser> is queued for destruction. On the second call, which must be in the form 'user confirm destroy <botuser>', the botuser will be destroyed. If you want to cancel the destruction, issue the command 'user cancel destroy <botuser>'") % {:highlight => Bold}
400       else
401         return _("user topics: show, enable|disable, add|rm netmask, set, reset, tell, create, list, destroy")
402       end
403     when "auth"
404       return _("auth <masterpassword>: log in as the bot owner; other commands: login, whoami, permissions syntax, permissions [re]set, permissions view, user, meet, hello, allow, prevent")
405     when "meet"
406       return _("meet <nick> [as <user>]: creates a bot user for nick, calling it user (defaults to the nick itself)")
407     when "hello"
408       return _("hello: creates a bot user for the person issuing the command")
409     when "allow"
410       return _("allow <user> to do <sample command> [<where>]: gives botuser <user> the permissions to execute a command such as the provided sample command (in private or in channel, according to the optional <where>)")
411     when "deny"
412       return _("deny <user> from doing <sample command> [<where>]: removes from botuser <user> the permissions to execute a command such as the provided sample command (in private or in channel, according to the optional <where>)")
413     else
414       return _("auth commands: auth, login, whoami, who, permission[s], user, meet, hello, allow, deny")
415     end
416   end
417
418   def need_args(cmd)
419     _("sorry, I need more arguments to %{command}") % {:command => cmd}
420   end
421
422   def not_args(cmd, *stuff)
423     _("I can only %{command} these: %{arguments}") %
424       {:command => cmd, :arguments => stuff.join(', ')}
425   end
426
427   def set_prop(botuser, prop, val)
428     k = prop.to_s.gsub("-","_")
429     botuser.send( (k + "=").to_sym, val)
430     if prop == :password and botuser == @bot.auth.botowner
431       @bot.config.items[:'auth.password'].set_string(@bot.auth.botowner.password)
432     end
433   end
434
435   def reset_prop(botuser, prop)
436     k = prop.to_s.gsub("-","_")
437     botuser.send( ("reset_"+k).to_sym)
438   end
439
440   def ask_bool_prop(botuser, prop)
441     k = prop.to_s.gsub("-","_")
442     botuser.send( (k + "?").to_sym)
443   end
444
445   def auth_manage_user(m, params)
446     splits = params[:data]
447
448     cmd = splits.first
449     return auth_whoami(m, params) if cmd.nil?
450
451     botuser = get_botuser_for(m.source)
452     # By default, we do stuff on the botuser the irc user is bound to
453     butarget = botuser
454
455     has_for = splits[-2] == "for"
456     if has_for
457       butarget = @bot.auth.get_botuser(splits[-1]) rescue nil
458       return m.reply(_("no such bot user %{user}") % {:user => splits[-1]}) unless butarget
459       splits.slice!(-2,2)
460     end
461     return m.reply(_("you can't mess with %{user}") % {:user => butarget.username}) if butarget.owner? && botuser != butarget
462
463     bools = [:autologin, :"login-by-mask"]
464     can_set = [:password]
465     can_addrm = [:netmasks]
466     can_reset = bools + can_set + can_addrm
467     can_show = can_reset + ["perms"]
468
469     begin
470     case cmd.to_sym
471
472     when :show
473       return m.reply(_("you can't see the properties of %{user}") %
474              {:user => butarget.username}) if botuser != butarget &&
475                                                !botuser.permit?("auth::show::other")
476
477       case splits[1]
478       when nil, "all"
479         props = can_reset
480       when "password"
481         if botuser != butarget
482           return m.reply(_("no way I'm telling you the master password!")) if butarget == @bot.auth.botowner
483           return m.reply(_("you can't ask for someone else's password"))
484         end
485         return m.reply(_("c'mon, you can't be asking me seriously to tell you the password in public!")) if m.public?
486         return m.reply(_("the password for %{user} is %{password}") %
487           { :user => butarget.username, :password => butarget.password })
488       else
489         props = splits[1..-1]
490       end
491
492       str = []
493
494       props.each { |arg|
495         k = arg.to_sym
496         next if k == :password
497         case k
498         when *bools
499           if ask_bool_prop(butarget, k)
500             str << _("can %{action}") % {:action => k}
501           else
502             str << _("can not %{action}") % {:action => k}
503           end
504         when :netmasks
505           if butarget.netmasks.empty?
506             str << _("knows no netmasks")
507           else
508             str << _("knows %{netmasks}") % {:netmasks => butarget.netmasks.join(", ")}
509           end
510         end
511       }
512       return m.reply("#{butarget.username} #{str.join('; ')}")
513
514     when :enable, :disable
515       return m.reply(_("you can't change the default user")) if butarget.default? && !botuser.permit?("auth::edit::other::default")
516       return m.reply(_("you can't edit %{user}") % {:user => butarget.username}) if butarget != botuser && !botuser.permit?("auth::edit::other")
517
518       return m.reply(need_args(cmd)) unless splits[1]
519       things = []
520       skipped = []
521       splits[1..-1].each { |a|
522         arg = a.to_sym
523         if bools.include?(arg)
524           set_prop(butarget, arg, cmd.to_sym == :enable)
525           things << a
526         else
527           skipped << a
528         end
529       }
530
531       m.reply(_("I ignored %{things} because %{reason}") % {
532                 :things => skipped.join(', '),
533                 :reason => not_args(cmd, *bools)}) unless skipped.empty?
534       if things.empty?
535         m.reply _("I haven't changed anything")
536       else
537         @bot.auth.set_changed
538         return auth_manage_user(m, {:data => ["show"] + things + ["for", butarget.username] })
539       end
540
541     when :set
542       return m.reply(_("you can't change the default user")) if
543              butarget.default? && !botuser.permit?("auth::edit::default")
544       return m.reply(_("you can't edit %{user}") % {:user=>butarget.username}) if
545              butarget != botuser && !botuser.permit?("auth::edit::other")
546
547       return m.reply(need_args(cmd)) unless splits[1]
548       arg = splits[1].to_sym
549       return m.reply(not_args(cmd, *can_set)) unless can_set.include?(arg)
550       argarg = splits[2]
551       return m.reply(need_args([cmd, splits[1]].join(" "))) unless argarg
552       if arg == :password && m.public?
553         return m.reply(_("is that a joke? setting the password in public?"))
554       end
555       set_prop(butarget, arg, argarg)
556       @bot.auth.set_changed
557       auth_manage_user(m, {:data => ["show", arg.to_s, "for", butarget.username] })
558
559     when :reset
560       return m.reply(_("you can't change the default user")) if
561              butarget.default? && !botuser.permit?("auth::edit::default")
562       return m.reply(_("you can't edit %{user}") % {:user=>butarget.username}) if
563              butarget != botuser && !botuser.permit?("auth::edit::other")
564
565       return m.reply(need_args(cmd)) unless splits[1]
566       things = []
567       skipped = []
568       splits[1..-1].each { |a|
569         arg = a.to_sym
570         if can_reset.include?(arg)
571           reset_prop(butarget, arg)
572           things << a
573         else
574           skipped << a
575         end
576       }
577
578       m.reply(_("I ignored %{things} because %{reason}") %
579                 { :things => skipped.join(', '),
580                   :reason => not_args(cmd, *can_reset)}) unless skipped.empty?
581       if things.empty?
582         m.reply _("I haven't changed anything")
583       else
584         @bot.auth.set_changed
585         @bot.say(m.source, _("the password for %{user} is now %{password}") %
586           {:user => butarget.username, :password => butarget.password}) if
587           things.include?("password")
588         return auth_manage_user(m, {:data => (["show"] + things - ["password"]) + ["for", butarget.username]})
589       end
590
591     when :add, :rm, :remove, :del, :delete
592       return m.reply(_("you can't change the default user")) if
593              butarget.default? && !botuser.permit?("auth::edit::default")
594       return m.reply(_("you can't edit %{user}") % {:user => butarget.username}) if
595              butarget != botuser && !botuser.permit?("auth::edit::other")
596
597       arg = splits[1]
598       if arg.nil? or arg !~ /netmasks?/ or splits[2].nil?
599         return m.reply(_("I can only add/remove netmasks. See +help user add+ for more instructions"))
600       end
601
602       method = cmd.to_sym == :add ? :add_netmask : :delete_netmask
603
604       failed = []
605
606       splits[2..-1].each { |mask|
607         begin
608           butarget.send(method, mask.to_irc_netmask(:server => @bot.server))
609         rescue => e
610           debug "failed with #{e.message}"
611           debug e.backtrace.join("\n")
612           failed << mask
613         end
614       }
615       m.reply "I failed to #{cmd} #{failed.join(', ')}" unless failed.empty?
616       @bot.auth.set_changed
617       return auth_manage_user(m, {:data => ["show", "netmasks", "for", butarget.username] })
618
619     else
620       m.reply _("sorry, I don't know how to %{request}") % {:request => m.message}
621     end
622     rescue => e
623       m.reply _("couldn't %{cmd}: %{exception}") % {:cmd => cmd, :exception => e}
624     end
625   end
626
627   def auth_meet(m, params)
628     nick = params[:nick]
629     if !nick
630       # we are actually responding to a 'hello' command
631       unless m.botuser.transient?
632         m.reply @bot.lang.get('hello_X') % m.botuser
633         return
634       end
635       nick = m.sourcenick
636       irc_user = m.source
637     else
638       # m.channel is always an Irc::Channel because the command is either
639       # public-only 'meet' or private/public 'hello' which was handled by
640       # the !nick case, so this shouldn't fail
641       irc_user = m.channel.users[nick]
642       return m.reply("I don't see anyone named '#{nick}' here") unless irc_user
643     end
644     # BotUser name
645     buname = params[:user] || nick
646     begin
647       call_event(:botuser,:pre_perm, {:irc_user => irc_user, :bot_user => buname})
648       met = @bot.auth.make_permanent(irc_user, buname)
649       @bot.auth.set_changed
650       call_event(:botuser,:post_perm, {:irc_user => irc_user, :bot_user => buname})
651       m.reply @bot.lang.get('hello_X') % met
652       @bot.say nick, _("you are now registered as %{buname}. I created a random password for you : %{pass} and you can change it at any time by telling me 'user set password <password>' in private" % {
653         :buname => buname,
654         :pass => met.password
655       })
656     rescue RuntimeError
657       # or can this happen for other cases too?
658       # TODO autologin if forced
659       m.reply _("but I already know %{buname}" % {:buname => buname})
660     rescue => e
661       m.reply _("I had problems meeting %{nick}: %{e}" % { :nick => nick, :e => e })
662     end
663   end
664
665   def auth_tell_password(m, params)
666     user = params[:user]
667     begin
668       botuser = @bot.auth.get_botuser(params[:botuser])
669     rescue
670       return m.reply(_("couldn't find botuser %{user}") % {:user => params[:botuser]})
671     end
672     return m.reply(_("I'm not telling the master password to anyone, pal")) if botuser == @bot.auth.botowner
673     msg = _("the password for botuser %{user} is %{password}") %
674           {:user => botuser.username, :password => botuser.password}
675     @bot.say user, msg
676     @bot.say m.source, _("I told %{user} that %{message}") % {:user => user, :message => msg}
677   end
678
679   def auth_create_user(m, params)
680     name = params[:name]
681     password = params[:password]
682     return m.reply(_("are you nuts, creating a botuser with a publicly known password?")) if m.public? and not password.nil?
683     begin
684       bu = @bot.auth.create_botuser(name, password)
685       @bot.auth.set_changed
686     rescue => e
687       m.reply(_("failed to create %{user}: %{exception}") % {:user => name,  :exception => e})
688       debug e.inspect + "\n" + e.backtrace.join("\n")
689       return
690     end
691     m.reply(_("created botuser %{user}") % {:user => bu.username})
692   end
693
694   def auth_list_users(m, params)
695     # TODO name regexp to filter results
696     list = @bot.auth.save_array.inject([]) { |list, x| ['everyone', 'owner'].include?(x[:username]) ? list : list << x[:username] }
697     if defined?(@destroy_q)
698       list.map! { |x|
699         @destroy_q.include?(x) ? x + _(" (queued for destruction)") : x
700       }
701     end
702     return m.reply(_("I have no botusers other than the default ones")) if list.empty?
703     return m.reply(n_("botuser: %{list}", "botusers: %{list}", list.length) %
704                    {:list => list.join(', ')})
705   end
706
707   def auth_destroy_user(m, params)
708     @destroy_q = [] unless defined?(@destroy_q)
709     buname = params[:name]
710     return m.reply(_("You can't destroy %{user}") % {:user => buname}) if
711            ["everyone", "owner"].include?(buname)
712     mod = params[:modifier].to_sym rescue nil
713
714     buser_array = @bot.auth.save_array
715     buser_hash = buser_array.inject({}) { |h, u|
716       h[u[:username]] = u
717       h
718     }
719
720     return m.reply(_("no such botuser %{user}") % {:user=>buname}) unless
721            buser_hash.keys.include?(buname)
722
723     case mod
724     when :cancel
725       if @destroy_q.include?(buname)
726         @destroy_q.delete(buname)
727         m.reply(_("%{user} removed from the destruction queue") % {:user=>buname})
728       else
729         m.reply(_("%{user} was not queued for destruction") % {:user=>buname})
730       end
731       return
732     when nil
733       if @destroy_q.include?(buname)
734         return m.reply(_("%{user} already queued for destruction, use %{highlight}user confirm destroy %{user}%{highlight} to destroy it") % {:user=>buname, :highlight=>Bold})
735       else
736         @destroy_q << buname
737         return m.reply(_("%{user} queued for destruction, use %{highlight}user confirm destroy %{user}%{highlight} to destroy it") % {:user=>buname, :highlight=>Bold})
738       end
739     when :confirm
740       begin
741         return m.reply(_("%{user} is not queued for destruction yet") %
742                {:user=>buname}) unless @destroy_q.include?(buname)
743         buser_array.delete_if { |u|
744           u[:username] == buname
745         }
746         @destroy_q.delete(buname)
747         @bot.auth.load_array(buser_array, true)
748         @bot.auth.set_changed
749       rescue => e
750         return m.reply(_("failed: %{exception}") % {:exception => e})
751       end
752       return m.reply(_("botuser %{user} destroyed") % {:user => buname})
753     end
754   end
755
756   def auth_copy_ren_user(m, params)
757     source = Auth::BotUser.sanitize_username(params[:source])
758     dest = Auth::BotUser.sanitize_username(params[:dest])
759     return m.reply(_("please don't touch the default users")) unless
760       (["everyone", "owner"] & [source, dest]).empty?
761
762     buser_array = @bot.auth.save_array
763     buser_hash = buser_array.inject({}) { |h, u|
764       h[u[:username]] = u
765       h
766     }
767
768     return m.reply(_("no such botuser %{source}") % {:source=>source}) unless
769            buser_hash.keys.include?(source)
770     return m.reply(_("botuser %{dest} exists already") % {:dest=>dest}) if
771            buser_hash.keys.include?(dest)
772
773     copying = m.message.split[1] == "copy"
774     begin
775       if copying
776         h = {}
777         buser_hash[source].each { |k, val|
778           h[k] = val.dup
779         }
780       else
781         h = buser_hash[source]
782       end
783       h[:username] = dest
784       buser_array << h if copying
785
786       @bot.auth.load_array(buser_array, true)
787       @bot.auth.set_changed
788       call_event(:botuser, copying ? :copy : :rename, :source => source, :dest => dest)
789     rescue => e
790       return m.reply(_("failed: %{exception}") % {:exception=>e})
791     end
792     if copying
793       m.reply(_("botuser %{source} copied to %{dest}") %
794            {:source=>source, :dest=>dest})
795     else
796       m.reply(_("botuser %{source} renamed to %{dest}") %
797            {:source=>source, :dest=>dest})
798     end
799
800   end
801
802   def auth_export(m, params)
803
804     exportfile = "#{@bot.botclass}/new-auth.users"
805
806     what = params[:things]
807
808     has_to = what[-2] == "to"
809     if has_to
810       exportfile = "#{@bot.botclass}/#{what[-1]}"
811       what.slice!(-2,2)
812     end
813
814     what.delete("all")
815
816     m.reply _("selecting data to export ...")
817
818     buser_array = @bot.auth.save_array
819     buser_hash = buser_array.inject({}) { |h, u|
820       h[u[:username]] = u
821       h
822     }
823
824     if what.empty?
825       we_want = buser_hash
826     else
827       we_want = buser_hash.delete_if { |key, val|
828         not what.include?(key)
829       }
830     end
831
832     m.reply _("preparing data for export ...")
833     begin
834       yaml_hash = {}
835       we_want.each { |k, val|
836         yaml_hash[k] = {}
837         val.each { |kk, v|
838           case kk
839           when :username
840             next
841           when :netmasks
842             yaml_hash[k][kk] = []
843             v.each { |nm|
844               yaml_hash[k][kk] << {
845                 :fullform => nm.fullform,
846                 :casemap => nm.casemap.to_s
847               }
848             }
849           else
850             yaml_hash[k][kk] = v
851           end
852         }
853       }
854     rescue => e
855       m.reply _("failed to prepare data: %{exception}") % {:exception=>e}
856       debug e.backtrace.dup.unshift(e.inspect).join("\n")
857       return
858     end
859
860     m.reply _("exporting to %{file} ...") % {:file=>exportfile}
861     begin
862       # m.reply yaml_hash.inspect
863       File.open(exportfile, "w") do |file|
864         file.puts YAML::dump(yaml_hash)
865       end
866     rescue => e
867       m.reply _("failed to export users: %{exception}") % {:exception=>e}
868       debug e.backtrace.dup.unshift(e.inspect).join("\n")
869       return
870     end
871     m.reply _("done")
872   end
873
874   def auth_import(m, params)
875
876     importfile = "#{@bot.botclass}/new-auth.users"
877
878     what = params[:things]
879
880     has_from = what[-2] == "from"
881     if has_from
882       importfile = "#{@bot.botclass}/#{what[-1]}"
883       what.slice!(-2,2)
884     end
885
886     what.delete("all")
887
888     m.reply _("reading %{file} ...") % {:file=>importfile}
889     begin
890       yaml_hash = YAML::load_file(importfile)
891     rescue => e
892       m.reply _("failed to import from: %{exception}") % {:exception=>e}
893       debug e.backtrace.dup.unshift(e.inspect).join("\n")
894       return
895     end
896
897     # m.reply yaml_hash.inspect
898
899     m.reply _("selecting data to import ...")
900
901     if what.empty?
902       we_want = yaml_hash
903     else
904       we_want = yaml_hash.delete_if { |key, val|
905         not what.include?(key)
906       }
907     end
908
909     m.reply _("parsing data from import ...")
910
911     buser_hash = {}
912
913     begin
914       yaml_hash.each { |k, val|
915         buser_hash[k] = { :username => k }
916         val.each { |kk, v|
917           case kk
918           when :netmasks
919             buser_hash[k][kk] = []
920             v.each { |nm|
921               buser_hash[k][kk] << nm[:fullform].to_irc_netmask(:casemap => nm[:casemap].to_irc_casemap).to_irc_netmask(:server => @bot.server)
922             }
923           else
924             buser_hash[k][kk] = v
925           end
926         }
927       }
928     rescue => e
929       m.reply _("failed to parse data: %{exception}") % {:exception=>e}
930       debug e.backtrace.dup.unshift(e.inspect).join("\n")
931       return
932     end
933
934     # m.reply buser_hash.inspect
935
936     org_buser_array = @bot.auth.save_array
937     org_buser_hash = org_buser_array.inject({}) { |h, u|
938       h[u[:username]] = u
939       h
940     }
941
942     # TODO we may want to do a(n optional) key-by-key merge
943     #
944     org_buser_hash.merge!(buser_hash)
945     new_buser_array = org_buser_hash.values
946     @bot.auth.load_array(new_buser_array, true)
947     @bot.auth.set_changed
948
949     m.reply _("done")
950   end
951
952 end
953
954 auth = AuthModule.new
955
956 auth.map "user export *things",
957   :action => 'auth_export',
958   :defaults => { :things => ['all'] },
959   :auth_path => ':manage:fedex:'
960
961 auth.map "user import *things",
962  :action => 'auth_import',
963  :auth_path => ':manage:fedex:'
964
965 auth.map "user create :name :password",
966   :action => 'auth_create_user',
967   :defaults => {:password => nil},
968   :auth_path => ':manage:'
969
970 auth.map "user [:modifier] destroy :name",
971   :action => 'auth_destroy_user',
972   :requirements => { :modifier => /^(cancel|confirm)?$/ },
973   :defaults => { :modifier => '' },
974   :auth_path => ':manage::destroy!'
975
976 auth.map "user copy :source [to] :dest",
977   :action => 'auth_copy_ren_user',
978   :auth_path => ':manage:'
979
980 auth.map "user rename :source [to] :dest",
981   :action => 'auth_copy_ren_user',
982   :auth_path => ':manage:'
983
984 auth.map "meet :nick [as :user]",
985   :action => 'auth_meet',
986   :auth_path => 'user::manage', :private => false
987
988 auth.map "hello",
989   :action => 'auth_meet',
990   :auth_path => 'user::manage::meet'
991
992 auth.default_auth("user::manage", false)
993 auth.default_auth("user::manage::meet::hello", true)
994
995 auth.map "user tell :user the password for :botuser",
996   :action => 'auth_tell_password',
997   :auth_path => ':manage:'
998
999 auth.map "user list",
1000   :action => 'auth_list_users',
1001   :auth_path => '::'
1002
1003 auth.map "user *data",
1004   :action => 'auth_manage_user'
1005
1006 auth.map "allow :user to do *stuff [*where]",
1007   :action => 'auth_allow',
1008   :requirements => {:where => /^(?:anywhere|everywhere|[io]n \S+)$/},
1009   :auth_path => ':edit::other:'
1010
1011 auth.map "deny :user from doing *stuff [*where]",
1012   :action => 'auth_deny',
1013   :requirements => {:where => /^(?:anywhere|everywhere|[io]n \S+)$/},
1014   :auth_path => ':edit::other:'
1015
1016 auth.default_auth("user", true)
1017 auth.default_auth("edit::other", false)
1018
1019 auth.map "whoami",
1020   :action => 'auth_whoami',
1021   :auth_path => '!*!'
1022
1023 auth.map "who is :user",
1024   :action => 'auth_whois',
1025   :auth_path => '!*!'
1026
1027 auth.map "auth :password",
1028   :action => 'auth_auth',
1029   :public => false,
1030   :auth_path => '!login!'
1031
1032 auth.map "login :botuser :password",
1033   :action => 'auth_login',
1034   :public => false,
1035   :defaults => { :password => nil },
1036   :auth_path => '!login!'
1037
1038 auth.map "login :botuser",
1039   :action => 'auth_login',
1040   :auth_path => '!login!'
1041
1042 auth.map "login",
1043   :action => 'auth_autologin',
1044   :auth_path => '!login!'
1045
1046 auth.map "permissions set *args",
1047   :action => 'auth_edit_perm',
1048   :auth_path => ':edit::set:'
1049
1050 auth.map "permissions reset *args",
1051   :action => 'auth_edit_perm',
1052   :auth_path => ':edit::set:'
1053
1054 auth.map "permissions view [for :user]",
1055   :action => 'auth_view_perm',
1056   :auth_path => '::'
1057
1058 auth.map "permissions search *pattern",
1059   :action => 'auth_search_perm',
1060   :auth_path => '::'
1061
1062 auth.default_auth('*', false)
1063