http post support

This commit is contained in:
Feng Lee 2014-12-07 14:56:46 +08:00
parent 4e01e12e25
commit 3865833156
4 changed files with 58 additions and 4 deletions

View File

@ -51,6 +51,11 @@ logs
log/*
http api
========
curl -v --basic -u user:passwd -d "topic=/abc&message=akakakk&qos=0" -k http://localhost:8883/mqtt/publish
design
=====

View File

@ -41,14 +41,14 @@ check(undefined, _) -> false;
check(_, undefined) -> false;
check(Username, Password) when is_binary(Username) ->
PasswdHash = crypto:md5(Password),
PasswdHash = crypto:hash(md5, Password),
case mnesia:dirty_read(internal_user, Username) of
[#internal_user{passwdhash=PasswdHash}] -> true;
_ -> false
end.
add(Username, Password) when is_binary(Username) and is_binary(Password) ->
mnesia:dirty_write(#internal_user{username=Username, passwdhash=crypto:md5(Password)}).
mnesia:dirty_write(#internal_user{username=Username, passwdhash=crypto:hash(md5, Password)}).
delete(Username) when is_binary(Username) ->
mnesia:dirty_delete(internal_user, Username).

View File

@ -22,8 +22,57 @@
-module(emqtt_http).
-include("emqtt.hrl").
-import(proplists, [get_value/2, get_value/3]).
-export([handle/2]).
handle(Req, Auth) ->
Req:not_found().
case authorized(Req, Auth) of
true ->
Path = Req:get(path),
Method = Req:get(method),
handle(Method, Path, Req);
false ->
error_logger:info_msg("Fobbidden"),
Req:respond({401, [], <<"Fobbiden">>})
end.
handle('POST', "/mqtt/publish", Req) ->
Params = mochiweb_request:parse_post(Req),
error_logger:info_msg("~p~n", [Params]),
Topic = get_value("topic", Params),
Message = list_to_binary(get_value("message", Params)),
Qos = list_to_integer(get_value("qos", Params, "0")),
%TODO: DUP, RETAIN...
emqtt_router:publish(Topic, #mqtt_msg {
retain = 0,
qos = Qos,
topic = Topic,
dup = 0,
payload = Message
}),
Req:ok({"text/plan", "ok"});
handle(_Method, _Path, Req) ->
Req:not_found().
%%------------------------------------------------------------------------------
%% basic authorization
%%------------------------------------------------------------------------------
authorized(Req, {Username, Password}) ->
case mochiweb_request:get_header_value("Authorization", Req) of
undefined -> false;
"Basic " ++ BasicAuth ->
case user_passwd(BasicAuth) of
{Username, Password} -> true;
_ -> false
end
end.
user_passwd(BasicAuth) ->
[U, P] = binary:split(base64:decode(BasicAuth), <<":">>),
{binary_to_list(U), binary_to_list(P)}.

View File

@ -41,7 +41,7 @@
{http, 8883, [
{max_conns, 512},
{acceptor_pool, 1},
{auth, {"username", "passwd"}}
{auth, {"user", "passwd"}}
]}
]}
]}