Making the best attempt out of a bad merge from waqas
[prosody.git] / util / sasl.lua
1
2 local base64 = require "base64"
3 local log = require "util.logger".init("sasl");
4 local tostring = tostring;
5 local st = require "util.stanza";
6 local s_match = string.match;
7 module "sasl"
8
9
10 local function new_plain(onAuth, onSuccess, onFail, onWrite)
11         local object = { mechanism = "PLAIN", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail,
12                                         onWrite = onWrite}
13         --local challenge = base64.encode("");
14         --onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
15         object.feed =   function(self, stanza)
16                                                 if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
17                                                 if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end
18                                                 local response = base64.decode(stanza[1])
19                                                 local authorization = s_match(response, "([^&%z]+)")
20                                                 local authentication = s_match(response, "%z([^&%z]+)%z")
21                                                 local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
22                                                 if self.onAuth(authentication, password) == true then
23                                                         self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
24                                                         self.onSuccess(authentication)
25                                                 else
26                                                         self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure"));
27                                                 end
28                                         end
29         return object
30 end
31
32
33 function new(mechanism, onAuth, onSuccess, onFail, onWrite)
34         local object
35         if mechanism == "PLAIN" then object = new_plain(onAuth, onSuccess, onFail, onWrite)
36         else
37                 log("debug", "Unsupported SASL mechanism: "..tostring(mechanism));
38                 onFail("unsupported-mechanism")
39         end
40         return object
41 end
42
43 return _M;