Skip to content

Instantly share code, notes, and snippets.

@etrepum
Forked from llaisdy/gist.erl
Created May 9, 2013 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etrepum/5549787 to your computer and use it in GitHub Desktop.
Save etrepum/5549787 to your computer and use it in GitHub Desktop.
-module(gist).
-export([authenticate/3]).
authenticate(UserName, Pass, IPAddress) ->
Checks = [fun user_ok/1,
fun password_ok/1,
fun ipaddr_ok/1
],
{Result, _} = lists:foldl(
fun(_CheckFun, {{error, Reason}, _}) ->
{{error, Reason}, undef};
(CheckFun, {ok, Context}) ->
{CheckFun(Context), Context}
end,
{ok, {UserName, Pass, IPAddress}},
Checks),
Result.
user_ok({UserName, _, _}) ->
case ext__user_exists(UserName) of
false ->
{error, user_not_found};
true ->
ok
end.
password_ok({UserName, Pass, _}) ->
case ext__user_pass_match(UserName, Pass) of
false ->
{error, password_incorrect};
true ->
ok
end.
ipaddr_ok({UserName, _, IPAddress}) ->
case ext__user_has_ip(UserName, IPAddress) of
false ->
{error, ipaddress_incorrect};
true ->
ok
end.
%%%% ext
ext__user_exists(groucho) ->
true;
ext__user_exists(_) ->
false.
ext__user_pass_match(groucho, julius) ->
true;
ext__user_pass_match(_, _) ->
false.
ext__user_has_ip(groucho, '123.45.67.89') ->
true;
ext__user_has_ip(_, _) ->
false.
%%%% example usage
%
% 2> gist:authenticate(groucho, julius, '123.45.67.89').
% ok
%
% 3> gist:authenticate(chico, julius, '123.45.67.89').
% {error,user_not_found}
%
% 4> gist:authenticate(groucho, rabbit, '123.45.67.89').
% {error,password_incorrect}
%
% 5> gist:authenticate(groucho, julius, '123.145.67.89').
% {error,ipaddress_incorrect}
%%%% caveats
%
% the foldl in authenticate should be abstracted as a utility function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment