Jason Xu
Jason Xu

Reputation: 2963

Add Extra Property to Cowboy Request

We used Erlang/Cowboy to develop a simple chatting service based on WebSockets. When user connects in, an authentication would be done based on the URL parameter, and it would return user id or none for the connection.

My stupid question is, how to store the user id into the Request data structure and the user id can be get for later-on processes?

Upvotes: 1

Views: 724

Answers (1)

Tilman
Tilman

Reputation: 2005

If you are using cowboy_rest you can use the handler_state to store your user data after authorization. Something like:

-record(rs_state{user}).
rest_init(Req, Opts) ->
    {ok, Req, #rs_state{}}.

is_authorized(Req, State) ->
    %% authentication code
    {ok, User} = ...
    {true, Req, State#rs_state{user=User}}}.

Upvotes: 6

Related Questions