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