Comparison

mod_http_muc_kick/mod_http_muc_kick.lua @ 4642:9fc52ccfb445

mod_http_muc_kick: Publish module
author Seve Ferrer <seve@delape.net>
date Tue, 10 Aug 2021 13:27:16 +0200
child 4643:df09f9ce0b1b
comparison
equal deleted inserted replaced
4641:64fafbeba14d 4642:9fc52ccfb445
1 local jid_split = require "util.jid".prepped_split;
2 local json = require "util.json";
3
4 module:depends("http");
5
6 local authorization = assert(
7 module:get_option_string("http_muc_kick_authorization_header", nil),
8 "http_muc_kick_authorization_header setting is missing, please add it to the Prosody config before using mod_http_muc_kick"
9 );
10
11 local function is_authorized(request)
12 return request.headers.authorization == authorization;
13 end
14
15 local function check_muc(jid)
16 local muc_node, host = jid_split(jid);
17
18 if not hosts[host] then
19 return nil, nil, "No such host: "..host;
20 elseif not hosts[host].modules.muc then
21 return nil, nil, "Host '"..host.."' is not a MUC service";
22 end
23
24 return muc_node, host;
25 end
26
27 local function get_muc(muc_jid)
28 local muc_node, host, err = check_muc(muc_jid);
29 if not muc_node then
30 return nil, host, err;
31 end
32
33 muc = prosody.hosts[host].modules.muc.get_room_from_jid(muc_jid);
34 if not muc then
35 return nil, host, "No MUC '"..muc_node.."' found for host: "..host;
36 end
37
38 return muc;
39 end
40
41 local function handle_error(response, status_code, error)
42 response.headers.content_type = "application/json";
43 response.status_code = status_code;
44 response:send(json.encode({error = error}));
45
46 -- return true to keep the connection open, and prevent other handlers from executing.
47 -- https://prosody.im/doc/developers/http#return_value
48 return true;
49 end
50
51 module:provides("http", {
52 route = {
53 ["POST"] = function (event)
54 local request, response = event.request, event.response;
55
56 if not is_authorized(request) then
57 return handle_error(response, 401, "Authorization failed");
58 end
59
60 local body = json.decode(request.body or "") or {};
61 if not body then
62 return handle_error(response, 400, "JSON body not found");
63 end
64
65 local nickname, muc_jid, reason = body.nickname, body.muc, body.reason or "";
66 if not nickname or not muc_jid then
67 return handle_error(response, 400, "Missing nickname and/or MUC");
68 end
69
70 local muc, _, err = get_muc(muc_jid);
71 if not muc then
72 return handle_error(response, 404, "MUC not found: " .. err);
73 end
74
75 local occupant_jid = muc.jid .. "/" .. nickname;
76
77 -- Kick user by giving them the "none" role
78 -- https://xmpp.org/extensions/xep-0045.html#kick
79 local success, error, condition = muc:set_role(true, occupant_jid, nil, reason);
80 if not success then
81 return handle_error(response, 400, "Coudln't kick user: ".. error .. ": " .. condition);
82 end
83
84 -- Kick was successful
85 return 200;
86 end;
87 };
88 });