Compare commits

..

No commits in common. "38d8e297343ea8176d1997e3d856a05276a53f90" and "e7e34d78d6a5771cbacf0e6062ecc655fe4f7685" have entirely different histories.

6 changed files with 136 additions and 152 deletions

View File

@ -3,8 +3,6 @@
ERLC?= erlc -server ERLC?= erlc -server
ERLOPTS= -I ../../
OBJS= dudeswave.beam dudeswave_app.beam OBJS= dudeswave.beam dudeswave_app.beam
OBJS+= dudeswave_supervisor.beam dudeswave_handler.beam OBJS+= dudeswave_supervisor.beam dudeswave_handler.beam
OBJS+= dudeswave_user_handler.beam dudeswave_auth.beam OBJS+= dudeswave_user_handler.beam dudeswave_auth.beam

View File

@ -18,7 +18,9 @@
-export([bootstrap/3, start/2, stop/1]). -export([bootstrap/3, start/2, stop/1]).
-include_lib("dudeswave/include/defines.hrl"). -define(APPBUCK, dudeswave).
-define(USERSBUCK, dudes).
-define(COOKIESBUCK, cookies).
start(_Type, StartArgs) -> start(_Type, StartArgs) ->
crypto:rand_seed(), crypto:rand_seed(),
@ -38,8 +40,9 @@ start(_Type, StartArgs) ->
Dispatch = cowboy_router:compile([ Dispatch = cowboy_router:compile([
{'_', [ {'_', [
{"/api/v1/user", dudeswave_user_handler, #{}}, {"/api/v1/user", dudeswave_user_handler, #{bucket => ?USERSBUCK,
{"/", dudeswave_handler, #{}} cookies => ?COOKIESBUCK}},
{"/", dudeswave_handler, #{bucket => ?APPBUCK}}
]} ]}
]), ]),

View File

@ -21,12 +21,13 @@ Here lives all the functions needed to create, update and delete users
from the dudeswave database. from the dudeswave database.
""". """.
-include_lib("dudeswave/include/defines.hrl"). -define(RANDBYTES, 32).
-define(DEFVALIDITY, 365).
-include_lib("storage/include/storage.hrl"). -include_lib("storage/include/storage.hrl").
-export([authenticate/2, details/1, new/3, -export([authenticate/3, authenticate/4, details/2, new/4,
update/4, delete/1, logout/2, auth_cookies/1, invalidate_cookies/1, update/5, delete/2, logout/3]).
set_auth_cookies/4]).
-doc """ -doc """
Verify a session with an existing cookie. Verify a session with an existing cookie.
@ -34,27 +35,24 @@ Verify a session with an existing cookie.
Spec: Spec:
``` ```
-spec authenticate(User, Auth) -> true | false | {true, Cookie, Validity} | {error, Reason} when -spec authenticate(User, Cookie, Bucket) -> true | false | {error, Reason} when
User :: binary(), User :: binary(),
Auth :: {cookie, binary()} | {password, binary()}, Cookie :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
``` ```
Authenticate a user with either an existing `Cookie` or by issuing a new one Check against che `Bucket` table, containing the list of current cookies,
after authenticating with `Password`. if `Cookie` is still valid to authenticate `User` session.
If `Cookie` is valid, the function returns `true`. If the authentication is denied
returns `false`
""". """.
-spec authenticate(User, Auth) -> true | false | {true, Cookie, Validity} | {error, Reason} when -spec authenticate(User, Cookie, Bucket) -> true | false | {error, Reason} when
User :: binary(), User :: binary(),
Auth :: {cookie, binary()} | {password, binary()},
Cookie :: binary(), Cookie :: binary(),
Validity :: pos_integer(), Bucket :: atom(),
Reason :: term(). Reason :: term().
authenticate(User, {cookie, Cookie}) -> authenticate(User, Cookie, Bucket) ->
case storage:read(?COOKIESBUCK, Cookie) of case storage:read(Bucket, Cookie) of
{ok, [R]} -> {ok, [R]} ->
CurTime = calendar:now_to_universal_time(erlang:timestamp()), CurTime = calendar:now_to_universal_time(erlang:timestamp()),
CookieTime = R#object.value, CookieTime = R#object.value,
@ -70,10 +68,43 @@ authenticate(User, {cookie, Cookie}) ->
end; end;
{ok, []} -> false; {ok, []} -> false;
{error, _} -> {error, service_unavailable} {error, _} -> {error, service_unavailable}
end; end.
authenticate(User, {password, Password}) -> -doc """
case storage:read(?USERSBUCK, User) of Authenticate a user and return a new cookie for the new session.
Spec:
```
-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` with `Password`, reading the user's details from `Bucket`.
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, 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]} -> {ok, [R]} ->
Validity = case application:get_env(cookie_validity) of Validity = case application:get_env(cookie_validity) of
{ok, Value} -> {ok, Value} ->
@ -89,8 +120,7 @@ authenticate(User, {password, Password}) ->
if if
Auth =:= Hash -> Auth =:= Hash ->
Cookie = base64:encode(rand:bytes(64)), Cookie = base64:encode(rand:bytes(64)),
case storage:write(?COOKIESBUCK, <<Cookie/binary>>, case storage:write(Cookies, <<Cookie/binary>>, Validity, [{user, User}]) of
Validity, [{user, User}]) of
ok -> {true, Cookie, Validity}; ok -> {true, Cookie, Validity};
{error, Reason} -> {error, Reason} {error, Reason} -> {error, Reason}
end; end;
@ -106,24 +136,26 @@ Close an existing session
Spec: Spec:
``` ```
-spec logout(User, Cookie) -> ok | {error, Reason} when -spec logout(User, Cookie, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Cookie :: binary(), Cookie :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
``` ```
Invalidate and delete `Cookie` associated with `User` from the system. Invalidate and delete `Cookie` associated with `User` from the system.
""". """.
-spec logout(User, Cookie) -> ok | {error, Reason} when -spec logout(User, Cookie, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Cookie :: binary(), Cookie :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
logout(User, Cookie) -> logout(User, Cookie, Bucket) ->
case storage:read(?COOKIESBUCK, Cookie) of case storage:read(Bucket, Cookie) of
{ok, [R]} -> {ok, [R]} ->
{user, User} = lists:keyfind(user, 1, R#object.metadata), {user, User} = lists:keyfind(user, 1, R#object.metadata),
storage:delete(?COOKIESBUCK, Cookie); storage:delete(Bucket, Cookie);
{ok, []} -> {ok, []} ->
{error, not_found}; {error, not_found};
{error, Reason} -> {error, Reason} ->
@ -136,19 +168,21 @@ Return user details.
Spec: Spec:
``` ```
-spec details(User) -> Value | {error, Reason} when -spec details(User, Bucket) -> Value | {error, Reason} when
User :: binary(), User :: binary(),
Bucket :: atom(),
Value :: term(), Value :: term(),
Reason :: term(). Reason :: term().
``` ```
""". """.
-spec details(User) -> Value | {error, Reason} when -spec details(User, Bucket) -> Value | {error, Reason} when
User :: binary(), User :: binary(),
Bucket :: atom(),
Value :: term(), Value :: term(),
Reason :: term(). Reason :: term().
details(User) -> details(User, Bucket) ->
case storage:read(?USERSBUCK, User) of case storage:read(Bucket, User) of
{ok, [R]} -> R#object.value; {ok, [R]} -> R#object.value;
{error, Reason} -> {error, Reason}; {error, Reason} -> {error, Reason};
{ok, []} -> {error, not_found} {ok, []} -> {error, not_found}
@ -160,33 +194,35 @@ Create a new user.
Spec: Spec:
``` ```
-spec new(User, Password, Email) -> ok | {error, Reason} when -spec new(User, Password, Email, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Password :: binary(), Password :: binary(),
Email :: binary(), Email :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
``` ```
The `User` is created, and stored in the application's users bucket The `User` is added to `Bucket`, that is, the users bucket for the application.
`Password` is salted and hashed with SHA256 before being stored. `Password` is salted and hashed with SHA256 before being stored.
The new user is saved with a metadata `status` of `waiting_confirmation`, The new user is saved with a metadata `status` of `waiting_confirmation`,
based on the application settings, the confirmation method may vary. based on the application settings, the confirmation method may vary.
""". """.
-spec new(User, Password, Email) -> ok | {error, Reason} when -spec new(User, Password, Email, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Password :: binary(), Password :: binary(),
Email :: binary(), Email :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
new(User, Password, Email) -> new(User, Password, Email, Bucket) ->
Salt = rand:bytes(?RANDBYTES), Salt = rand:bytes(?RANDBYTES),
Hash = crypto:hash(sha256, <<Password/binary, Salt/binary>>), Hash = crypto:hash(sha256, <<Password/binary, Salt/binary>>),
Data = #{<<"email">> => Email}, Data = #{<<"email">> => Email},
Metadata = [{salt, Salt}, {hash, Hash}, {status, waiting_confirmation}], Metadata = [{salt, Salt}, {hash, Hash}, {status, waiting_confirmation}],
storage:write(?USERSBUCK, User, Data, Metadata). storage:write(Bucket, User, Data, Metadata).
-doc """ -doc """
Update user's details Update user's details
@ -194,11 +230,12 @@ Update user's details
Spec: Spec:
``` ```
-spec update(User, Name, Email, Desc) -> ok | {error, Reason} when -spec update(User, Name, Email, Desc, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Name :: binary(), Name :: binary(),
Email :: binary(), Email :: binary(),
Desc :: binary(), Desc :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
``` ```
@ -206,15 +243,16 @@ The details apart from `User` are updated. The username itself is immutable
and cannot be modified. All the other fields, excluding the e-mail, are the and cannot be modified. All the other fields, excluding the e-mail, are the
ones that can be seen in the public page. ones that can be seen in the public page.
""". """.
-spec update(User, Name, Email, Desc) -> ok | {error, Reason} when -spec update(User, Name, Email, Desc, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Name :: binary(), Name :: binary(),
Email :: binary(), Email :: binary(),
Desc :: binary(), Desc :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
update(User, Name, Email, Desc) -> update(User, Name, Email, Desc, Bucket) ->
{ok, CurData, Metadata} = case storage:read(?USERSBUCK, User) of {ok, CurData, Metadata} = case storage:read(Bucket, User) of
{ok, [R]} -> {ok, [R]} ->
{ok, R#object.value, R#object.metadata}; {ok, R#object.value, R#object.metadata};
{error, Reason} -> {error, Reason} {error, Reason} -> {error, Reason}
@ -223,103 +261,25 @@ update(User, Name, Email, Desc) ->
Data = CurData#{<<"email">> => Email, <<"name">> => Name, Data = CurData#{<<"email">> => Email, <<"name">> => Name,
<<"description">> => Desc}, <<"description">> => Desc},
storage:write(?USERSBUCK, User, Data, Metadata). storage:write(Bucket, User, Data, Metadata).
-doc """ -doc """
Delete an existing user from the database. Delete an existing user from the database.
``` ```
-spec delete(User) -> ok | {error, Reason} when -spec delete(User, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
``` ```
""". """.
-spec delete(User) -> ok | {error, Reason} when -spec delete(User, Bucket) -> ok | {error, Reason} when
User :: binary(), User :: binary(),
Bucket :: atom(),
Reason :: term(). Reason :: term().
delete(User) -> delete(User, Bucket) ->
% We are missing the cleanup of the cookies % We are missing the cleanup of the cookies
% here. For that, we need to add at least another % here. For that, we need to add at least another
% API to the storage layer. % API to the storage layer.
storage:delete(?USERSBUCK, User). storage:delete(Bucket, 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}.
-doc """
Invalidate the cookies in the passed request.
Spec:
```
-spec invalidate_cookies(Req) -> Req0 when
Req :: cowboy_req:req(),
Req0 :: cowboy_req:req().
```
A new request `Req0` is returned to the caller with the cookies zeroed and
completely invalidated.
""".
-spec invalidate_cookies(Req) -> Req0 when
Req :: cowboy_req:req(),
Req0 :: cowboy_req:req().
invalidate_cookies(Req) ->
Req0 = cowboy_req:set_resp_cookie(<<"dudeauth">>, <<"">>, Req,
#{max_age => 0}),
Req1 = cowboy_req:set_resp_cookie(<<"dudename">>, <<"">>, Req0,
#{max_age => 0}),
Req1.
-doc """
Set the authentication cookies for the provided clien request
Spec:
```
-spec set_auth_cookies(Req, User, Cookie, Validity) -> Req0 when
Req :: cowboy_req:req(),
User :: binary(),
Cookie :: binary(),
Validity :: pos_integer(),
Req0 :: cowboy_req:req().
```
A new request object `Req0`is returned, with the user and auth cookies set.
""".
-spec set_auth_cookies(Req, User, Cookie, Validity) -> Req0 when
Req :: cowboy_req:req(),
User :: binary(),
Cookie :: binary(),
Validity :: pos_integer(),
Req0 :: cowboy_req:req().
set_auth_cookies(Req, User, Cookie, Validity) ->
Req0 = cowboy_req:set_resp_cookie(<<"dudeauth">>, Cookie, Req,
#{max_age => Validity}),
Req1 = cowboy_req:set_resp_cookie(<<"dudename">>, User, Req0,
#{max_age => Validity}),
Req1.

View File

@ -94,9 +94,11 @@ forbidden(Req, State) ->
<<"POST">> -> <<"POST">> ->
{false, Req, State}; {false, Req, State};
_ -> _ ->
{User, Auth} = dudeswave_auth:auth_cookies(Req), #{dudeauth := Auth, dudename := User} = cowboy_req:match_cookies([dudeauth,
dudename], Req),
{ok, Bucket} = maps:find(cookies, State),
case dudeswave_auth:authenticate(User, {cookie, Auth}) of case dudeswave_auth:authenticate(User, Auth, Bucket) of
{error, service_unavailable} -> exit(service_unavailable); {error, service_unavailable} -> exit(service_unavailable);
true -> {false, Req, State}; true -> {false, Req, State};
false -> {true, Req, State} false -> {true, Req, State}
@ -112,14 +114,16 @@ content_types_accepted(Req, State) ->
end. end.
resource_exists(Req, State) -> resource_exists(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req), #{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{ok, Bucket} = maps:find(bucket, State),
case dudeswave_auth:details(User) of case dudeswave_auth:details(User, Bucket) of
[] -> [] ->
{false, Req, State}; {false, Req, State};
{error, Reason} -> exit(Reason); {error, Reason} -> exit(Reason);
_ -> _ ->
NewState = State#{ NewState = State#{
bucket => Bucket,
user_exists => true user_exists => true
}, },
{true, Req, NewState} {true, Req, NewState}
@ -135,13 +139,18 @@ is_conflict(Req, State) -> {true, Req, State}.
allow_missing_post(Req, State) -> {false, Req, State}. allow_missing_post(Req, State) -> {false, Req, State}.
delete_resource(Req, State) -> delete_resource(Req, State) ->
{User, Auth} = dudeswave_auth:auth_cookies(Req), {ok, Bucket} = maps:find(bucket, State),
#{dudename := User, dudeauth := Auth} = cowboy_req:match_cookies([dudename,
dudeauth], Req),
case dudeswave_auth:logout(User, Auth) of case dudeswave_auth:logout(User, Auth, Bucket) of
ok -> ok ->
{true, dudeswave_auth:invalidate_cookies(Req), State}; Req0 = cowboy_req:set_resp_cookie(<<"dudeauth">>, Auth, Req,
{error, _} -> #{max_age => 0}),
{false, Req, State} Req1 = cowboy_req:set_resp_cookie(<<"dudename">>, User, Req0,
#{max_age => 0}),
{true, Req1, State};
{error, _} -> {false, Req, State}
end. end.
delete_completed(Req, State) -> {false, Req, State}. delete_completed(Req, State) -> {false, Req, State}.
@ -151,12 +160,19 @@ delete_completed(Req, State) -> {false, Req, State}.
% %
login(Req, State) -> login(Req, State) ->
{ok, Cookies} = maps:find(cookies, State),
{ok, Bucket} = maps:find(bucket, State),
{ok, Data, Req0} = cowboy_req:read_body(Req), {ok, Data, Req0} = cowboy_req:read_body(Req),
#{<<"user">> := User, <<"password">> := Pass} = json:decode(Data), #{<<"user">> := User, <<"password">> := Pass} = json:decode(Data),
case dudeswave_auth:authenticate(User, {password, Pass}) of case dudeswave_auth:authenticate(User, Pass, Cookies, Bucket) of
{true, Cookie, Validity} -> {true, Cookie, Validity} ->
{true, dudeswave_auth:set_auth_cookies(Req, User, Cookie, Validity), State}; Req1 = cowboy_req:set_resp_cookie(<<"dudeauth">>, Cookie, Req0,
#{max_age => Validity}),
Req2 = cowboy_req:set_resp_cookie(<<"dudename">>, User, Req1,
#{max_age => Validity}),
{true, Req2, State};
false -> false ->
{false, Req0, State}; {false, Req0, State};
{error, _} -> {error, _} ->

View File

@ -145,9 +145,11 @@ forbidden(Req, State) ->
<<"PUT">> -> <<"PUT">> ->
{false, Req, State}; {false, Req, State};
_ -> _ ->
{User, Auth} = dudeswave_auth:auth_cookies(Req), #{dudeauth := Auth, dudename := User} = cowboy_req:match_cookies([dudeauth,
dudename], Req),
{ok, Bucket} = maps:find(cookies, State),
case dudeswave_auth:authenticate(User, {cookie, Auth}) of case dudeswave_auth:authenticate(User, Auth, Bucket) of
{error, service_unavailable} -> {error, service_unavailable} ->
{true, Req, State}; {true, Req, State};
true -> true ->
@ -177,13 +179,15 @@ content_types_accepted(Req, State) ->
end. end.
resource_exists(Req, State) -> resource_exists(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req), #{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{ok, Bucket} = maps:find(bucket, State),
case dudeswave_auth:details(User) of case dudeswave_auth:details(User, Bucket) of
[] -> {false, Req, State}; [] -> {false, Req, State};
{error, _} -> {false, Req, State}; {error, _} -> {false, Req, State};
Details -> Details ->
NewState = State#{ NewState = State#{
bucket => Bucket,
details => Details, details => Details,
user_exists => true, user_exists => true,
request => cowboy_req:method(Req) request => cowboy_req:method(Req)
@ -201,9 +205,10 @@ is_conflict(Req, State) -> {false, Req, State}.
allow_missing_post(Req, State) -> {false, Req, State}. allow_missing_post(Req, State) -> {false, Req, State}.
delete_resource(Req, State) -> delete_resource(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req), {ok, Bucket} = maps:find(bucket, State),
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
case dudeswave_auth:delete(User) of case dudeswave_auth:delete(User, Bucket) of
ok -> {true, Req, State}; ok -> {true, Req, State};
{error, _} -> {false, Req, State} {error, _} -> {false, Req, State}
end. end.
@ -215,31 +220,33 @@ delete_completed(Req, State) -> {true, Req, State}.
% %
create_user(Req, State) -> create_user(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req), {ok, Bucket} = maps:find(bucket, State),
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{ok, Data, Req0} = cowboy_req:read_body(Req), {ok, Data, Req0} = cowboy_req:read_body(Req),
#{<<"password">> := Pass, <<"email">> := Email} = json:decode(Data), #{<<"password">> := Pass, <<"email">> := Email} = json:decode(Data),
case dudeswave_auth:new(User, Pass, Email) of case dudeswave_auth:new(User, Pass, Email, Bucket) of
ok -> {true, Req0, []}; ok -> {true, Req0, []};
{error, _} -> {false, Req0, State} {error, _} -> {false, Req0, State}
end. end.
modify_user(Req, State) -> modify_user(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req), {ok, Bucket} = maps:find(bucket, State),
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
{ok, Data, Req0} = cowboy_req:read_body(Req), {ok, Data, Req0} = cowboy_req:read_body(Req),
#{<<"email">> := Email, <<"description">> := Desc, #{<<"email">> := Email, <<"description">> := Desc,
<<"name">> := Name} = json:decode(Data), <<"name">> := Name} = json:decode(Data),
case dudeswave_auth:update(User, Name, Email, Desc) of case dudeswave_auth:update(User, Name, Email, Desc, Bucket) of
ok -> {true, Req0, []}; ok -> {true, Req0, []};
{error, _} -> {false, Req0, State} {error, _} -> {false, Req0, State}
end. end.
user_details(Req, State) -> user_details(Req, State) ->
{User, _} = dudeswave_auth:auth_cookies(Req),
#{details := Details} = State, #{details := Details} = State,
#{dudename := User} = cowboy_req:match_cookies([dudename], Req),
Data = Details#{user => User}, Data = Details#{user => User},
{iolist_to_binary(json:encode(Data)), Req, State}. {iolist_to_binary(json:encode(Data)), Req, State}.

View File

@ -3,7 +3,7 @@
ERLC?= erlc -server ERLC?= erlc -server
ERLOPTS+= -I ../../ ERLOPTS+= -I ../include
OBJS= storage.beam storage_app.beam OBJS= storage.beam storage_app.beam