Merging SASL buggy client workaround with current tip.
[prosody.git] / core / usermanager.lua
1 -- Prosody IM v0.4
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10
11 require "util.datamanager"
12 local datamanager = datamanager;
13 local log = require "util.logger".init("usermanager");
14 local type = type;
15 local error = error;
16 local ipairs = ipairs;
17 local hashes = require "util.hashes";
18 local jid_bare = require "util.jid".bare;
19 local config = require "core.configmanager";
20
21 module "usermanager"
22
23 function validate_credentials(host, username, password, method)
24         log("debug", "User '%s' is being validated", username);
25         local credentials = datamanager.load(username, host, "accounts") or {};
26         if method == nil then method = "PLAIN"; end
27         if method == "PLAIN" and credentials.password then -- PLAIN, do directly
28                 if password == credentials.password then
29                         return true;
30                 else
31                         return nil, "Auth failed. Invalid username or password.";
32                 end
33         end
34         -- must do md5
35         -- make credentials md5
36         local pwd = credentials.password;
37         if not pwd then pwd = credentials.md5; else pwd = hashes.md5(pwd, true); end
38         -- make password md5
39         if method == "PLAIN" then
40                 password = hashes.md5(password or "", true);
41         elseif method ~= "DIGEST-MD5" then
42                 return nil, "Unsupported auth method";
43         end
44         -- compare
45         if password == pwd then
46                 return true;
47         else
48                 return nil, "Auth failed. Invalid username or password.";
49         end
50 end
51
52 function user_exists(username, host)
53         return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials
54 end
55
56 function create_user(username, password, host)
57         return datamanager.store(username, host, "accounts", {password = password});
58 end
59
60 function get_supported_methods(host)
61         local methods = {["PLAIN"] = true}; -- TODO this should be taken from the config
62         methods["DIGEST-MD5"] = true;
63         return methods;
64 end
65
66 function is_admin(jid)
67         local admins = config.get("*", "core", "admins") or {};
68         if type(admins) == "table" then
69                 jid = jid_bare(jid);
70                 for _,admin in ipairs(admins) do
71                         if admin == jid then return true; end
72                 end
73         else log("debug", "Option core.admins is not a table"); end
74         return nil;
75 end
76
77 return _M;