Comparison

mod_register_json/register_json/mod_register_json.lua @ 989:7c04c5856daa

mod_register_json: major code overhaul into a token based registration & verification system.
author Marco Cirillo <maranda@lightwitch.org>
date Mon, 29 Apr 2013 22:53:39 +0200
child 991:929dcf3c4bcb
comparison
equal deleted inserted replaced
988:c15cea87036f 989:7c04c5856daa
1 -- Expose a simple token based servlet to handle user registrations from web pages
2 -- through Base64 encoded JSON.
3
4 -- Copyright (C) 2010 - 2013, Marco Cirillo (LW.Org)
5
6 local datamanager = datamanager
7 local b64_decode = require "util.encodings".base64.decode
8 local b64_encode = require "util.encodings".base64.encode
9 local http_event = require "net.http.server".fire_event
10 local jid_prep = require "util.jid".prep
11 local jid_split = require "util.jid".split
12 local json_decode = require "util.json".decode
13 local nodeprep = require "util.encodings".stringprep.nodeprep
14 local open, os_time, setmt, type = io.open, os.time, setmetatable, type
15 local sha1 = require "util.hashes".sha1
16 local urldecode = http.urldecode
17 local usermanager = usermanager
18 local uuid_gen = require "util.uuid".generate
19 local timer = require "util.timer"
20
21 module:depends("http")
22
23 -- Pick up configuration and setup stores/variables.
24
25 local auth_token = module:get_option_string("reg_servlet_auth_token")
26 local secure = module:get_option_boolean("reg_servlet_secure", true)
27 local base_path = module:get_option_string("reg_servlet_base", "/register_account/")
28 local throttle_time = module:get_option_number("reg_servlet_ttime", nil)
29 local whitelist = module:get_option_set("reg_servlet_wl", {})
30 local blacklist = module:get_option_set("reg_servlet_bl", {})
31 local fm_patterns = module:get_option("reg_servlet_filtered_mails", {})
32 if type(fm_patterns) ~= "table" then fm_patterns = {} end
33
34 local files_base = module.path:gsub("/[^/]+$","") .. "/template/"
35
36 local recent_ips = {}
37 local pending = {}
38 local pending_node = {}
39
40 -- Setup hashes data structure
41
42 hashes = { _index = {} }
43 local hashes_mt = {} ; hashes_mt.__index = hashes_mt
44 function hashes_mt:add(node, mail)
45 local _hash = b64_encode(sha1(mail))
46 if not self:exists(_hash) then
47 self[_hash] = node ; self._index[node] = _hash ; self:save()
48 return true
49 else
50 return false
51 end
52 end
53 function hashes_mt:exists(hash)
54 if hashes[hash] then return true else return false end
55 end
56 function hashes_mt:remove(node)
57 local _hash = self._index[node]
58 if _hash then
59 self[_hash] = nil ; self._index[node] = nil ; self:save()
60 end
61 end
62 function hashes_mt:save()
63 if not datamanager.store("register_json", module.host, "hashes", hashes) then
64 module:log("error", "Failed to save the mail addresses' hashes store.")
65 end
66 end
67
68 local function check_mail(address)
69 for _, pattern in ipairs(fm_patterns) do
70 if address:match(pattern) then return false end
71 end
72 return true
73 end
74
75 -- Begin
76
77 local function handle(code, message) return http_event("http-error", { code = code, message = message }) end
78 local function http_response(event, code, message, headers)
79 local response = event.response
80
81 if headers then
82 for header, data in pairs(headers) do response.headers[header] = data end
83 end
84
85 response.status_code = code
86 response:send(handle(code, message))
87 end
88
89 local function handle_req(event)
90 local response = event.response
91 local request = event.request
92 local body = request.body
93 if secure and not request.secure then return nil end
94
95 if request.method ~= "POST" then
96 return http_response(event, 405, "Bad method.", {["Allow"] = "POST"})
97 end
98
99 local req_body
100 -- We check that what we have is valid JSON wise else we throw an error...
101 if not pcall(function() req_body = json_decode(b64_decode(body)) end) then
102 module:log("debug", "Data submitted for user registration by %s failed to Decode.", user)
103 return http_response(event, 400, "Decoding failed.")
104 else
105 -- Decode JSON data and check that all bits are there else throw an error
106 if req_body["username"] == nil or req_body["password"] == nil or req_body["ip"] == nil or req_body["mail"] == nil or
107 req_body["auth_token"] == nil then
108 module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user)
109 return http_response(event, 400, "Invalid syntax.")
110 end
111 -- Set up variables
112 local username, password, ip, mail, token = req_body.username, req_body.password, req_body.ip, req_body.mail, req_body.auth_token
113
114 -- Check if user is an admin of said host
115 if token ~= auth_token then
116 module:log("warn", "%s tried to retrieve a registration token for %s@%s", request.ip, username, module.host)
117 return http_response(event, 401, "Auth token is invalid! The attempt has been logged.")
118 else
119 -- Blacklist can be checked here.
120 if blacklist:contains(ip) then
121 module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", ip)
122 return http_response(403, "The specified address is blacklisted, sorry.")
123 end
124
125 if not check_mail(mail) then
126 module:log("warn", "%s attempted to use a mail address (%s) matching one of the forbidden patterns.", ip, mail)
127 return http_response(403, "Requesting to register using this E-Mail address is forbidden, sorry.")
128 end
129
130 -- We first check if the supplied username for registration is already there.
131 -- And nodeprep the username
132 username = nodeprep(username)
133 if not username then
134 module:log("debug", "An username containing invalid characters was supplied: %s", req_body["username"])
135 return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.")
136 else
137 if pending_node[username] then
138 module:log("warn", "%s attempted to submit a registration request but another request for that user is pending")
139 return http_response(event, 401, "Another user registration by that username is pending.")
140 end
141
142 if not usermanager.user_exists(username, module.host) then
143 -- if username fails to register successive requests shouldn't be throttled until one is successful.
144 if throttle_time and not whitelist:contains(ip) then
145 if not recent_ips[ip] then
146 recent_ips[ip] = os_time()
147 else
148 if os_time() - recent_ips[ip] < throttle_time then
149 recent_ips[ip] = os_time()
150 module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"])
151 return http_response(event, 503, "Request throttled, wait a bit and try again.")
152 end
153 recent_ips[ip] = os_time()
154 end
155 end
156
157 local uuid = uuid_gen()
158 if not hashes:add(username, mail) then
159 module:log("warn", "%s (%s) attempted to register to the server with an E-Mail address we already possess the hash of.", username, ip)
160 return http_response(event, 409, "The E-Mail Address provided matches the hash associated to an existing account.")
161 end
162 pending[uuid] = { node = username, password = password, ip = ip }
163 pending_node[username] = uuid
164
165 timer.add_task(300, function()
166 if pending[uuid] then
167 pending[uuid] = nil
168 pending_node[username] = nil
169 hashes:remove(username)
170 end
171 end)
172 module:log("info", "%s (%s) submitted a registration request and is awaiting final verification", username, uuid)
173 return uuid
174 else
175 module:log("debug", "%s registration data submission failed (user already exists)", username)
176 return http_response(event, 409, "User already exists.")
177 end
178 end
179 end
180 end
181 end
182
183 local function open_file(file)
184 local f, err = open(file, "rb");
185 if not f then return nil end
186
187 local data = f:read("*a") ; f:close()
188 return data
189 end
190
191 local function r_template(event, type)
192 local response = event.response
193
194 local data = open_file(files_base..type.."_t.html")
195 if data then
196 data = data:gsub("%%REG%-URL", base_path.."verify/")
197 return data
198 else return http_response(event, 500, "Failed to obtain template.") end
199 end
200
201 local function handle_verify(event, path)
202 local response = event.response
203 local request = event.request
204 local body = request.body
205 if secure and not request.secure then return nil end
206
207 local valid_files = {
208 ["css/style.css"] = files_base.."css/style.css",
209 ["images/tile.png"] = files_base.."images/tile.png",
210 ["images/header.png"] = files_base.."images/header.png"
211 }
212
213 if request.method == "GET" then
214 if path == "" then
215 return r_template(event, "form")
216 end
217
218 if valid_files[path] then
219 local data = open_file(valid_files[path])
220 if data then return data
221 else return http_response(event, 404, "Not found.") end
222 end
223 elseif request.method == "POST" then
224 if path == "" then
225 if not request.body then return http_response(event, 400, "Bad Request.") end
226 local uuid = urldecode(request.body):match("^uuid=(.*)$")
227
228 if not pending[uuid] then
229 return r_template(event, "fail")
230 else
231 local username, password, ip =
232 pending[uuid].node, pending[uuid].password, pending[uuid].ip
233
234 local ok, error = usermanager.create_user(username, password, module.host)
235 if ok then
236 module:fire_event(
237 "user-registered",
238 { username = username, host = module.host, source = "mod_register_json", session = { ip = ip } }
239 )
240 module:log("info", "Account %s@%s is successfully verified and activated", username, module.host)
241 -- we shall not clean the user from the pending lists as long as registration doesn't succeed.
242 pending[uuid] = nil ; pending_node[username] = nil
243 return r_template(event, "success")
244 else
245 module:log("error", "User creation failed: "..error)
246 return http_response(event, 500, "Encountered server error while creating the user: "..error)
247 end
248 end
249 end
250 else
251 return http_response(event, 405, "Invalid method.")
252 end
253 end
254
255 local function handle_user_deletion(event)
256 local user, hostname = event.username, event.host
257 if hostname == module.host then hashes:remove(user) end
258 end
259
260 -- Set it up!
261
262 hashes = datamanager.load("register_json", module.host, "hashes") or hashes ; setmt(hashes, hashes_mt)
263
264 module:provides("http", {
265 default_path = base_path,
266 route = {
267 ["GET /"] = handle_req,
268 ["POST /"] = handle_req,
269 ["GET /verify/*"] = handle_verify,
270 ["POST /verify/*"] = handle_verify
271 }
272 })
273
274 module:hook_global("user-deleted", handle_user_deletion, 10);
275
276 -- Reloadability
277
278 module.save = function() return { hashes = hashes } end
279 module.restore = function(data) hashes = data.hashes or { _index = {} } ; setmt(hashes, hashes_mt) end