1 |
|
-module(cyrsasl_oauth). |
2 |
|
-author('adrian.stachurski@erlang-solutions.com'). |
3 |
|
|
4 |
|
-export([mechanism/0, mech_new/3, mech_step/2]). |
5 |
|
|
6 |
|
-ignore_xref([mech_new/3]). |
7 |
|
|
8 |
|
-behaviour(cyrsasl). |
9 |
|
|
10 |
|
-record(state, {creds}). |
11 |
|
|
12 |
|
-spec mechanism() -> cyrsasl:mechanism(). |
13 |
|
mechanism() -> |
14 |
6174 |
<<"X-OAUTH">>. |
15 |
|
|
16 |
|
-spec mech_new(Host :: jid:server(), |
17 |
|
Creds :: mongoose_credentials:t(), |
18 |
|
Socket :: term()) -> {ok, tuple()}. |
19 |
|
mech_new(_Host, Creds, _Socket) -> |
20 |
7 |
{ok, #state{creds = Creds}}. |
21 |
|
|
22 |
|
-spec mech_step(State :: tuple(), |
23 |
|
ClientIn :: binary()) -> {ok, mongoose_credentials:t()} |
24 |
|
| {error, binary()}. |
25 |
|
mech_step(#state{creds = Creds}, SerializedToken) -> |
26 |
|
%% SerializedToken is a token decoded from CDATA <auth/> body sent by client |
27 |
7 |
HostType = mongoose_credentials:host_type(Creds), |
28 |
7 |
case mod_auth_token:authenticate(HostType, SerializedToken) of |
29 |
|
% Validating access token |
30 |
|
{ok, AuthModule, User} -> |
31 |
2 |
{ok, mongoose_credentials:extend(Creds, |
32 |
|
[{username, User}, |
33 |
|
{auth_module, AuthModule}])}; |
34 |
|
% Validating refresh token and returning new tokens |
35 |
|
{ok, AuthModule, User, AccessToken} -> |
36 |
2 |
{ok, mongoose_credentials:extend(Creds, |
37 |
|
[{username, User}, |
38 |
|
{auth_module, AuthModule}, |
39 |
|
{sasl_success_response, AccessToken}])}; |
40 |
|
{error, {Username, _}} -> |
41 |
2 |
{error, <<"not-authorized">>, Username}; |
42 |
|
{error, _Reason} -> |
43 |
1 |
{error, <<"not-authorized">>} |
44 |
|
end. |