2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local st = require "util.stanza";
12 local t_concat = table.concat;
14 local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption");
16 local sessionmanager = require "core.sessionmanager";
17 local usermanager = require "core.usermanager";
18 local nodeprep = require "util.encodings".stringprep.nodeprep;
19 local resourceprep = require "util.encodings".stringprep.resourceprep;
21 module:add_feature("jabber:iq:auth");
22 module:hook("stream-features", function(event)
23 local origin, features = event.origin, event.features;
24 if secure_auth_only and not origin.secure then
25 -- Sorry, not offering to insecure streams!
27 elseif not origin.username then
28 features:tag("auth", {xmlns='http://jabber.org/features/iq-auth'}):up();
32 module:add_iq_handler("c2s_unauthed", "jabber:iq:auth",
33 function (session, stanza)
34 if secure_auth_only and not session.secure then
35 session.send(st.error_reply(stanza, "modify", "not-acceptable", "Encryption (SSL or TLS) is required to connect to this server"));
39 local username = stanza.tags[1]:child_with_name("username");
40 local password = stanza.tags[1]:child_with_name("password");
41 local resource = stanza.tags[1]:child_with_name("resource");
42 if not (username and password and resource) then
43 local reply = st.reply(stanza);
44 session.send(reply:query("jabber:iq:auth")
47 :tag("resource"):up());
49 username, password, resource = t_concat(username), t_concat(password), t_concat(resource);
50 username = nodeprep(username);
51 resource = resourceprep(resource)
52 local reply = st.reply(stanza);
53 if usermanager.validate_credentials(session.host, username, password) then
54 -- Authentication successful!
55 local success, err = sessionmanager.make_authenticated(session, username);
57 local err_type, err_msg;
58 success, err_type, err, err_msg = sessionmanager.bind_resource(session, resource);
60 session.send(st.error_reply(stanza, err_type, err, err_msg));
61 session.username, session.type = nil, "c2s_unauthed"; -- FIXME should this be placed in sessionmanager?
63 elseif resource ~= session.resource then -- server changed resource, not supported by legacy auth
64 session.send(st.error_reply(stanza, "cancel", "conflict", "The requested resource could not be assigned to this session."));
65 session:close(); -- FIXME undo resource bind and auth instead of closing the session?
69 session.send(st.reply(stanza));
71 session.send(st.error_reply(stanza, "auth", "not-authorized"));