| 1 |
|
-module(shurbej_ws_login). |
| 2 |
|
|
| 3 |
|
%% Cowboy WebSocket handler for login session notifications. |
| 4 |
|
%% The Zotero client connects to this to get instant loginComplete events. |
| 5 |
|
|
| 6 |
|
-export([init/2, websocket_init/1, websocket_handle/2, websocket_info/2, terminate/3]). |
| 7 |
|
|
| 8 |
|
init(Req, State) -> |
| 9 |
1 |
{cowboy_websocket, Req, State, #{idle_timeout => 600000}}. |
| 10 |
|
|
| 11 |
|
websocket_init(State) -> |
| 12 |
1 |
{ok, State}. |
| 13 |
|
|
| 14 |
|
%% Handle incoming messages from the client. |
| 15 |
|
websocket_handle({text, Msg}, State) -> |
| 16 |
1 |
Decoded = try simdjson:decode(Msg) |
| 17 |
:-( |
catch error:_ -> invalid |
| 18 |
|
end, |
| 19 |
1 |
case Decoded of |
| 20 |
|
#{<<"action">> := <<"subscribe">>, <<"topic">> := <<"login-session:", Token/binary>>} -> |
| 21 |
1 |
shurbej_session:subscribe(Token, self()), |
| 22 |
1 |
Reply = simdjson:encode(#{ |
| 23 |
|
<<"event">> => <<"subscribed">>, |
| 24 |
|
<<"topic">> => <<"login-session:", Token/binary>> |
| 25 |
|
}), |
| 26 |
1 |
{reply, {text, Reply}, State#{token => Token}}; |
| 27 |
|
_ -> |
| 28 |
:-( |
{ok, State} |
| 29 |
|
end; |
| 30 |
|
websocket_handle(_Frame, State) -> |
| 31 |
:-( |
{ok, State}. |
| 32 |
|
|
| 33 |
|
%% Handle messages from the session manager. |
| 34 |
|
websocket_info({session_event, {login_complete, ApiKey, UserInfo}}, State) -> |
| 35 |
1 |
#{user_id := UserId, username := Username} = UserInfo, |
| 36 |
1 |
Reply = simdjson:encode(#{ |
| 37 |
|
<<"event">> => <<"loginComplete">>, |
| 38 |
|
<<"apiKey">> => ApiKey, |
| 39 |
|
<<"userID">> => UserId, |
| 40 |
|
<<"username">> => Username, |
| 41 |
|
<<"displayName">> => maps:get(display_name, UserInfo, Username) |
| 42 |
|
}), |
| 43 |
1 |
{reply, {text, Reply}, State}; |
| 44 |
|
|
| 45 |
|
websocket_info({session_event, login_cancelled}, State) -> |
| 46 |
:-( |
Reply = simdjson:encode(#{<<"event">> => <<"loginCancelled">>}), |
| 47 |
:-( |
{reply, {text, Reply}, State}; |
| 48 |
|
|
| 49 |
|
websocket_info(_Info, State) -> |
| 50 |
:-( |
{ok, State}. |
| 51 |
|
|
| 52 |
|
terminate(_Reason, _Req, _State) -> |
| 53 |
1 |
ok. |