Properly set the cookie validity, and return it to the

caller along with the cookie itself.
main
absc 2024-08-07 20:22:45 +00:00
parent 9bf0e3609a
commit 3b9693e276
1 changed files with 14 additions and 4 deletions

View File

@ -22,6 +22,7 @@ from the dudeswave database.
""". """.
-define(RANDBYTES, 32). -define(RANDBYTES, 32).
-define(DEFVALIDITY, 365).
-include_lib("storage/include/storage.hrl"). -include_lib("storage/include/storage.hrl").
@ -88,26 +89,35 @@ If the authentication is successful, a new cookie is generated and stored in
the `Cookies` bucket. The cookie is returned to the caller in a tuple `{true, Cookie}`, the `Cookies` bucket. The cookie is returned to the caller in a tuple `{true, Cookie}`,
otherwise `false` is returned and the authentication is denied. otherwise `false` is returned and the authentication is denied.
""". """.
-spec authenticate(User, Password, Cookies, Bucket) -> {true, Cookie} | false | {error, Reason} when -spec authenticate(User, Password, Cookies, Bucket) -> {true, Cookie, Validity} |
false | {error, Reason} when
User :: binary(), User :: binary(),
Password :: binary(), Password :: binary(),
Cookies :: atom(), Cookies :: atom(),
Bucket :: atom(), Bucket :: atom(),
Cookie :: binary(), Cookie :: binary(),
Validity :: non_neg_integer(),
Reason :: term(). Reason :: term().
authenticate(User, Password, Cookies, Bucket) -> authenticate(User, Password, Cookies, Bucket) ->
case storage:read(Bucket, User) of case storage:read(Bucket, User) of
{ok, [R]} -> {ok, [R]} ->
Validity = case application:get_env(cookie_validity) of
{ok, Value} ->
erlang:system_time(seconds) + Value * 86400;
undefined ->
erlang:system_time(seconds) + ?DEFVALIDITY * 86400
end,
{ok, Hash} = lists:keyfind(hash, 1, R#object.metadata), {ok, Hash} = lists:keyfind(hash, 1, R#object.metadata),
{ok, Salt} = lists:keyfind(salt, 1, R#object.metadata), {ok, Salt} = lists:keyfind(salt, 1, R#object.metadata),
Auth = crypto:hash(sha256, <<Password/binary, Salt/binary>>), Auth = crypto:hash(sha256, <<Password/binary, Salt/binary>>),
if if
Auth =:= Hash -> Auth =:= Hash ->
Cookie = base64:encode(rand:bytes(64)), Cookie = base64:encode(rand:bytes(64)),
Until = calendar:now_to_universal_time(erlang:timestamp()), case storage:write(Cookies, <<Cookie/binary>>, User, [{until, Validity}]) of
case storage:write(Cookies, <<Cookie/binary>>, User, [{until, Until}]) of ok -> {true, Cookie, Validity};
ok -> {true, Cookie};
{error, Reason} -> {error, Reason} {error, Reason} -> {error, Reason}
end; end;
true -> false true -> false