Abstract cookie handling.

main
absc 2024-08-15 21:00:06 +00:00
parent a0cbc962d1
commit dac21c4537
2 changed files with 31 additions and 9 deletions

View File

@ -25,7 +25,7 @@ from the dudeswave database.
-include_lib("storage/include/storage.hrl").
-export([authenticate/2, details/1, new/3,
update/4, delete/1, logout/2]).
update/4, delete/1, logout/2, auth_cookies/1]).
-doc """
Verify a session with an existing cookie.
@ -242,3 +242,26 @@ delete(User) ->
% here. For that, we need to add at least another
% API to the storage layer.
storage:delete(?USERSBUCK, User).
-doc """
Get the authentication cookies from a cowboy request.
Spec:
```
-spec auth_cookies(Req) -> {User, Cookie} when
Req :: cowboy_req:req(),
User :: binary(),
Cookie :: binary().
```
""".
-spec auth_cookies(Req) -> {User, Cookie} when
Req :: cowboy_req:req(),
User :: binary(),
Cookie :: binary().
auth_cookies(Req) ->
#{dudeauth := Cookie, dudename := User} = cowboy_req:match_cookies([dudeauth,
dudename], Req),
{User, Cookie}.

View File

@ -145,8 +145,7 @@ forbidden(Req, State) ->
<<"PUT">> ->
{false, Req, State};
_ ->
#{dudeauth := Auth, dudename := User} = cowboy_req:match_cookies([dudeauth,
dudename], Req),
{User, Auth} = dudeswave_auth:auth_cookies(Req),
case dudeswave_auth:authenticate(User, {cookie, Auth}) of
{error, service_unavailable} ->
@ -178,7 +177,7 @@ content_types_accepted(Req, State) ->
end.
resource_exists(Req, State) ->
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{User, _} = dudeswave_auth:auth_cookies(Req),
case dudeswave_auth:details(User) of
[] -> {false, Req, State};
@ -202,7 +201,7 @@ is_conflict(Req, State) -> {false, Req, State}.
allow_missing_post(Req, State) -> {false, Req, State}.
delete_resource(Req, State) ->
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{User, _} = dudeswave_auth:auth_cookies(Req),
case dudeswave_auth:delete(User) of
ok -> {true, Req, State};
@ -216,7 +215,7 @@ delete_completed(Req, State) -> {true, Req, State}.
%
create_user(Req, State) ->
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{User, _} = dudeswave_auth:auth_cookies(Req),
{ok, Data, Req0} = cowboy_req:read_body(Req),
#{<<"password">> := Pass, <<"email">> := Email} = json:decode(Data),
@ -227,7 +226,7 @@ create_user(Req, State) ->
end.
modify_user(Req, State) ->
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{User, _} = dudeswave_auth:auth_cookies(Req),
{ok, Data, Req0} = cowboy_req:read_body(Req),
#{<<"email">> := Email, <<"description">> := Desc,
@ -239,8 +238,8 @@ modify_user(Req, State) ->
end.
user_details(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req),
#{details := Details} = State,
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
Data = Details#{user => User},
{iolist_to_binary(json:encode(Data)), Req, State}.