Guest User

Untitled

a guest
Mar 14th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. -module(ldapc).
  2.  
  3. %% API exports
  4. -export([main/1]).
  5.  
  6. -include_lib("eldap/include/eldap.hrl").
  7.  
  8. %%====================================================================
  9. %% API functions
  10. %%====================================================================
  11. usage() ->
  12. io:format("Usage: ~s <host> <base_dn> <user_grp> ~n", [escript:script_name()]),
  13. halt(1).
  14.  
  15. authenticate(Conn, Login, Password) ->
  16. case eldap:simple_bind(Conn, Login, Password) of
  17. ok ->
  18. ok;
  19. {error, Reason} ->
  20. {error, Reason}
  21. end.
  22.  
  23. mail_or_username_filter(Login) ->
  24. eldap:'or'([
  25. eldap:equalityMatch("userPrincipalName", Login),
  26. eldap:equalityMatch("sAMAccountName", Login)]).
  27.  
  28. belongs_to_group(Conn, Login, GroupDN, BaseDN) ->
  29. SearchOpts = [
  30. {filter, mail_or_username_filter(Login)},
  31. {base, BaseDN },
  32. {scope, wholeSubtree},
  33. {attributes, ["MemberOf"]}
  34. ],
  35. case eldap:search(Conn, SearchOpts) of
  36. {ok, #eldap_search_result{
  37. entries=[#eldap_entry{attributes=Att}|_]}} ->
  38.  
  39. % io:format("Search result: ~p ~n", [Att]),
  40. Groups = proplists:get_value("memberOf", Att),
  41. member_of(Groups, GroupDN);
  42. {error, _Reason} = Err ->
  43. Err
  44. end.
  45.  
  46. member_of0([], _Group) ->
  47. false;
  48. member_of0([H|T], Group) ->
  49. case string:to_lower(H) =:= Group of
  50. true -> true;
  51. false -> member_of0(T, Group)
  52. end.
  53.  
  54. member_of(ListOfGroups, Group, true) ->
  55. member_of0(ListOfGroups, string:to_lower(Group));
  56. member_of(ListOfGroups, Group, false) ->
  57. lists:member(Group, ListOfGroups).
  58.  
  59. member_of(ListOfGroups, Group) ->
  60. member_of(ListOfGroups, Group, false).
  61.  
  62. %% escript Entry point
  63. main([Host, BaseDN, UserGroup]) ->
  64. % io:format("Args: ~p~n", [Args]),
  65.  
  66. Options = [{ssl, false}, {timeout, 5000}],
  67. {ok, Conn} = eldap:open([Host], Options),
  68. % io:format("Connected to server ~n"),
  69.  
  70. {ok, [Login]} = io:fread("Username: ", "~s"),
  71. {ok, [Password]} = io:fread("Password: ", "~s"),
  72. ok = authenticate(Conn, Login, Password),
  73.  
  74. R = belongs_to_group(Conn, Login, UserGroup, BaseDN),
  75. io:format("User [~p] is Authorized to access resources from group [~p] : ~p ~n", [Login, UserGroup, R]),
  76. halt(0);
  77.  
  78. main(_Args) ->
  79. usage().
Add Comment
Please, Sign In to add comment