Skip to content
This repository has been archived by the owner on Jul 28, 2022. It is now read-only.

Commit

Permalink
json response for login provider
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabio Mascarenhas committed Mar 24, 2010
1 parent 438cb14 commit 373e77f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/mk/auth.lua
Expand Up @@ -83,12 +83,23 @@ function methods:provider()
end
local expires = (data.persistent and (os.time() + self.expiration)) or nil
local user, message = self:login(data.username, data.password)
local redirect_or_json = function (url)
if url then
return res:redirect(url)
else
res:content_type("application/json")
res:write(json.encode{ user = user,
message = message,
expires = expires })
return res:finish()
end
end
if user then
res:set_cookie(self.cookie_name, { value = message, expires = expires })
return res:redirect(data.success)
return redirect_or_json(data.success)
else
res:delete_cookie(self.cookie_name)
return res:redirect(data.failure .. "?message=" .. util.url_encode(message))
return redirect_or_json(data.failure and data.failure .. "?message=" .. util.url_encode(message))
end
end
end
Expand Down
30 changes: 30 additions & 0 deletions test/test_auth.lua
Expand Up @@ -121,6 +121,22 @@ do
assert(user == "mascarenhas")
end

do
-- successful login with json data, json response
local a = auth.new{ login = login, login_salt = login_salt,
session_salt = session_salt }
local env = util.make_env_post("json=" .. json.encode({ username = "mascarenhas",
password = "foobar" }))
local status, headers, res = a:provider()(env)
assert(status == 200)
local res = json.decode(res())
local cookie = util.url_decode(headers["Set-Cookie"]:match("mk_auth_user=(.+)"))
local user, message = a:authenticate(cookie)
assert(user == "mascarenhas")
assert(res.user == user)
assert(a:authenticate(res.message) == user)
end

do
-- successful login with json data, change cookie name
local a = auth.new{ login = login, login_salt = login_salt,
Expand Down Expand Up @@ -168,6 +184,20 @@ do
assert(headers["Set-Cookie"]:match("mk_auth_user=xxx"))
end

do
-- bad login with json data, wrong password, json response
local a = auth.new{ login = login, login_salt = login_salt,
session_salt = session_salt }
local env = util.make_env_post("json=" .. json.encode({ username = "mascarenhas",
password = "foo" }))
local status, headers, res = a:provider()(env)
assert(status == 200)
assert(headers["Set-Cookie"]:match("mk_auth_user=xxx"))
local res = json.decode(res())
assert(not res.user)
assert(res.message == "invalid password")
end

do
-- bad login with json data, unknown user
local a = auth.new{ login = login, login_salt = login_salt,
Expand Down

0 comments on commit 373e77f

Please sign in to comment.