-module(glome@core@authentication). -compile(no_auto_import). -export([authenticate/2]). -export_type([access_token/0]). -type access_token() :: {access_token, binary()}. -spec authenticate(nerf@websocket:connection(), access_token()) -> {ok, binary()} | {error, glome@core@error:glome_error()}. authenticate(Connection, Access_token) -> case authentication_phase_started(Connection) of {error, _try} -> {error, _try}; {ok, _@1} -> Auth_message = glome@core@json:encode( [glome@core@json:json_element(<<"type"/utf8>>, <<"auth"/utf8>>), glome@core@json:json_element( <<"access_token"/utf8>>, erlang:element(2, Access_token) )] ), nerf@websocket:send(Connection, Auth_message), case begin _pipe = nerf@websocket:'receive'(Connection, 500), gleam@result:map_error( _pipe, fun(_) -> {authentication_error, <<"authentication failed! Auth result message not received!"/utf8>>} end ) end of {error, _try@1} -> {error, _try@1}; {ok, {text, Auth_response}} -> case begin _pipe@1 = glome@core@json:string_field( Auth_response, <<"type"/utf8>> ), gleam@result:map_error( _pipe@1, fun(_) -> {authentication_error, <<"authentication failed! Auth result message has no field [ type ]!"/utf8>>} end ) end of {error, _try@2} -> {error, _try@2}; {ok, Type_field} -> case Type_field of <<"auth_ok"/utf8>> -> {ok, <<"Authenticated connection established"/utf8>>}; <<"auth_invalid"/utf8>> -> {error, {authentication_error, <<"Invalid authentication"/utf8>>}} end end end end. -spec authentication_phase_started(nerf@websocket:connection()) -> {ok, binary()} | {error, glome@core@error:glome_error()}. authentication_phase_started(Connection) -> case begin _pipe = nerf@websocket:'receive'(Connection, 500), gleam@result:map_error( _pipe, fun(_) -> {authentication_error, <<"could not start auth phase! Auth message not received!"/utf8>>} end ) end of {error, _try} -> {error, _try}; {ok, {text, Initial_message}} -> case begin _pipe@1 = glome@core@json:string_field( Initial_message, <<"type"/utf8>> ), gleam@result:map_error( _pipe@1, fun(_) -> {authentication_error, <<"could not start auth phase! Auth message has no field [ type ]!"/utf8>>} end ) end of {error, _try@1} -> {error, _try@1}; {ok, Auth_required} -> case Auth_required of <<"auth_required"/utf8>> -> {ok, Auth_required}; _@1 -> {error, {authentication_error, <<"Something went wrong. Authentication phase not started!"/utf8>>}} end end end.