Packages

Session management library for Wisp. Manage user sessions in a simple key-value store.

Current section

Files

Jump to
kv_sessions src kv_sessions@internal@utils.erl
Raw

src/kv_sessions@internal@utils.erl

-module(kv_sessions@internal@utils).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([inject_session_cookie/4, set_session_cookie/4, get_session_id/2, is_session_expired/1]).
-spec inject_session_cookie(
binary(),
gleam@http@request:request(wisp@internal:connection()),
kv_sessions@session:session_id(),
wisp:security()
) -> gleam@http@request:request(wisp@internal:connection()).
inject_session_cookie(Cookie_name, Req, Session_id, Security) ->
Value = kv_sessions@session:id_to_string(Session_id),
Value@1 = case Security of
plain_text ->
gleam_stdlib:bit_array_base64_encode(<<Value/binary>>, false);
signed ->
wisp:sign_message(Req, <<Value/binary>>, sha512)
end,
_pipe = Req,
_pipe@1 = gleam@http@request:remove_cookie(_pipe, Cookie_name),
gleam@http@request:set_cookie(_pipe@1, Cookie_name, Value@1).
-spec seconds_from_now(
{{integer(), integer(), integer()}, {integer(), integer(), integer()}}
) -> integer().
seconds_from_now(Time) ->
_pipe = Time,
_pipe@1 = birl:from_erlang_universal_datetime(_pipe),
_pipe@2 = birl:difference(_pipe@1, birl:now()),
birl@duration:blur_to(_pipe@2, second).
-spec set_session_cookie(
binary(),
gleam@http@response:response(wisp:body()),
gleam@http@request:request(wisp@internal:connection()),
kv_sessions@session:session()
) -> gleam@http@response:response(wisp:body()).
set_session_cookie(Cookie_name, Response, Req, Session) ->
wisp:set_cookie(
Response,
Req,
Cookie_name,
kv_sessions@session:id_to_string(erlang:element(2, Session)),
signed,
seconds_from_now(erlang:element(3, Session))
).
-spec get_session_id(
binary(),
gleam@http@request:request(wisp@internal:connection())
) -> {ok, kv_sessions@session:session_id()} |
{error, kv_sessions@session:session_error()}.
get_session_id(Cookie_name, Req) ->
_pipe = wisp:get_cookie(Req, Cookie_name, signed),
_pipe@1 = gleam@result:replace_error(_pipe, no_session_error),
gleam@result:map(_pipe@1, fun kv_sessions@session:id_from_string/1).
-spec is_session_expired(kv_sessions@session:session()) -> boolean().
is_session_expired(Session) ->
Expiry = birl:from_erlang_universal_datetime(erlang:element(3, Session)),
case birl:compare(birl:now(), Expiry) of
gt ->
true;
_ ->
false
end.