telegram.erl 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. -module(telegram).
  2. -include_lib("avz/include/avz.hrl").
  3. -include_lib("nitro/include/nitro.hrl").
  4. -include_lib("kvs/include/user.hrl").
  5. -compile(export_all).
  6. -export(?API).
  7. -define(TL_BOT_NAME, application:get_env(avz, tl_bot, [])).
  8. -define(TL_BOT_TOKEN, application:get_env(avz, tl_bot_token, [])).
  9. -define(TL_AUTH_URL, application:get_env(avz, tl_auth_url, [])).
  10. -define(TL_ACCESS, application:get_env(avz, tl_request_access, "write")).
  11. -define(TL_BTN_SIZE, application:get_env(avz, tl_btn_size, "large")).
  12. -define(TL_BTN_RADIUS, application:get_env(avz, tl_btn_radius, "20")).
  13. -define(TL_USER, [<<"id">>, <<"first_name">>, <<"last_name">>,<<"username">>,<<"auth_date">>, <<"photo_url">>]).
  14. -define(ATTS, #{email => <<"id">>}).
  15. api_event(_,_,_) -> ok.
  16. registration_data(Props, telegram, Ori) ->
  17. Id = proplists:get_value(<<"id">>, Props),
  18. UserName = binary_to_list(proplists:get_value(<<"username">>, Props)),
  19. Email = email_prop(Props,telegram),
  20. Ori#user{ username = re:replace(UserName, "\\.", "_", [{return, list}]),
  21. display_name = proplists:get_value(<<"username">>, Props),
  22. images = avz:update({tl_avatar,proplists:get_value(<<"photo_url">>, Props)},Ori#user.images),
  23. names = proplists:get_value(<<"first_name">>, Props),
  24. email = Email,
  25. surnames = proplists:get_value(<<"last_name">>, Props),
  26. tokens = avz:update({telegram,Id},Ori#user.tokens),
  27. register_date = os:timestamp(),
  28. status = ok }.
  29. index(K) -> maps:get(K, ?ATTS, wf:to_binary(K)).
  30. email_prop(Props, telegram) -> proplists:get_value(maps:get(email,?ATTS), Props).
  31. login_button() ->
  32. #dtl{bind_script=false, file="telegram_login", ext="dtl", bindings=[
  33. {bot, ?TL_BOT_NAME},
  34. {size, ?TL_BTN_SIZE},
  35. {radius, ?TL_BTN_RADIUS},
  36. {auth_url, ?TL_AUTH_URL},
  37. {request_access, ?TL_ACCESS} ]}.
  38. event(E) -> ok.
  39. sdk() -> [].
  40. % HMAC-SHA-256 signature of the data-check-string with the SHA256 hash of the bot's token used as a secret key
  41. callback() ->
  42. Hash = wf:q(<<"hash">>),
  43. Rec = lists:filter(fun({_, undefined}) -> false; (_) -> true end, [ {T, wf:q(T)} || T <- lists:sort(?TL_USER) ]),
  44. Data = lists:join(<<"\n">>, [unicode:characters_to_nfkc_binary([K, <<"=">>, V]) || {K, V} <- Rec]),
  45. case crypto:hmac(sha256, crypto:hash(sha256, ?TL_BOT_TOKEN), Data) of <<X:256/big-unsigned-integer>> ->
  46. case list_to_binary(lists:flatten(io_lib:format("~64.16.0b", [X]))) of
  47. Hash ->
  48. avz:login(telegram, Rec);
  49. _ -> skip
  50. end;
  51. _ -> skip
  52. end.