1 |
|
%%%------------------------------------------------------------------- |
2 |
|
%%% @author ludwikbukowski |
3 |
|
%%% @copyright (C) 2016, Erlang Solutions Ltd. |
4 |
|
%%% Created : 20. Jul 2016 10:16 |
5 |
|
%%%------------------------------------------------------------------- |
6 |
|
%%% @doc Utilities for the REST API |
7 |
|
|
8 |
|
-module(mongoose_api_common). |
9 |
|
-author("ludwikbukowski"). |
10 |
|
|
11 |
|
%% API |
12 |
|
-export([get_auth_details/1, |
13 |
|
is_known_auth_method/1, |
14 |
|
make_unauthorized_response/2, |
15 |
|
check_password/2]). |
16 |
|
|
17 |
|
%%-------------------------------------------------------------------- |
18 |
|
%% Authorization |
19 |
|
%%-------------------------------------------------------------------- |
20 |
|
|
21 |
|
-spec get_auth_details(cowboy_req:req()) -> |
22 |
|
{basic, User :: binary(), Password :: binary()} | undefined. |
23 |
|
get_auth_details(Req) -> |
24 |
1043 |
case cowboy_req:parse_header(<<"authorization">>, Req) of |
25 |
|
{basic, _User, _Password} = Details -> |
26 |
241 |
Details; |
27 |
|
_ -> |
28 |
802 |
undefined |
29 |
|
end. |
30 |
|
|
31 |
|
-spec is_known_auth_method(atom()) -> boolean(). |
32 |
229 |
is_known_auth_method(basic) -> true; |
33 |
:-( |
is_known_auth_method(_) -> false. |
34 |
|
|
35 |
|
make_unauthorized_response(Req, State) -> |
36 |
19 |
{{false, <<"Basic realm=\"mongooseim\"">>}, Req, State}. |
37 |
|
|
38 |
|
-spec check_password(jid:jid() | error, binary()) -> {true, mongoose_credentials:t()} | false. |
39 |
|
check_password(error, _) -> |
40 |
:-( |
false; |
41 |
|
check_password(JID, Password) -> |
42 |
424 |
{LUser, LServer} = jid:to_lus(JID), |
43 |
424 |
case mongoose_domain_api:get_domain_host_type(LServer) of |
44 |
|
{ok, HostType} -> |
45 |
423 |
Creds0 = mongoose_credentials:new(LServer, HostType, #{}), |
46 |
423 |
Creds1 = mongoose_credentials:set(Creds0, username, LUser), |
47 |
423 |
Creds2 = mongoose_credentials:set(Creds1, password, Password), |
48 |
423 |
case ejabberd_auth:authorize(Creds2) of |
49 |
423 |
{ok, Creds} -> {true, Creds}; |
50 |
:-( |
_ -> false |
51 |
|
end; |
52 |
1 |
{error, not_found} -> false |
53 |
|
end. |