Bumper commit for the new modulemanager API \o/ Updates all the modules, though some...
[prosody.git] / core / usermanager.lua
1
2 require "util.datamanager"
3 local datamanager = datamanager;
4 local log = require "util.logger".init("usermanager");
5 local error = error;
6 local hashes = require "util.hashes";
7
8 module "usermanager"
9
10 function validate_credentials(host, username, password, method)
11         log("debug", "User '%s' is being validated", username);
12         local credentials = datamanager.load(username, host, "accounts") or {};
13         if method == nil then method = "PLAIN"; end
14         if method == "PLAIN" and credentials.password then -- PLAIN, do directly
15                 if password == credentials.password then
16                         return true;
17                 else
18                         return nil, "Auth failed. Invalid username or password.";
19                 end
20         end
21         -- must do md5
22         if not hashes.md5 then
23                 return nil, "Server misconfiguration, the md5 library is not available.";
24         end
25         -- make credentials md5
26         local pwd = credentials.password;
27         if not pwd then pwd = credentials.md5; else pwd = hashes.md5(pwd); end
28         -- make password md5
29         if method == "PLAIN" then
30                 password = hashes.md5(password or "");
31         elseif method ~= "DIGEST-MD5" then
32                 return nil, "Unsupported auth method";
33         end
34         -- compare
35         if password == pwd then
36                 return true;
37         else
38                 return nil, "Auth failed. Invalid username or password.";
39         end
40 end
41
42 function user_exists(username, host)
43         return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials
44 end
45
46 function create_user(username, password, host)
47         return datamanager.store(username, host, "accounts", {password = password});
48 end
49
50 function get_supported_methods(host)
51         local methods = {["PLAIN"] = true}; -- TODO this should be taken from the config
52         if hashes.md5 then
53                 methods["DIGEST-MD5"] = true;
54         end
55         return methods;
56 end
57
58 return _M;