./ct_report/coverage/mongoose_admin_api_sessions.COVER.html

1 -module(mongoose_admin_api_sessions).
2
3 -behaviour(mongoose_admin_api).
4 -export([routes/1]).
5
6 -behaviour(cowboy_rest).
7 -export([init/2,
8 is_authorized/2,
9 content_types_provided/2,
10 allowed_methods/2,
11 to_json/2,
12 delete_resource/2]).
13
14 -ignore_xref([to_json/2, from_json/2]).
15
16 -import(mongoose_admin_api, [try_handle_request/3, throw_error/2]).
17
18 -type req() :: cowboy_req:req().
19 -type state() :: mongoose_admin_api:state().
20
21 -spec routes(state()) -> mongoose_http_handler:routes().
22 routes(State) ->
23 49 [{"/sessions/:domain/[:username]/[:resource]", ?MODULE, State}].
24
25 -spec init(req(), state()) -> {cowboy_rest, req(), state()}.
26 init(Req, State) ->
27 7 mongoose_admin_api:init(Req, State).
28
29 -spec is_authorized(req(), state()) -> {true | {false, iodata()}, req(), state()}.
30 is_authorized(Req, State) ->
31 7 mongoose_admin_api:is_authorized(Req, State).
32
33 -spec content_types_provided(req(), state()) ->
34 {[{{binary(), binary(), '*'}, atom()}], req(), state()}.
35 content_types_provided(Req, State) ->
36 7 {[
37 {{<<"application">>, <<"json">>, '*'}, to_json}
38 ], Req, State}.
39
40 -spec allowed_methods(req(), state()) -> {[binary()], req(), state()}.
41 allowed_methods(Req, State) ->
42 7 {[<<"OPTIONS">>, <<"GET">>, <<"DELETE">>], Req, State}.
43
44 %% @doc Called for a method of type "GET"
45 -spec to_json(req(), state()) -> {iodata() | stop, req(), state()}.
46 to_json(Req, State) ->
47 3 try_handle_request(Req, State, fun handle_get/2).
48
49 %% @doc Called for a method of type "DELETE"
50 -spec delete_resource(req(), state()) -> {true | stop, req(), state()}.
51 delete_resource(Req, State) ->
52 4 try_handle_request(Req, State, fun handle_delete/2).
53
54 %% Internal functions
55
56 handle_get(Req, State) ->
57 3 #{domain := Domain} = cowboy_req:bindings(Req),
58 3 {ok, Sessions} = mongoose_session_api:list_resources(Domain),
59 3 {jiffy:encode(Sessions), Req, State}.
60
61 handle_delete(Req, State) ->
62 4 #{domain := Domain} = Bindings = cowboy_req:bindings(Req),
63 4 UserName = get_user_name(Bindings),
64 2 Resource = get_resource(Bindings),
65 2 case mongoose_session_api:kick_session(jid:make(UserName, Domain, Resource), <<"kicked">>) of
66 {ok, _} ->
67 1 {true, Req, State};
68 {no_session, Reason} ->
69 1 throw_error(not_found, Reason)
70 end.
71
72 2 get_user_name(#{username := UserName}) -> UserName;
73 2 get_user_name(#{}) -> throw_error(bad_request, <<"Missing user name">>).
74
75 %% Resource is matched first, so it is not possible for it to be missing
76 2 get_resource(#{resource := Resource}) -> Resource.
Line Hits Source