Automated merge with http://waqas.ath.cx:8000/
[prosody.git] / core / usermanager.lua
1 -- Prosody IM v0.2
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21
22 require "util.datamanager"
23 local datamanager = datamanager;
24 local log = require "util.logger".init("usermanager");
25 local error = error;
26 local hashes = require "util.hashes";
27
28 module "usermanager"
29
30 function validate_credentials(host, username, password, method)
31         log("debug", "User '%s' is being validated", username);
32         local credentials = datamanager.load(username, host, "accounts") or {};
33         if method == nil then method = "PLAIN"; end
34         if method == "PLAIN" and credentials.password then -- PLAIN, do directly
35                 if password == credentials.password then
36                         return true;
37                 else
38                         return nil, "Auth failed. Invalid username or password.";
39                 end
40         end
41         -- must do md5
42         -- make credentials md5
43         local pwd = credentials.password;
44         if not pwd then pwd = credentials.md5; else pwd = hashes.md5(pwd, true); end
45         -- make password md5
46         if method == "PLAIN" then
47                 password = hashes.md5(password or "", true);
48         elseif method ~= "DIGEST-MD5" then
49                 return nil, "Unsupported auth method";
50         end
51         -- compare
52         if password == pwd then
53                 return true;
54         else
55                 return nil, "Auth failed. Invalid username or password.";
56         end
57 end
58
59 function user_exists(username, host)
60         return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials
61 end
62
63 function create_user(username, password, host)
64         return datamanager.store(username, host, "accounts", {password = password});
65 end
66
67 function get_supported_methods(host)
68         local methods = {["PLAIN"] = true}; -- TODO this should be taken from the config
69         methods["DIGEST-MD5"] = true;
70         return methods;
71 end
72
73 return _M;