Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rest api #78

Merged
merged 8 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ PROJECT_DESCRIPTION = EMQ X Authentication with ClientId/Password
CUR_BRANCH := $(shell git branch | grep -e "^*" | cut -d' ' -f 2)
BRANCH := $(if $(filter $(CUR_BRANCH), master develop), $(CUR_BRANCH), develop)

DEPS = emqx_passwd clique
DEPS = emqx_passwd clique minirest
dep_emqx_passwd = git-emqx https://github.com/emqx/emqx-passwd v1.0
dep_clique = git-emqx https://github.com/emqx/clique v0.3.11
dep_minirest = git-emqx https://github.com/emqx/minirest v0.2.2

BUILD_DEPS = emqx cuttlefish
dep_emqx = git-emqx https://github.com/emqx/emqx $(BRANCH)
dep_cuttlefish = git-emqx https://github.com/emqx/cuttlefish v2.2.1

TEST_DEPS = emqx_ct_helper emqx_management
dep_emqx_ct_helper = git-emqx https://github.com/emqx/emqx-ct-helpers $(BRANCH)
dep_emqx_management = git-emqx https://github.com/emqx/emqx-management $(BRANCH)

NO_AUTOPATCH = cuttlefish

ERLC_OPTS += +debug_info
Expand Down
73 changes: 73 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,79 @@ etc/emqx_auth_clientid.conf:
auth.client.password_hash = sha256
```

[REST API](https://developer.emqx.io/docs/emq/v3/en/rest.html)
------------

List all clientids:
```
# Request
GET api/v3/auth_clientid

# Response
{
"code": 0,
"data": ["username1"]
}
```

Add cliendid:
```
# Request
POST api/v3/auth_clientid
{
"clientid": "a_client_id",
"password": "password"
}

# Response
{
"code": 0
}
```

Update password for a clientid:

```
# Request
PUT api/v3/auth_clientid/$CLIENTID

{
"password": "password"
}

# Response
{
"code": 0
}

```

Lookup a clientid info:
```
# Request
GET api/v3/auth_clientid/$CLIENTID

# Response
{
"code": 0,
"data": {
"clientid": "a_client_id",
"password": "hash_password"
}
}
```

Delete a clientid:

```
# Request
DELETE api/v3/auth_clientid/$CLIENTID

# Response
{
"code": 0
}

```

Load the Plugin
Expand Down
5 changes: 5 additions & 0 deletions src/emqx_auth_clientid.erl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
, description/0
]).

-export([unwrap_salt/1]).

-define(TAB, ?MODULE).
-record(?TAB, {client_id, password}).
-define(UNDEFINED(S), (S =:= undefined)).
Expand Down Expand Up @@ -149,6 +151,9 @@ check(Credentials = #{client_id := ClientId, password := Password}, #{hash_type
end
end.

unwrap_salt(<<_Salt:4/binary, HashPasswd/binary>>) ->
HashPasswd.

description() ->
"ClientId Authentication Module".

Expand Down
122 changes: 122 additions & 0 deletions src/emqx_auth_clientid_api.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
%% Copyright (c) 2013-2019 EMQ Technologies Co., Ltd. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.

-module(emqx_auth_clientid_api).

-include("emqx_auth_clientid.hrl").

-import(proplists, [get_value/2]).
-import(minirest, [return/0, return/1]).

-rest_api(#{ name => list_clientid
, method => 'GET'
, path => "/auth_clientid"
, func => list
, descr => "List available clientid in the cluster"
}).

-rest_api(#{ name => lookup_clientid
, method => 'GET'
, path => "/auth_clientid/:bin:clientid"
, func => lookup
, descr => "Lookup clientid in the cluster"
}).

-rest_api(#{ name => add_clientid
, method => 'POST'
, path => "/auth_clientid"
, func => add
, descr => "Add clientid in the cluster"
}).

-rest_api(#{ name => update_clientid
, method => 'PUT'
, path => "/auth_clientid/:bin:clientid"
, func => update
, descr => "Update clientid in the cluster"
}).

-rest_api(#{ name => delete_clientid
, method => 'DELETE'
, path => "/auth_clientid/:bin:clientid"
, func => delete
, descr => "Delete clientid in the cluster"
}).

-export([ list/2
, lookup/2
, add/2
, update/2
, delete/2
]).

list(_Bindings, _Params) ->
return({ok, emqx_auth_clientid:all_clientids()}).

lookup(#{clientid := ClientId}, _Params) ->
return({ok, format(emqx_auth_clientid:lookup_clientid(ClientId))}).

add(_Bindings, Params) ->
ClientId = get_value(<<"clientid">>, Params),
Password = get_value(<<"password">>, Params),
case validate([clientid, password], [ClientId, Password]) of
ok ->
case emqx_auth_clientid:add_clientid(ClientId, Password) of
ok -> return();
Error -> return(Error)
end;
Error -> return(Error)
end.

update(#{clientid := ClientId}, Params) ->
Password = get_value(<<"password">>, Params),
case validate([password], [Password]) of
ok ->
case emqx_auth_clientid:update_password(ClientId, Password) of
ok -> return();
Error -> return(Error)
end;
Error -> return(Error)
end.

delete(#{clientid := ClientId}, _) ->
case emqx_auth_clientid:remove_clientid(ClientId) of
ok -> return();
Error -> return(Error)
end.

%%------------------------------------------------------------------------------
%% Interval Funcs
%%------------------------------------------------------------------------------

format([{?APP, ClientId, Password}]) ->
[{clientid, ClientId},
{password, emqx_auth_clientid:unwrap_salt(Password)}].

validate([], []) ->
ok;
validate([K|Keys], [V|Values]) ->
case validation(K, V) of
false -> {error, K};
true -> validate(Keys, Values)
end.

validation(clientid, V) when is_binary(V)
andalso byte_size(V) > 0 ->
true;
validation(password, V) when is_binary(V)
andalso byte_size(V) > 0 ->
true;
validation(_, _) ->
false.
102 changes: 53 additions & 49 deletions test/emqx_auth_clientid_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -20,63 +20,37 @@

-include_lib("common_test/include/ct.hrl").

-import(emqx_ct_http, [ request_api/3
, request_api/4
, request_api/5
, get_http_data/1
, create_default_app/0
, default_auth_header/0]).

-define(HOST, "http://127.0.0.1:8080/").

-define(API_VERSION, "v3").

-define(BASE_PATH, "api").

all() ->
[{group, emqx_auth_clientid}].

groups() ->
[{emqx_auth_clientid, [sequence], [emqx_auth_clientid_api, cli, change_config]}].
[{emqx_auth_clientid, [sequence], [emqx_auth_clientid_api, cli, change_config, t_http_api]}].

init_per_suite(Config) ->
[start_apps(App, {SchemaFile, ConfigFile}) ||
{App, SchemaFile, ConfigFile}
<- [{emqx, deps_path(emqx, "priv/emqx.schema"),
deps_path(emqx, "etc/emqx.conf")},
{emqx_auth_clientid, local_path("priv/emqx_auth_clientid.schema"),
local_path("etc/emqx_auth_clientid.conf")}]],
emqx_ct_helpers:start_apps([emqx, emqx_auth_clientid, emqx_management], [{plugins_loaded_file, emqx, "test/emqx_SUITE_data/loaded_plugins"}]),
application:set_env(emqx, allow_anonymous, false),
application:set_env(emqx, enable_acl_cache, false),
ekka_mnesia:start(),
emqx_mgmt_auth:mnesia(boot),
create_default_app(),
Config.

end_per_suite(_Config) ->
application:stop(emqx_auth_clientid),
application:stop(emqx).

% get_base_dir() ->
% {file, Here} = code:is_loaded(?MODULE),
% filename:dirname(filename:dirname(Here)).

deps_path(App, RelativePath) ->
%% Note: not lib_dir because etc dir is not sym-link-ed to _build dir
%% but priv dir is
Path0 = code:priv_dir(App),
Path = case file:read_link(Path0) of
{ok, Resolved} -> Resolved;
{error, _} -> Path0
end,
filename:join([Path, "..", RelativePath]).

local_path(RelativePath) ->
% filename:join([get_base_dir(), RelativePath]).
deps_path(emqx_auth_clientid, RelativePath).

start_apps(App, {SchemaFile, ConfigFile}) ->
read_schema_configs(App, {SchemaFile, ConfigFile}),
set_special_configs(App),
application:ensure_all_started(App).

read_schema_configs(App, {SchemaFile, ConfigFile}) ->
ct:pal("Read configs - SchemaFile: ~p, ConfigFile: ~p", [SchemaFile, ConfigFile]),
Schema = cuttlefish_schema:files([SchemaFile]),
Conf = conf_parse:file(ConfigFile),
NewConfig = cuttlefish_generator:map(Schema, Conf),
Vals = proplists:get_value(App, NewConfig, []),
[application:set_env(App, Par, Value) || {Par, Value} <- Vals].

set_special_configs(emqx) ->
application:set_env(emqx, allow_anonymous, false),
application:set_env(emqx, enable_acl_cache, false),
application:set_env(emqx, plugins_loaded_file,
deps_path(emqx, "test/emqx_SUITE_data/loaded_plugins"));
set_special_configs(_App) ->
ok.
emqx_ct_helpers:stop_apps([emqx_auth_clientid, emqx_management, emqx]),
ekka_mnesia:ensure_stopped().

emqx_auth_clientid_api(_Config) ->
ok = emqx_auth_clientid:add_clientid(<<"emq_auth_clientid">>, <<"password">>),
Expand Down Expand Up @@ -121,11 +95,41 @@ cli(_Config) ->
case Hash1 =:= emqx_passwd:hash(HashType, <<Salt1/binary, <<"newpassword">>/binary>>) of
true -> ok;
false -> ct:fail("password error")
end,
end,
emqx_auth_clientid:cli(["del", "clientid"]),
[] = emqx_auth_clientid:lookup_clientid(<<"clientid">>),
emqx_auth_clientid:cli(["add", "user1", "pass1"]),
emqx_auth_clientid:cli(["add", "user2", "pass2"]),
UserList = emqx_auth_clientid:cli(["list"]),
2 = length(UserList),
emqx_auth_clientid:cli(usage).

t_http_api(_Config) ->
[mnesia:dirty_delete({emqx_auth_clientid, ClientId}) || ClientId <- mnesia:dirty_all_keys(emqx_auth_clientid)],
{ok, Result} = request_api(get, api_path(["auth_clientid"]), default_auth_header()),
[] = get_http_data(Result),
{ok, _} = request_api(post, api_path(["auth_clientid"]), [], default_auth_header(), [{<<"clientid">>, <<"clientid">>},
{<<"password">>, <<"password">>}]),
{ok, Result1} = request_api(get, api_path(["auth_clientid", "clientid"]), default_auth_header()),
[_, {<<"password">>, Hash}] = get_http_data(Result1),
[{emqx_auth_clientid, <<"clientid">>, <<Salt:4/binary, _Hash/binary>>}] =
emqx_auth_clientid:lookup_clientid(<<"clientid">>),
HashType = application:get_env(emqx_auth_clientid, password_hash, sha256),
case Hash =:= emqx_passwd:hash(HashType, <<Salt/binary, <<"password">>/binary>>) of
true -> ok;
false -> ct:fail("password error")
end,
{ok, _} = request_api(put, api_path(["auth_clientid", "clientid"]), [], default_auth_header(), [{<<"password">>, <<"newpassword">>}]),
[{emqx_auth_clientid, <<"clientid">>, <<Salt1:4/binary, Hash1/binary>>}] =
emqx_auth_clientid:lookup_clientid(<<"clientid">>),
HashType1 = application:get_env(emqx_auth_clientid, password_hash, sha256),
case Hash1 =:= emqx_passwd:hash(HashType1, <<Salt1/binary, <<"newpassword">>/binary>>) of
true -> ok;
false -> ct:fail("password error")
end,
{ok, _} = request_api(delete, api_path(["auth_clientid", "clientid"]), default_auth_header()),
[] = emqx_auth_clientid:lookup_clientid(<<"clientid">>),
ok.

api_path(Parts) ->
?HOST ++ filename:join([?BASE_PATH, ?API_VERSION] ++ Parts).