From 3b9693e276538ec8823307f2b54dcb2e9fbe4d17 Mon Sep 17 00:00:00 2001 From: absc Date: Wed, 7 Aug 2024 20:22:45 +0000 Subject: [PATCH] Properly set the cookie validity, and return it to the caller along with the cookie itself. --- dudeswave/src/dudeswave_auth.erl | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/dudeswave/src/dudeswave_auth.erl b/dudeswave/src/dudeswave_auth.erl index 176d698..815292b 100644 --- a/dudeswave/src/dudeswave_auth.erl +++ b/dudeswave/src/dudeswave_auth.erl @@ -22,6 +22,7 @@ from the dudeswave database. """. -define(RANDBYTES, 32). +-define(DEFVALIDITY, 365). -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}`, 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(), Password :: binary(), Cookies :: atom(), Bucket :: atom(), Cookie :: binary(), + Validity :: non_neg_integer(), Reason :: term(). authenticate(User, Password, Cookies, Bucket) -> case storage:read(Bucket, User) of {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, Salt} = lists:keyfind(salt, 1, R#object.metadata), Auth = crypto:hash(sha256, <>), + if Auth =:= Hash -> Cookie = base64:encode(rand:bytes(64)), - Until = calendar:now_to_universal_time(erlang:timestamp()), - case storage:write(Cookies, <>, User, [{until, Until}]) of - ok -> {true, Cookie}; + case storage:write(Cookies, <>, User, [{until, Validity}]) of + ok -> {true, Cookie, Validity}; {error, Reason} -> {error, Reason} end; true -> false